blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
ef860663a0e5a3f6a904927c60dc7cd9396a82d8
da13476293be1a3f3fe011b64d0c22fe22053930
/搓排.cpp
800dd402f2254360dfe662e5887c90e4a121a7df
[]
no_license
dongZheX/Coding
4138bccbc3683329f7571b2cac56180f8d8399b3
6be5f801876b28b5abd574d98995b893e39e3279
refs/heads/master
2020-07-11T18:40:45.172457
2019-08-27T04:02:58
2019-08-27T04:02:58
204,617,001
1
0
null
null
null
null
GB18030
C++
false
false
433
cpp
#include<stdio.h> long long Fn[22]; int main() { Fn[1] = 0; Fn[2] = 1; for (int i = 3;i < 22;i++) { Fn[i] = (i - 1)*Fn[i - 1] + (i - 1)*Fn[i - 2]; /* 第一步:将第n封信放入k,有n-1种方法 第二步: ①将k放入n,则剩下的n-2有F(n-2)中方法 ②k不放入n,(k相当于n不能放入n处),则有D(n-1)种 */ } int n; while (scanf("%d", &n) != EOF) { printf("%lld\n",Fn[n]); } }
[ "ncxxdz@126.com" ]
ncxxdz@126.com
069aa977b8f4276560d77f61abfc92d6326d66c0
18aee5d93a63eab684fe69e3aa0abd1372dd5d08
/paddle/fluid/operators/activation_op.cu.h
08a8d9a08960936bcd2d660cc368d4fda0a61184
[ "Apache-2.0" ]
permissive
Shixiaowei02/Paddle
8d049f4f29e281de2fb1ffcd143997c88078eadb
3d4d995f26c48f7792b325806ec3d110fc59f6fc
refs/heads/develop
2023-06-26T06:25:48.074273
2023-06-14T06:40:21
2023-06-14T06:40:21
174,320,213
2
1
Apache-2.0
2022-12-28T05:14:30
2019-03-07T10:09:34
C++
UTF-8
C++
false
false
5,079
h
/* Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "paddle/fluid/operators/activation_op.h" #include "paddle/fluid/operators/amp/fp16_type_traits.h" #include "paddle/fluid/operators/elementwise/elementwise_op_impl.cu.h" #include "paddle/fluid/platform/bfloat16.h" #include "paddle/phi/backends/gpu/gpu_device_function.h" #include "paddle/phi/kernels/funcs/activation_functor.h" namespace paddle { namespace operators { template <typename T> struct CudaSoftReluFunctor : public BaseActivationFunctor<T> { using MPType = typename details::MPTypeTrait<T>::Type; MPType one = static_cast<MPType>(1.0f); float threshold; typename BaseActivationFunctor<T>::AttrPair GetAttrs() { return {{"threshold", &threshold}}; } // soft_relu(x) = log(1 + exp(max(min(x, threshold), -threshold))) // threshold should not be negative __device__ __forceinline__ T operator()(const T arg_x) const { MPType x = static_cast<MPType>(arg_x); MPType t = static_cast<MPType>(threshold); MPType temp_min = x < t ? x : t; MPType temp_max = temp_min > -t ? temp_min : -t; return static_cast<T>(log(one + exp(temp_max))); } }; template <typename T> struct CudaSoftReluGradFunctor : public BaseActivationFunctor<T> { using MPType = typename details::MPTypeTrait<T>::Type; MPType one = static_cast<MPType>(1.0f); float threshold; typename BaseActivationFunctor<T>::AttrPair GetAttrs() { return {{"threshold", &threshold}}; } // dx = (out > -threshold && out < threshold) ? dout * (1 - exp(-out)) : 0 // threshold should not be negative __device__ __forceinline__ T operator()(const T arg_dout, const T arg_out) const { MPType dout = static_cast<MPType>(arg_dout); MPType out = static_cast<MPType>(arg_out); MPType t = static_cast<MPType>(threshold); return (out > -t && out < t) ? static_cast<T>(dout * (one - exp(-out))) : static_cast<T>(0.0f); } static constexpr ActBwdOpFwdDeps FwdDeps() { return ActBwdOpFwdDeps::kDepOut; } }; template <typename DeviceContext, typename Functor> class ActivationCudaKernel : public framework::OpKernel<typename Functor::ELEMENT_TYPE> { public: using T = typename Functor::ELEMENT_TYPE; void Compute(const framework::ExecutionContext& ctx) const override { const phi::DenseTensor* x = nullptr; phi::DenseTensor* out = nullptr; ExtractActivationTensor(ctx, &x, &out); out->mutable_data<T>(ctx.GetPlace()); auto& dev_ctx = ctx.template device_context<DeviceContext>(); std::vector<const phi::DenseTensor*> ins = {x}; std::vector<phi::DenseTensor*> outs = {out}; auto functor = Functor(); auto attrs = functor.GetAttrs(); for (auto& attr : attrs) { *attr.second = ctx.Attr<float>(attr.first); } paddle::operators::LaunchSameDimsElementwiseCudaKernel<T>( dev_ctx, ins, &outs, functor); } }; template <typename DeviceContext, typename Functor> class ActivationGradCudaKernel : public framework::OpKernel<typename Functor::ELEMENT_TYPE> { public: using T = typename Functor::ELEMENT_TYPE; void Compute(const framework::ExecutionContext& ctx) const override { const phi::DenseTensor *x, *out, *d_out; phi::DenseTensor* d_x = nullptr; x = out = d_out = nullptr; ExtractActivationGradTensor<Functor::FwdDeps()>( ctx, &x, &out, &d_out, &d_x); d_x->mutable_data<T>(ctx.GetPlace()); auto& dev_ctx = ctx.template device_context<DeviceContext>(); auto functor = Functor(); auto attrs = functor.GetAttrs(); for (auto& attr : attrs) { *attr.second = ctx.Attr<float>(attr.first); } std::vector<const phi::DenseTensor*> ins = {d_out}; std::vector<phi::DenseTensor*> outs = {d_x}; if (static_cast<int>(Functor::FwdDeps()) == static_cast<int>(ActBwdOpFwdDeps::kDepOut)) { // Only need forward output Out ins.push_back(out); paddle::operators::LaunchSameDimsElementwiseCudaKernel<T>( dev_ctx, ins, &outs, functor); } else if (static_cast<int>(Functor::FwdDeps()) == static_cast<int>(ActBwdOpFwdDeps::kDepX)) { // Only need forward input X ins.push_back(x); paddle::operators::LaunchSameDimsElementwiseCudaKernel<T>( dev_ctx, ins, &outs, functor); } else { paddle::operators::LaunchSameDimsElementwiseCudaKernel<T>( dev_ctx, ins, &outs, functor); } } }; } // namespace operators } // namespace paddle
[ "noreply@github.com" ]
Shixiaowei02.noreply@github.com
6f501ffefe3f9b1027528bbd56f675541c8f2741
37ff83f8dd5204e8181e07fbf27909621794ef90
/src/lidar_localization/include/lidar_localization/publisher/cloud_publisher.hpp
3ddd2a820083e8452e6a2f0e7d507725b12269d0
[]
no_license
leiyubiao/boonray
419480607a006af6a5d2ff6265de64f0cf539150
a6357a6f4071d94f28b34203629bfe21cf84a75f
refs/heads/main
2023-02-22T14:14:07.508438
2021-01-16T14:34:50
2021-01-16T14:34:50
330,179,491
0
0
null
null
null
null
UTF-8
C++
false
false
1,318
hpp
/* * @Description: 在ros中发布点云 * @Author: Ren Qian * @Date: 2020-02-05 02:27:30 */ #ifndef LIDAR_LOCALIZATION_PUBLISHER_CLOUD_PUBLISHER_HPP_ #define LIDAR_LOCALIZATION_PUBLISHER_CLOUD_PUBLISHER_HPP_ #include <sensor_msgs/PointCloud2.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl_conversions/pcl_conversions.h> #include "lidar_localization/sensor_data/cloud_data.hpp" #include "lidar_localization/sensor_data/gnss_data.hpp" namespace lidar_localization { class CloudPublisher { public: CloudPublisher(ros::NodeHandle& nh, std::string topic_name, std::string frame_id, size_t buff_size); CloudPublisher() = default; void Publish(CloudData::CLOUD_PTR& cloud_ptr_input, double time); void Publish(CloudData::CLOUD_PTR& cloud_ptr_input); void Publish_GPS2xy( std::deque<GNSSData> &gnss_data_buff, double time); void Publish_GPS2xy( std::deque<GNSSData> &gnss_data_buff); bool HasSubscribers(); private: void PublishData(CloudData::CLOUD_PTR& cloud_ptr_input, ros::Time time); void transformGPS2xy(std::deque<GNSSData> &gnss_data_buff, CloudData &map_point_cloud_data); private: ros::NodeHandle nh_; ros::Publisher publisher_; std::string frame_id_; }; } #endif
[ "1104881327@qq.com" ]
1104881327@qq.com
ed08e5e5fde011935fb2b562b2a6b19c000909bb
8ca37e18b25d0b9cbf1ebe003f460ca3098e64ee
/homework5_4/MinQueue.h
b91cf85b16e532c7a9d8559980dd6b63bf73f2e5
[]
no_license
FredyJMartinez/Coding-Problems-
b87d7ce83eb13f0338779fbf133326559cb9101f
3948f356e2246d824b29ffa00ce94a05fd8ce61a
refs/heads/master
2020-03-25T15:57:17.091381
2018-08-07T17:50:00
2018-08-07T17:50:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,076
h
// // Created by Fredy on 3/18/2018. // #ifndef HOMEWORK5_4_MINQUEUE_H #define HOMEWORK5_4_MINQUEUE_H #include "circQueue+copy.h" #include <stack> #include <utility> #include <vector> class MinQueue : public circQueue { private: std::stack<std::pair<int, int>> the_stack; std::pair<int, int> value_min_pair; circQueue the_queue; public: /********************************************************************************************************************************************/ // queueMin() // Begins by getting the front of the queue and assuming it is the // least value (either way we have to go through entire queue). // Modify the pair accordingly. Push the pair onto the stack. // enqueue the value onto the circular queue. While queue is not // empty dequeue and save the value. Then check if current min // needs to be modified if not then enqueue the value we dequeued // from this. If current min does need to be modified then modify // and change the top of the stack's minimum value accordingly. // // The queue is just used to store all the values of this and we only // create one pair and modify it when needed // // Note: I think I can do this without a queue at all. // // // // Assumes that the dequeue "flag" (INT8_MIN represents nothing is in the queue) I defined is not a value inside the actual queue /********************************************************************************************************************************************/ int queueMin() { int current_min = this->get_Front(); value_min_pair.first = current_min; value_min_pair.second = current_min; the_stack.push(value_min_pair); the_queue.enqueue(current_min); while (this->get_Front() != INT8_MIN){ auto dequeued_value = this->dequeue(); if (current_min > dequeued_value) { current_min = dequeued_value; the_stack.top().second = current_min; the_queue.enqueue(current_min); } the_queue.enqueue(dequeued_value); } return the_stack.top().second; } }; #endif //HOMEWORK5_4_MINQUEUE_H
[ "36689742+FredyJMartinez@users.noreply.github.com" ]
36689742+FredyJMartinez@users.noreply.github.com
1f0d0d588ba15d24288e553f1bc0d5d93237bd1a
b7e97047616d9343be5b9bbe03fc0d79ba5a6143
/src/protocols/toolbox/task_operations/SeqprofConsensusOperation.fwd.hh
f7b91a80a19f27c84241462daa986b84f95d1c7a
[]
no_license
achitturi/ROSETTA-main-source
2772623a78e33e7883a453f051d53ea6cc53ffa5
fe11c7e7cb68644f404f4c0629b64da4bb73b8f9
refs/heads/master
2021-05-09T15:04:34.006421
2018-01-26T17:10:33
2018-01-26T17:10:33
119,081,547
1
3
null
null
null
null
UTF-8
C++
false
false
1,309
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/toolbox/task_operations/SeqprofConsensusOperation.fwd.hh /// @brief /// @author Florian Richter, floric@u.washington.edu, april 2011 #ifndef INCLUDED_protocols_toolbox_task_operations_SeqprofConsensusOperation_fwd_hh #define INCLUDED_protocols_toolbox_task_operations_SeqprofConsensusOperation_fwd_hh #include <utility/pointer/owning_ptr.hh> namespace protocols { namespace toolbox { namespace task_operations { class SeqprofConsensusOperation; class RestrictConservedLowDdgOperation; typedef utility::pointer::shared_ptr< SeqprofConsensusOperation > SeqprofConsensusOperationOP; typedef utility::pointer::shared_ptr< RestrictConservedLowDdgOperation > RestrictConservedLowDdgOperationOP; } // task_operations } // toolbox } // protocols #endif
[ "achitturi17059@gmail.com" ]
achitturi17059@gmail.com
52dc965a9846ca2d7f7b81a5f3c085cfa2764149
08d9d0299f365a44d92cc66553fab267d56596c8
/src/triangle.h
30e4f87bf4c4089b27a51ecf03499cd1f6f72fb3
[]
no_license
pranav-asthana/3d-graphics-scene
89967c587b2007aa806962804aae7a6b2f84ae4b
c0a5f08cb448de4f8fa6fadf7c79b4a93e759c7a
refs/heads/master
2021-08-22T03:40:26.525635
2017-11-29T05:24:39
2017-11-29T05:24:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
324
h
/** @file */ #ifndef TRIANGLE_H #define TRIANGLE_H #include <glm/glm.hpp> class Triangle { public: glm::vec3 A; glm::vec3 B; glm::vec3 C; /// Create a tringle with given vertices Triangle(glm::vec3 v1, glm::vec3 v2, glm::vec3 v3) { A = v1; B = v2; C = v3; } }; #endif
[ "pranav.i.asthana@happiestminds.com" ]
pranav.i.asthana@happiestminds.com
78272d9bb1db86ff0ee32c327c926192344c93ed
4eafc3b25f8b7d5749409318122a680068665613
/helloLeet/0104.cpp
36b4325520e07f9872810a7cdf555b1e49f21b98
[]
no_license
ctyVegetableDog/leetcode
6f663ab230fb9dbaec4453828e2bd0b274b83a18
2b956412ddfa6b58f5c245da46f96665a8ec276d
refs/heads/master
2023-07-15T06:48:30.869786
2023-07-10T08:13:51
2023-07-10T08:13:51
216,207,344
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
//get depth of a tree /* if !root->left && !root->right return 1; if root->left && !root->right return func(root->left)+1 if !root0>left && root->right return func(root->right)+1 if left && right return max(func(left),func(right)+1) */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getDeep(TreeNode* root) { if (!root->left && !root->right) return 1; else if (!root->left && root->right) return getDeep(root->right) + 1; else if (root->left && !root->right) return getDeep(root->left) + 1; else return max(getDeep(root->left), getDeep(root->right)) + 1; } int maxDepth(TreeNode* root) { if (!root) return 0; return getDeep(root); } }; /* simpler version if !root return 0; else return max(func(left),func(right))+1 */ class Solution { public: int maxDepth(TreeNode* root) { if (!root) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
[ "821789905@qq.com" ]
821789905@qq.com
f092705132c2e7732f46572341f710f7d0dd7159
5696f7e9bb6cb18e791be3f71e8a72f9a26a0a22
/src/StockIndicator/StockIndicator/src/CalcDateBollTask.cpp
e7a7dc3da786a051e736d2aa705f665f6647e005
[ "MIT" ]
permissive
xylsxyls/xueyelingshuang
0fdde992e430bdee38abb7aaf868b320e48dba64
a646d281c4b2ec3c2b27de29a67860fccce22436
refs/heads/master
2023-08-04T01:02:35.112586
2023-07-17T09:30:27
2023-07-17T09:30:27
61,338,042
4
2
null
null
null
null
UTF-8
C++
false
false
1,167
cpp
#include "CalcDateBollTask.h" #include "StockIndicatorHelper.h" #include "StockMarket/StockMarketAPI.h" CalcDateBollTask::CalcDateBollTask() : m_indicatorData(nullptr) { } void CalcDateBollTask::DoTask() { if (!m_market.setDate(m_date)) { return; } std::map<std::string, std::vector<std::vector<std::string>>>& indicatorData = *m_indicatorData; std::string stock = m_market.stock(); indicatorData[stock]; auto& stockData = indicatorData.find(stock)->second; stockData.push_back(std::vector<std::string>()); auto& stockDataBack = stockData.back(); stockDataBack.push_back(m_date.dateToString()); std::pair<BigNumber, std::pair<BigNumber, BigNumber>> dayBoll = StockIndicatorHelper::boll(m_date, m_market); stockDataBack.push_back(dayBoll.first.toString()); stockDataBack.push_back(dayBoll.second.first.toString()); stockDataBack.push_back(dayBoll.second.second.toString()); } void CalcDateBollTask::setParam(const IntDateTime& date, const StockMarket& market, std::map<std::string, std::vector<std::vector<std::string>>>* indicatorData) { m_date = date; m_market = market; m_indicatorData = indicatorData; }
[ "yangnan@sensetime.com" ]
yangnan@sensetime.com
3b473a5dcc4f09c5c789928dcd1c0be555a117e6
415ef5c9ba794c92a7b604621d901e6e41819469
/c,c++/secondMost.cpp
a21f3dbb9d778408774e1da1c182cbbf4ab7c935
[]
no_license
Sruthi-Ganesh/GitHub
2d18db7f78b928da7a15b4283328d8fd6e0eaa59
7aa2407e70c4cd9a1bf3cdc51af4519fcff607bc
refs/heads/master
2021-01-01T17:58:33.274325
2017-07-24T15:24:26
2017-07-24T15:24:26
98,207,308
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
cpp
// unordered_map::begin/end example #include <iostream> #include <unordered_map> #include<vector> #include<iomanip> using namespace std; string unordered(vector<string> words) { int max=0; int second_max=0; unordered_map <string,int>values; for(int j=0;j<words.size();j++) { values[words[j]]++; } for(auto j=values.begin();j!=values.end();j++) { cout<<setw(2)<<j->second; if(j->second>max) { second_max=max; max = j->second; } else if(j->second>second_max && j->second!=max) { second_max=j->second; } } for(auto j=values.begin();j!=values.end();j++) { if(j->second == second_max) { return j->first; } } } int main () { vector<string> words; string x; for( int i=0;cin.get()!='\n';i++) { cin>>x; words.push_back(x); } for(int j=0;j<words.size();j++) { cout<<words[j]; } cout<<unordered(words); return 0; }
[ "sruthibadal@gmail.com" ]
sruthibadal@gmail.com
38b7fa0ff17e307dee3d371b60d8706ad4ebb8da
8c8f0e9b33aac8b62ad1009549c291834b4a1aec
/Code/Arduino/programmable_smarticle/programmable_smarticle.ino
96bb19842501a8987cf672bfabd8e6b9862a890b
[]
no_license
MurpheyLab/SmarticlesNU
070f89cd1a376fefa757097924abe5d409986789
837d3fde85ca193411d4d9ed722f367e281f2286
refs/heads/master
2022-12-30T13:35:58.464215
2020-10-21T13:36:18
2020-10-21T13:36:18
202,380,351
1
1
null
null
null
null
UTF-8
C++
false
false
424
ino
#include <Smarticle.h> Smarticle smart(1); void setup() { randomSeed(analogRead(A7)); NeoSerial1.attachInterrupt(handleRxChar); smart.init_t4(); smart.toggle_led(1); delay(3000); smart.toggle_led(0); } void loop() { smart.read_sensors(); smart.transmit_data(); smart.manage_msg(); } ISR(TIMER4_COMPA_vect){ smart.t4_interrupt(); } static void handleRxChar( uint8_t c) { smart.rx_interrupt(c); }
[ "alexandersamland2020@u.northwestern.edu" ]
alexandersamland2020@u.northwestern.edu
dca74e59efaf372ef45ae5aebfadf46f0d802c6c
3bc7467217697dcce015d4a3fec7d8348409dec1
/Lab 2/lab2_histogram.cpp
c157d59b060eb9188061c9c4312ad7505e990523
[]
no_license
juliocmontes/bcc_course
abe2f2282f0b111f2f939761c2b1baec69776b95
770df1ec477f8fedb6d3bd592b9178ecacaa8e83
refs/heads/master
2020-07-08T12:40:00.718012
2019-10-25T15:11:58
2019-10-25T15:11:58
203,673,742
0
0
null
null
null
null
UTF-8
C++
false
false
6,039
cpp
/* Title: Lab 2 - Histograms Author: Julio Montes Date: 10.22.19 Description: two different counters, from 0-1 and 0-10 counting them multiple times and displaying histograms for them */ #include <iostream> #include <cmath> #include <math.h> // for random #include <stdlib.h> // for time to seed random each time #include<time.h> // Histogram for 1000 count int main() { // initialize random number generator , time is returned with seconds therefore always pproviding a different number when ran srand(time(NULL)); // initialized as strings and will use the length properties to count std::string counter1 = ""; std::string counter2 = ""; std::string counter3 = ""; std::string counter4 = ""; std::string counter5 = ""; std::string counter6 = ""; std::string counter7 = ""; std::string counter8 = ""; std::string counter9 = ""; std::string counter10 = ""; for(int i = 1000; i > 0; i--){ // initialize the random number between 0 and 1 double randnum = (double)rand() / ((double)RAND_MAX + 1); if (randnum < 0.1) { // appends * to string if random numberis les that 0.1 counter1 += '*'; } else if ((0.1 <= randnum) && ( randnum < 0.2)) { counter2 += '*'; } else if ((0.2 <= randnum) && ( randnum< 0.3)) { counter3 += '*'; } else if ((0.3 <= randnum) && (randnum < 0.4)) { counter4 += '*'; } else if ((0.4 <= randnum) && (randnum < 0.5)) { counter5 += '*'; } else if ((0.5 <= randnum) && (randnum < 0.6)) { counter6 += '*'; } else if ((0.6 <= randnum) && (randnum < 0.7)) { counter7 += '*'; } else if ((0.7 <= randnum) && (randnum < 0.8)) { counter8 += '*'; } else if ((0.8 <= randnum) && (randnum < 0.9)) { counter9 += '*'; } else counter10 += '*'; }; // print count and histogram std::cout << "Counter 1: " << counter1.length() << " - " << counter1 << std::endl; std::cout << "Counter 2: " << counter2.length() << " - " << counter2 << std::endl; std::cout << "Counter 3: " << counter3.length() << " - " << counter3 << std::endl; std::cout << "Counter 4: " << counter4.length() << " - " << counter4 << std::endl; std::cout << "Counter 5: " << counter5.length() << " - " << counter5 << std::endl; std::cout << "Counter 6: " << counter6.length() << " - " << counter6 << std::endl; std::cout << "Counter 7: " << counter7.length() << " - " << counter7 << std::endl; std::cout << "Counter 8: " << counter8.length() << " - " << counter8 << std::endl; std::cout << "Counter 9: " << counter9.length() << " - " << counter9 << std::endl; std::cout << "Counter 10: " << counter9.length() << " - " << counter10 << std::endl; std::cout << "Total: " << counter1.length() + counter2.length() + counter3.length() + counter4.length() + counter5.length() + counter6.length() + counter7.length() + counter8.length() + counter9.length() + counter10.length() << std::endl; return 0; } // // Histogram modified for 10 count // int main() // { // // initialize random number generator , time is returned with seconds therefore always pproviding a different number when ran // srand(time(NULL)); // // initialized as strings and will use the length properties to count // std::string counter1 = ""; // std::string counter2 = ""; // std::string counter3 = ""; // std::string counter4 = ""; // std::string counter5 = ""; // std::string counter6 = ""; // std::string counter7 = ""; // std::string counter8 = ""; // std::string counter9 = ""; // std::string counter10 = ""; // for(int i = 10; i > 0; i--) { // // initialize the random number between 0 and 1 // int randnum = rand() % 10; // if (randnum < 1) { // // appends * to string if random numberis les that 0.1 // counter1 += '*'; // } else if ((1 >= randnum) && (randnum < 2)) { // counter2 += '*'; // } else if ((2 >= randnum) && (randnum < 3)) { // counter3 += '*'; // } else if ((3 >= randnum) && (randnum < 4)) { // counter4 += '*'; // } else if ((4 >= randnum) && (randnum < 5)) { // counter5 += '*'; // } else if ((5 >= randnum) && (randnum < 6)) { // counter6 += '*'; // } else if ((6 >= randnum) && (randnum < 7)) { // counter7 += '*'; // } else if ((7 >= randnum) && (randnum < 8)) { // counter8 += '*'; // } else if ((8 >= randnum) && (randnum < 9)) { // counter9 += '*'; // } else // counter10 += '*'; // }; // // print count and histogram // std::cout << "Counter 1: " << counter1.length() << " - " << counter1 << std::endl; // std::cout << "Counter 2: " << counter2.length() << " - " << counter2 << std::endl; // std::cout << "Counter 3: " << counter3.length() << " - " << counter3 << std::endl; // std::cout << "Counter 4: " << counter4.length() << " - " << counter4 << std::endl; // std::cout << "Counter 5: " << counter5.length() << " - " << counter5 << std::endl; // std::cout << "Counter 6: " << counter6.length() << " - " << counter6 << std::endl; // std::cout << "Counter 7: " << counter7.length() << " - " << counter7 << std::endl; // std::cout << "Counter 8: " << counter8.length() << " - " << counter8 << std::endl; // std::cout << "Counter 9: " << counter9.length() << " - " << counter9 << std::endl; // std::cout << "Counter 10: " << counter9.length() << " - " << counter10 << std::endl; // std::cout << "Total: " << counter1.length() + counter2.length() + counter3.length() + counter4.length() + counter5.length() + counter6.length() + counter7.length() + counter8.length() + counter9.length() + counter10.length() << std::endl; // return 0; // }
[ "juliocmontes.a@gmail.com" ]
juliocmontes.a@gmail.com
01489111424c211e3db3e5828cee1187c8e8e6f1
1c1ec116ce31c5eef0df06d2aca182781ae17824
/source/HIS/include/ComponentElement/ChipE1Logic.h
60f7abe27115d0b764d922895fbddd41078e880f
[]
no_license
Gloriacnb/ISAP300
0410462cbf76f82f6f21b911e899d6b64407fa10
9f36607ac21524ab16609ee2d0c39bb222cd7be3
refs/heads/master
2021-01-18T23:41:05.998369
2017-12-25T01:16:37
2017-12-25T01:16:37
100,565,892
0
0
null
2017-08-17T05:43:16
2017-08-17T05:43:16
null
UTF-8
C++
false
false
886
h
/* * ChipE1Logic.h * * Created on: 2013-12-17 * Author: Administrator */ #ifndef CHIPE1LOGIC_H_ #define CHIPE1LOGIC_H_ #include "FPGAChip.h" class RegisterAccess; class CBaseSlot; class ChipE1Logic : public FPGAChip { static const uint16 VER = 0x000f; static const uint16 REG_LED_CTRL = 0x0100; //bit0 work, bit1 alm, bit2 connect, bit3 drop public: ChipE1Logic(CBaseSlot* slt); ChipE1Logic(const std::string& chipName, CBaseSlot* slt); virtual ~ChipE1Logic(); virtual Chip_INIT_RESULT ChipInit(void); void ledWorkOn(bool on); void ledAlmkOn(bool on); void ledConnectOn(bool on); void ledDropOn(bool on); private: typedef enum { LED_WRK, LED_ALM, LED_CON, LED_DRP }E1_LED_E; void ledOn(E1_LED_E led, bool on); void initRegs(void); }; #endif /* CHIPE1LOGIC_H_ */
[ "momo_nono@163.com" ]
momo_nono@163.com
93fded7167c61110cfd159d56ae3e1bbdd6e76d6
16fc09c8ac89b10916eac5a7e2ac3487a4d0f03a
/lec07/examples/Algo.h
db2d00c2155678d6d32cd7366631b01f9be99113
[]
no_license
Lorenzo128/CMP
c23b0f71cf63795e29a6945a2a1104bf79031a0a
d7638580c6cdae351f8d74ffbed7e4c95833a8f5
refs/heads/master
2020-04-03T10:43:17.550278
2018-10-29T09:08:21
2018-10-29T09:08:21
155,200,416
1
0
null
null
null
null
UTF-8
C++
false
false
233
h
#ifndef Algo_h #define Algo_h class Algo { public: Algo() { params_ = 0; } Algo(const Algo& algo) { params_ = algo.params_; } double compute(const double& arg) const; private: int params_; }; #endif
[ "rahatlou@gmail.com" ]
rahatlou@gmail.com
20c8352836eeae0b5930e5a84c92681832437451
affb4f713b00303bf72552ec39684f5420884e94
/Classes/Modal/GameSprite.cpp
f1815779c2666c597cc84a81a5283f5e748f4931
[]
no_license
dinhquochung/battleduty
7024f8132048be45ba2803e1911e6ce7e16de0f2
6189cff13d4672c0b0444a927ab8c3a6068d7b8b
refs/heads/master
2021-01-23T12:06:45.137365
2014-02-27T06:40:10
2014-02-27T06:40:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
// // GameSprite.cpp // BattleDuty // // Created by dinh-q on 2014/02/12. // // #include "GameSprite.h" GameSprite::GameSprite(void){ _vector = ccp(0,0); } GameSprite::~GameSprite(void){ } GameSprite* GameSprite::gameSpriteWithFile(const char *pszFileName) { GameSprite* sprite = new GameSprite(); if (sprite && sprite->initWithFile(pszFileName)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); } void GameSprite::setPosition(const CCPoint& pos) { CCSprite::setPosition(pos); if (!_nextPosition.equals(pos)) { _nextPosition = pos; } } float GameSprite::radius() { return getTexture()->getContentSize().width * 0.5f; }
[ "dinh-q@klab.com" ]
dinh-q@klab.com
66ebeffce3e63e6265262c05e1cfaf96d8822250
3bd1518535099526a3241deaec88864ac3a8a528
/source/Lib/TLibDecoder/TDecSlice.cpp
66f2ef26fa363cb649e6be7873f94076f6a0a2d4
[]
no_license
zinsayon/HEVC-HOP
a18668b11b50d65fb62460dcdca59fb6eacd1642
49d03a6f6a1d6c8e4e9a90e30a5aaa6453d5a163
refs/heads/master
2022-12-09T11:06:23.430018
2020-09-02T17:13:31
2020-09-02T17:13:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,969
cpp
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2014, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file TDecSlice.cpp \brief slice decoder class */ #include "TDecSlice.h" //! \ingroup TLibDecoder //! \{ ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// TDecSlice::TDecSlice() { m_pcBufferSbacDecoders = NULL; m_pcBufferBinCABACs = NULL; m_pcBufferLowLatSbacDecoders = NULL; m_pcBufferLowLatBinCABACs = NULL; } TDecSlice::~TDecSlice() { for (std::vector<TDecSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++) { delete (*i); } CTXMem.clear(); } Void TDecSlice::initCtxMem( UInt i ) { for (std::vector<TDecSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++) { delete (*j); } CTXMem.clear(); CTXMem.resize(i); } Void TDecSlice::create() { } Void TDecSlice::destroy() { if ( m_pcBufferSbacDecoders ) { delete[] m_pcBufferSbacDecoders; m_pcBufferSbacDecoders = NULL; } if ( m_pcBufferBinCABACs ) { delete[] m_pcBufferBinCABACs; m_pcBufferBinCABACs = NULL; } if ( m_pcBufferLowLatSbacDecoders ) { delete[] m_pcBufferLowLatSbacDecoders; m_pcBufferLowLatSbacDecoders = NULL; } if ( m_pcBufferLowLatBinCABACs ) { delete[] m_pcBufferLowLatBinCABACs; m_pcBufferLowLatBinCABACs = NULL; } } Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder) { m_pcEntropyDecoder = pcEntropyDecoder; m_pcCuDecoder = pcCuDecoder; } Void TDecSlice::decompressSlice(TComInputBitstream** ppcSubstreams, TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders) { TComDataCU* pcCU; UInt uiIsLast = 0; Int iStartCUEncOrder = max(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU(), rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU()); Int iStartCUAddr = rpcPic->getPicSym()->getCUOrderMap(iStartCUEncOrder); // decoder don't need prediction & residual frame buffer rpcPic->setPicYuvPred( 0 ); rpcPic->setPicYuvResi( 0 ); #if ENC_DEC_TRACE g_bJustDoIt = g_bEncDecTraceEnable; #endif DTRACE_CABAC_VL( g_nSymbolCounter++ ); DTRACE_CABAC_T( "\tPOC: " ); DTRACE_CABAC_V( rpcPic->getPOC() ); DTRACE_CABAC_T( "\n" ); #if ENC_DEC_TRACE g_bJustDoIt = g_bEncDecTraceDisable; #endif UInt uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1; TComSlice* pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx()); Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams(); // delete decoders if already allocated in previous slice if (m_pcBufferSbacDecoders) { delete [] m_pcBufferSbacDecoders; } if (m_pcBufferBinCABACs) { delete [] m_pcBufferBinCABACs; } // allocate new decoders based on tile numbaer m_pcBufferSbacDecoders = new TDecSbac [uiTilesAcross]; m_pcBufferBinCABACs = new TDecBinCABAC[uiTilesAcross]; for (UInt ui = 0; ui < uiTilesAcross; ui++) { m_pcBufferSbacDecoders[ui].init(&m_pcBufferBinCABACs[ui]); } //save init. state for (UInt ui = 0; ui < uiTilesAcross; ui++) { m_pcBufferSbacDecoders[ui].load(pcSbacDecoder); } // free memory if already allocated in previous call if (m_pcBufferLowLatSbacDecoders) { delete [] m_pcBufferLowLatSbacDecoders; } if (m_pcBufferLowLatBinCABACs) { delete [] m_pcBufferLowLatBinCABACs; } m_pcBufferLowLatSbacDecoders = new TDecSbac [uiTilesAcross]; m_pcBufferLowLatBinCABACs = new TDecBinCABAC[uiTilesAcross]; for (UInt ui = 0; ui < uiTilesAcross; ui++) { m_pcBufferLowLatSbacDecoders[ui].init(&m_pcBufferLowLatBinCABACs[ui]); } //save init. state for (UInt ui = 0; ui < uiTilesAcross; ui++) { m_pcBufferLowLatSbacDecoders[ui].load(pcSbacDecoder); } UInt uiWidthInLCUs = rpcPic->getPicSym()->getFrameWidthInCU(); //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU(); UInt uiCol=0, uiLin=0, uiSubStrm=0; UInt uiTileCol; UInt uiTileStartLCU; UInt uiTileLCUX; Int iNumSubstreamsPerTile = 1; // if independent. Bool depSliceSegmentsEnabled = rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceSegmentsEnabledFlag(); uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr(); if( depSliceSegmentsEnabled ) { if( (!rpcPic->getSlice(rpcPic->getCurrSliceIdx())->isNextSlice()) && iStartCUAddr != rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr()) { if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) { uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); m_pcBufferSbacDecoders[uiTileCol].loadContexts( CTXMem[1] );//2.LCU if ( (iStartCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs ) { uiTileLCUX = uiTileStartLCU % uiWidthInLCUs; uiCol = iStartCUAddr % uiWidthInLCUs; if(uiCol==uiTileLCUX) { CTXMem[0]->loadContexts(pcSbacDecoder); } } } pcSbacDecoder->loadContexts(CTXMem[0] ); //end of depSlice-1 pcSbacDecoders[uiSubStrm].loadContexts(pcSbacDecoder); } else { if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) { CTXMem[1]->loadContexts(pcSbacDecoder); } CTXMem[0]->loadContexts(pcSbacDecoder); } } for( Int iCUAddr = iStartCUAddr; !uiIsLast && iCUAddr < rpcPic->getNumCUsInFrame(); iCUAddr = rpcPic->getPicSym()->xCalculateNxtCUAddr(iCUAddr) ) { pcCU = rpcPic->getCU( iCUAddr ); pcCU->initCU( rpcPic, iCUAddr ); uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in? uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr(); uiTileLCUX = uiTileStartLCU % uiWidthInLCUs; uiCol = iCUAddr % uiWidthInLCUs; // The 'line' is now relative to the 1st line in the slice, not the 1st line in the picture. uiLin = (iCUAddr/uiWidthInLCUs)-(iStartCUAddr/uiWidthInLCUs); // inherit from TR if necessary, select substream to use. if( (pcSlice->getPPS()->getNumSubstreams() > 1) || ( depSliceSegmentsEnabled && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) )) { // independent tiles => substreams are "per tile". iNumSubstreams has already been multiplied. iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles(); uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(iCUAddr)*iNumSubstreamsPerTile + uiLin%iNumSubstreamsPerTile; m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] ); // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line. if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())) { // We'll sync if the TR is available. TComDataCU *pcCUUp = pcCU->getCUAbove(); UInt uiWidthInCU = rpcPic->getFrameWidthInCU(); TComDataCU *pcCUTR = NULL; if ( pcCUUp && ((iCUAddr%uiWidthInCU+1) < uiWidthInCU) ) { pcCUTR = rpcPic->getCU( iCUAddr - uiWidthInCU + 1 ); } UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1); if ( (true/*bEnforceSliceRestriction*/ && ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getSliceCurStartCUAddr()) || ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))) )) ) { // TR not available. } else { // TR is available, we use it. pcSbacDecoders[uiSubStrm].loadContexts( &m_pcBufferSbacDecoders[uiTileCol] ); } } pcSbacDecoder->load(&pcSbacDecoders[uiSubStrm]); //this load is used to simplify the code (avoid to change all the call to pcSbacDecoders) } else if ( pcSlice->getPPS()->getNumSubstreams() <= 1 ) { // Set variables to appropriate values to avoid later code change. iNumSubstreamsPerTile = 1; } if ( (iCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr()) && // 1st in tile. (iCUAddr!=0) && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU()) && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU()) ) // !1st in frame && !1st in slice { if (pcSlice->getPPS()->getNumSubstreams() > 1) { // We're crossing into another tile, tiles are independent. // When tiles are independent, we have "substreams per tile". Each substream has already been terminated, and we no longer // have to perform it here. // For TILES_DECODER, there can be a header at the start of the 1st substream in a tile. These are read when the substreams // are extracted, not here. } else { SliceType sliceType = pcSlice->getSliceType(); if (pcSlice->getCabacInitFlag()) { switch (sliceType) { case P_SLICE: // change initialization table to B_SLICE intialization sliceType = B_SLICE; break; case B_SLICE: // change initialization table to P_SLICE intialization sliceType = P_SLICE; break; default : // should not occur assert(0); } } m_pcEntropyDecoder->updateContextTables( sliceType, pcSlice->getSliceQp() ); } } #if ENC_DEC_TRACE g_bJustDoIt = g_bEncDecTraceEnable; #endif if ( pcSlice->getSPS()->getUseSAO() ) { SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[iCUAddr]; if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) { Bool sliceEnabled[NUM_SAO_COMPONENTS]; sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag(); sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma(); Bool leftMergeAvail = false; Bool aboveMergeAvail= false; //merge left condition Int rx = (iCUAddr % uiWidthInLCUs); if(rx > 0) { leftMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-1); } //merge up condition Int ry = (iCUAddr / uiWidthInLCUs); if(ry > 0) { aboveMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-uiWidthInLCUs); } pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail); } else { saoblkParam[SAO_Y ].modeIdc = SAO_MODE_OFF; saoblkParam[SAO_Cb].modeIdc = SAO_MODE_OFF; saoblkParam[SAO_Cr].modeIdc = SAO_MODE_OFF; } } #if IT_GT if(pcCU->getCUPelX() == 320 && pcCU->getCUPelY() == 128) int coiso = 0; #endif m_pcCuDecoder->decodeCU ( pcCU, uiIsLast ); m_pcCuDecoder->decompressCU ( pcCU ); #if ENC_DEC_TRACE g_bJustDoIt = g_bEncDecTraceDisable; #endif pcSbacDecoders[uiSubStrm].load(pcSbacDecoder); if ( uiCol == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getRightEdgePosInCU() && pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() && !uiIsLast ) { // Parse end_of_substream_one_bit for WPP case UInt binVal; pcSbacDecoder->parseTerminatingBit( binVal ); assert( binVal ); } //Store probabilities of second LCU in line into buffer if ( (uiCol == uiTileLCUX+1)&& (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) ) { m_pcBufferSbacDecoders[uiTileCol].loadContexts( &pcSbacDecoders[uiSubStrm] ); } if( uiIsLast && depSliceSegmentsEnabled ) { if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) { CTXMem[1]->loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );//ctx 2.LCU } CTXMem[0]->loadContexts( pcSbacDecoder );//ctx end of dep.slice return; } } } ParameterSetManagerDecoder::ParameterSetManagerDecoder() : m_vpsBuffer(MAX_NUM_VPS) , m_spsBuffer(MAX_NUM_SPS) , m_ppsBuffer(MAX_NUM_PPS) { } ParameterSetManagerDecoder::~ParameterSetManagerDecoder() { } TComVPS* ParameterSetManagerDecoder::getPrefetchedVPS (Int vpsId) { if (m_vpsBuffer.getPS(vpsId) != NULL ) { return m_vpsBuffer.getPS(vpsId); } else { return getVPS(vpsId); } } TComSPS* ParameterSetManagerDecoder::getPrefetchedSPS (Int spsId) { if (m_spsBuffer.getPS(spsId) != NULL ) { return m_spsBuffer.getPS(spsId); } else { return getSPS(spsId); } } TComPPS* ParameterSetManagerDecoder::getPrefetchedPPS (Int ppsId) { if (m_ppsBuffer.getPS(ppsId) != NULL ) { return m_ppsBuffer.getPS(ppsId); } else { return getPPS(ppsId); } } Void ParameterSetManagerDecoder::applyPrefetchedPS() { m_vpsMap.mergePSList(m_vpsBuffer); m_ppsMap.mergePSList(m_ppsBuffer); m_spsMap.mergePSList(m_spsBuffer); } //! \}
[ "ricardojorgesmonteiro@gmail.com" ]
ricardojorgesmonteiro@gmail.com
81603f685dc79eebed5238d7d6c20407570d50d7
349fe46c47f9164347f66bdfedac37fc314c20e5
/test/mytest/ModInt.test.cpp
fae7b18a0996e573bbc96b7d33885c4626d06bd9
[]
no_license
spihill/library
f9a4a56242f505a8cd2236ca9e01e587cddbe2a9
b7e81c94202a082eff30988793c8f5be9d969fdc
refs/heads/master
2020-06-24T15:21:40.591287
2020-03-18T14:00:44
2020-03-18T14:00:44
198,998,636
0
3
null
null
null
null
UTF-8
C++
false
false
6,338
cpp
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/lesson/2/ITP1/1/ITP1_1_A" #include <bits/stdc++.h> using namespace std; #include "../../math/ModInt.cpp" #define RANGE_CHECK(a) assert(0 <= (a).x && (a).x < (modint::get_mod())) struct random_class { struct xorshift { using result_type = unsigned int; result_type x=123456789u,y=362436069u,z=521288629u,w; static constexpr result_type min() {return 0u;} static constexpr result_type max() {return UINT_MAX;} xorshift(result_type a) : w(a) {} result_type operator()() { result_type t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); } }; random_device rd; xorshift xor128; random_class() : rd(), xor128(rd()) {} long long make_random(long long min_v, long long max_v) { return uniform_int_distribution<long long>(min_v, max_v)(xor128);} }; constexpr bool isprime(int m) { if (m < 2) return false; for (long long i = 2; i * i <= m; i++) { if (m % i == 0) return false; } return true; } template<class modint> void test(modint a) { static_assert(isprime(modint::get_mod()), "a.M is not a prime number"); random_class R; a = LLONG_MIN; RANGE_CHECK(a); a = LLONG_MAX; RANGE_CHECK(a); for (int i = 0; i < 100; i++) { a = R.make_random(LLONG_MIN, LLONG_MAX); RANGE_CHECK(a); modint b = R.make_random(LLONG_MIN, LLONG_MAX); RANGE_CHECK(b); modint c; modint d = a; c = a + b; RANGE_CHECK(c); assert((d += b) == c); assert(!(d != c)); d = a; c = a - b; RANGE_CHECK(c); assert((d -= b) == c); assert(!(d != c)); d = a; c = a / b; RANGE_CHECK(c); assert((d /= b) == c); assert(!(d != c)); d = a; c = a * b; RANGE_CHECK(c); assert((d *= b) == c); assert(!(d != c)); d = a; long long B = R.make_random(LLONG_MIN, LLONG_MAX); modint C; modint D = a; RANGE_CHECK(D); C = a + B; RANGE_CHECK(C); assert((D += B) == C); assert(!(D != C)); D = B; C = B + a; RANGE_CHECK(C); assert((D += a) == C); assert(!(D != C)); D = a; C = a - B; RANGE_CHECK(C); assert((D -= B) == C); assert(!(D != C)); D = B; C = B - a; RANGE_CHECK(C); assert((D -= a) == C); assert(!(D != C)); D = a; C = a * B; RANGE_CHECK(C); assert((D *= B) == C); assert(!(D != C)); D = B; C = B * a; RANGE_CHECK(C); assert((D *= a) == C); assert(!(D != C)); D = a; C = a / B; RANGE_CHECK(C); assert((D /= B) == C); assert(!(D != C)); D = B; C = B / a; RANGE_CHECK(C); assert((D /= a) == C); assert(!(D != C)); D = a; } for (int i = 0; i < 100; i++) { a = R.make_random(LLONG_MIN, LLONG_MAX); modint b = R.make_random(LLONG_MIN, LLONG_MAX); modint c; c = a + b - b; RANGE_CHECK(c); assert(c == a); c = b + a - a; RANGE_CHECK(c); assert(c == b); c = -a; RANGE_CHECK(c); assert(c == 0 - a); c = +a; RANGE_CHECK(c); assert(c == a); if (b != 0) { assert(a * b / b == a); assert(b / b == 1); } if (a != 0) { assert(b * a / a == b); assert(a / a == 1); } modint t = a; RANGE_CHECK(t); modint d; c = a++; d = t; RANGE_CHECK(c); RANGE_CHECK(d); assert(c == d); c = a; d = ++t; RANGE_CHECK(c); RANGE_CHECK(d); assert(c == d); c = a--; d = t; RANGE_CHECK(c); RANGE_CHECK(d); assert(c == d); c = a; d = --t; RANGE_CHECK(c); RANGE_CHECK(d); assert(c == d); } } void check_literal() { cerr << "ModInt<1000000007> is literal_type" << endl; static_assert(is_literal_type<ModInt<2>>::value, ""); using modint = ModInt<1000000007>; static_assert(modint(1) / 2 == 500000004, ""); static_assert(modint(1) + 2 == 3, ""); static_assert(modint(1) - 2 == 1000000006, ""); static_assert(modint(1) * 2 == 2, ""); static_assert(+modint(1) == 1, ""); static_assert(-modint(1) == 1000000006, ""); static_assert(++modint(1) == 2, ""); static_assert(modint(1)++ == 1, ""); static_assert(--modint(1) == 0, ""); static_assert(modint(1)-- == 1, ""); static_assert(modint(2) == (modint(1) = 2), ""); static_assert(modint(2).power(2) == 4, ""); static_assert(modint(2).inv() == 500000004, ""); static_assert(modint(2) != 1, ""); static_assert(modint(2) == 2, ""); static_assert(static_cast<int>(modint(2)) == 2, ""); static_assert(is_same<decltype(modint(1) + 1), modint>::value, ""); static_assert(is_same<decltype(1 + modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) + modint(1)), modint>::value, ""); static_assert(is_same<decltype(+modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) += 1), modint&>::value, ""); static_assert(is_same<decltype(modint(1)++), modint>::value, ""); static_assert(is_same<decltype(++modint(1)), modint&>::value, ""); static_assert(is_same<decltype(modint(1) - 1), modint>::value, ""); static_assert(is_same<decltype(1 - modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) - modint(1)), modint>::value, ""); static_assert(is_same<decltype(-modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) -= 1), modint&>::value, ""); static_assert(is_same<decltype(modint(1)--), modint>::value, ""); static_assert(is_same<decltype(--modint(1)), modint&>::value, ""); static_assert(is_same<decltype(modint(1) * 1), modint>::value, ""); static_assert(is_same<decltype(1 * modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) * modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) *= 1), modint&>::value, ""); static_assert(is_same<decltype(modint(1) / 1), modint>::value, ""); static_assert(is_same<decltype(1 / modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) / modint(1)), modint>::value, ""); static_assert(is_same<decltype(modint(1) /= 1), modint&>::value, ""); static_assert(is_integral<modint>::value, ""); static_assert(is_scalar<modint>::value, ""); static_assert(!is_floating_point<modint>::value, ""); static_assert(!is_signed<modint>::value, ""); static_assert(is_unsigned<modint>::value, ""); } int main() { check_literal(); for (int i = 0; i < 100; i++) { test(ModInt<1811939329>(0)); test(ModInt<1711276033>(0)); test(ModInt<1000000007>(0)); test(ModInt<1000000009>(0)); test(ModInt<998244353>(0)); test(ModInt<10007>(0)); test(ModInt<10009>(0)); test(ModInt<2>(0)); test(ModInt<3>(0)); test(ModInt<5>(0)); test(ModInt<7>(0)); test(ModInt<11>(0)); test(ModInt<13>(0)); test(ModInt<97>(0)); } cout << "Hello World" << endl; }
[ "spihill.in@gmail.com" ]
spihill.in@gmail.com
7cd5be6aebe3848f9b1d6fde5e7eb56fc1a6e256
c928ee4909bff4d412bd04d085d7ce5455d2af26
/src/netbase.h
ac6765681e6eb6aaa4f6d450bfaedaa2b42d9fe9
[]
no_license
turnkeyglobal/BitcoinJ
71004527a9448be79f7e48cc5067410f2398762c
c969ae131b5ffeccb00d3850267d50a1b3e8fd5b
refs/heads/master
2020-03-06T14:30:11.138789
2018-03-27T06:17:04
2018-03-27T06:17:04
126,937,125
0
0
null
null
null
null
UTF-8
C++
false
false
8,720
h
// Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NETBASE_H #define BITCOIN_NETBASE_H #if defined(HAVE_CONFIG_H) #include "config/minmontcoin-config.h" #endif #include "compat.h" #include "serialize.h" #include <stdint.h> #include <string> #include <vector> extern int nConnectTimeout; extern bool fNameLookup; //! -timeout default static const int DEFAULT_CONNECT_TIMEOUT = 5000; //! -dns default static const int DEFAULT_NAME_LOOKUP = true; #ifdef WIN32 // In MSVC, this is defined as a macro, undefine it to prevent a compile and link error #undef SetPort #endif enum Network { NET_UNROUTABLE = 0, NET_IPV4, NET_IPV6, NET_TOR, NET_MAX, }; /** IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96)) */ class CNetAddr { protected: unsigned char ip[16]; // in network byte order public: CNetAddr(); CNetAddr(const struct in_addr& ipv4Addr); explicit CNetAddr(const char *pszIp, bool fAllowLookup = false); explicit CNetAddr(const std::string &strIp, bool fAllowLookup = false); void Init(); void SetIP(const CNetAddr& ip); /** * Set raw IPv4 or IPv6 address (in network byte order) * @note Only NET_IPV4 and NET_IPV6 are allowed for network. */ void SetRaw(Network network, const uint8_t *data); bool SetSpecial(const std::string &strName); // for Tor addresses bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0) bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor) bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) bool IsRFC2544() const; // IPv4 inter-network communcations (192.18.0.0/15) bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10) bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32) bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16) bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16) bool IsRFC4193() const; // IPv6 unique local (FC00::/7) bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32) bool IsRFC4843() const; // IPv6 ORCHID (2001:10::/28) bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64) bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96) bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96) bool IsTor() const; bool IsLocal() const; bool IsRoutable() const; bool IsValid() const; bool IsMulticast() const; enum Network GetNetwork() const; std::string ToString() const; std::string ToStringIP() const; unsigned int GetByte(int n) const; uint64_t GetHash() const; bool GetInAddr(struct in_addr* pipv4Addr) const; std::vector<unsigned char> GetGroup() const; int GetReachabilityFrom(const CNetAddr *paddrPartner = NULL) const; CNetAddr(const struct in6_addr& pipv6Addr); bool GetIn6Addr(struct in6_addr* pipv6Addr) const; friend bool operator==(const CNetAddr& a, const CNetAddr& b); friend bool operator!=(const CNetAddr& a, const CNetAddr& b); friend bool operator<(const CNetAddr& a, const CNetAddr& b); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(FLATDATA(ip)); } friend class CSubNet; }; class CSubNet { protected: /// Network (base) address CNetAddr network; /// Netmask, in network byte order uint8_t netmask[16]; /// Is this value valid? (only used to signal parse errors) bool valid; public: CSubNet(); explicit CSubNet(const std::string &strSubnet, bool fAllowLookup = false); //constructor for single ip subnet (<ipv4>/32 or <ipv6>/128) explicit CSubNet(const CNetAddr &addr); bool Match(const CNetAddr &addr) const; std::string ToString() const; bool IsValid() const; friend bool operator==(const CSubNet& a, const CSubNet& b); friend bool operator!=(const CSubNet& a, const CSubNet& b); friend bool operator<(const CSubNet& a, const CSubNet& b); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(network); READWRITE(FLATDATA(netmask)); READWRITE(FLATDATA(valid)); } }; /** A combination of a network address (CNetAddr) and a (TCP) port */ class CService : public CNetAddr { protected: unsigned short port; // host order public: CService(); CService(const CNetAddr& ip, unsigned short port); CService(const struct in_addr& ipv4Addr, unsigned short port); CService(const struct sockaddr_in& addr); explicit CService(const char *pszIpPort, int portDefault, bool fAllowLookup = false); explicit CService(const char *pszIpPort, bool fAllowLookup = false); explicit CService(const std::string& strIpPort, int portDefault, bool fAllowLookup = false); explicit CService(const std::string& strIpPort, bool fAllowLookup = false); void Init(); void SetPort(unsigned short portIn); unsigned short GetPort() const; bool GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const; bool SetSockAddr(const struct sockaddr* paddr); friend bool operator==(const CService& a, const CService& b); friend bool operator!=(const CService& a, const CService& b); friend bool operator<(const CService& a, const CService& b); std::vector<unsigned char> GetKey() const; std::string ToString() const; std::string ToStringPort() const; std::string ToStringIPPort() const; CService(const struct in6_addr& ipv6Addr, unsigned short port); CService(const struct sockaddr_in6& addr); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(FLATDATA(ip)); unsigned short portN = htons(port); READWRITE(FLATDATA(portN)); if (ser_action.ForRead()) port = ntohs(portN); } }; class proxyType { public: proxyType(): randomize_credentials(false) {} proxyType(const CService &proxy, bool randomize_credentials=false): proxy(proxy), randomize_credentials(randomize_credentials) {} bool IsValid() const { return proxy.IsValid(); } CService proxy; bool randomize_credentials; }; enum Network ParseNetwork(std::string net); std::string GetNetworkName(enum Network net); void SplitHostPort(std::string in, int &portOut, std::string &hostOut); bool SetProxy(enum Network net, const proxyType &addrProxy); bool GetProxy(enum Network net, proxyType &proxyInfoOut); bool IsProxy(const CNetAddr &addr); bool SetNameProxy(const proxyType &addrProxy); bool HaveNameProxy(); bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions = 0, bool fAllowLookup = true); bool Lookup(const char *pszName, CService& addr, int portDefault = 0, bool fAllowLookup = true); bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault = 0, bool fAllowLookup = true, unsigned int nMaxSolutions = 0); bool LookupNumeric(const char *pszName, CService& addr, int portDefault = 0); bool ConnectSocket(const CService &addr, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed = 0); bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed = 0); /** Return readable error string for a network error code */ std::string NetworkErrorString(int err); /** Close socket and set hSocket to INVALID_SOCKET */ bool CloseSocket(SOCKET& hSocket); /** Disable or enable blocking-mode for a socket */ bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking); /** * Convert milliseconds to a struct timeval for e.g. select. */ struct timeval MillisToTimeval(int64_t nTimeout); #endif // BITCOIN_NETBASE_H
[ "sarathb922@gmail.com" ]
sarathb922@gmail.com
dfa393d840f92f04bf3655a6df930303666a04bd
e50828cb0c2e7099c5334bf326f7947e618aa722
/history.h
e9995dcf89e067ce27970526622c0ed473fba74d
[]
no_license
xuchuanxin/Qt-ImageViewer
0441f7bca0c8ae20ce169461d828a87f0a2277b0
2d0dfe718d8b1c30348672a9ed04dd9b870ec945
refs/heads/master
2023-06-26T02:13:35.884832
2018-03-11T15:10:23
2018-03-11T15:10:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
758
h
#ifndef HISTORY_H #define HISTORY_H #include <stack> #include "imageprocessor.h" enum {ROTATE = 0, SCALE = 1, CROP = 2, SELECT_ZOOM = 3}; struct command { int type; qreal factor; qreal factor2; QImage img; QRect *rectangle; QPoint scrollPoints; }; class History { public: History(ImageProcessor * processor); void addHistory(command c); void undo(QGraphicsView * graphicsArea); void redo(QGraphicsView * graphicsArea); void clearHistory(); void reset(QGraphicsView * graphicsArea); bool hasUndo(); bool hasRedo(); void setOrg(QImage img); private: ImageProcessor *imageProcessor; std::stack<command> undoStack; std::stack<command> redoStack; QImage orgImg; }; #endif // HISTORY_H
[ "re13amr@gmail.com" ]
re13amr@gmail.com
25b284247191c0ea4c2ff52431477b939233aa30
9c7461a77fdefa04f3794d4a9d6f85ed9ff96c91
/day17/day17/源.cpp
b971e4825b6afa6aebd9067fb7962e088fccfe81
[]
no_license
bengbengxiong/class
b333cb9c57d7013c996ad19009a4c396090f404e
f2b77aac918051b7e5d77805469ca8bf0a0b944e
refs/heads/master
2020-03-31T08:03:24.549684
2019-07-07T04:25:11
2019-07-07T04:25:11
152,043,559
0
0
null
null
null
null
UTF-8
C++
false
false
433
cpp
#include <iostream> using namespace std; int main() { /*int a[] = { 1, 2, 3, 4, 5 }; int *p[] = { a, a + 1, a + 2, a + 3 }; int **q = p; cout << *(p[0] + 1) + **(q + 2) << endl; cout << *(p[0] + 1) << endl; cout << **(q + 2) << endl;*/ /*char *p = "abc"; char *q = "abc123"; while (*p == *q) { printf("%c %c", *p, *q); }*/ long long a = 1, b = 2, c = 3; printf("%d %d %d", a, b, c); system("pause"); return 0; }
[ "1620585746@qq.com" ]
1620585746@qq.com
b8c69009726ea7b57b4095a5f1a400a33a2f0e40
18cf0f85c48c33c76177743a2de5c0384ec4e9fb
/Source/ArenaBattle/Private/ABPlayerController.cpp
a3946124df37431aeb10a6645b1c6be5c186d338
[]
no_license
AnnoyedSloth/ArenaBattle
fc35b0ee19d10b9e0eeb64a7fb011b6d3cfb74b8
b8b85f125fdbb77ba46270913fe5d07568da84a1
refs/heads/master
2020-06-17T03:13:57.310177
2019-07-16T09:54:30
2019-07-16T09:54:30
195,777,333
1
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ABPlayerController.h" #include "ABHUDWidget.h" #include "ABPlayerState.h" #include "ABCharacter.h" AABPlayerController::AABPlayerController() { static ConstructorHelpers::FClassFinder<UABHUDWidget> UI_HUD(TEXT("/Game/UI/UI_HUD.UI_HUD_C")); if (UI_HUD.Succeeded()) { hudWidgetClass = UI_HUD.Class; } } void AABPlayerController::PostInitializeComponents() { Super::PostInitializeComponents(); //ABLOG_S(Warning); } void AABPlayerController::Possess(APawn* pawn) { //ABLOG_S(Warning); Super::Possess(pawn); } void AABPlayerController::BeginPlay() { Super::BeginPlay(); FInputModeGameOnly inputMode; SetInputMode(inputMode); hudWidget = CreateWidget<UABHUDWidget>(this, hudWidgetClass); hudWidget->AddToViewport(); myPlayerState = Cast<AABPlayerState>(PlayerState); ABCHECK(myPlayerState); hudWidget->BindPlayerState(myPlayerState); myPlayerState->onPlayerStateChanged.Broadcast(); } void AABPlayerController::NPCKill(AABCharacter* killedNPC) const { myPlayerState->AddExp(killedNPC->GetExp()); }
[ "sksk31052@hanmail.net" ]
sksk31052@hanmail.net
e78220df55b6c7dafa3a3144ee06001990388a9d
a66d5c56036b6fe6a5fff65bf914e5ad145ba66a
/mymarlin/src/ttbar.cc
1b1005dd0356d5ed129fc202f4a1ee3c248d887f
[]
no_license
msohailamjad/ttbar
2f08687b7e3a348fba7266e2ba647bb85092b826
7f353c61cb470620d715509d0a520e26701096cc
refs/heads/master
2021-09-24T11:56:27.139024
2018-10-09T14:31:58
2018-10-09T14:31:58
125,369,414
0
0
null
null
null
null
UTF-8
C++
false
false
72,631
cc
#include "ttbar.h" #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <TStyle.h> #include <LCIOSTLTypes.h> #include <EVENT/LCCollection.h> #include <EVENT/ReconstructedParticle.h> #include <UTIL/PIDHandler.h> #include <EVENT/MCParticle.h> #include <EVENT/ParticleID.h> #include <TH1.h> #include <TH2.h> #include <EVENT/LCRelation.h> #include <EVENT/Vertex.h> #include "marlin/VerbosityLevels.h" using namespace lcio; using namespace marlin; using namespace std; ttbar attbar; ttbar::ttbar() : Processor("ttbar") { _description = "Analyse ttbar to fully hadronic mode at Reconstruction and MC level"; registerProcessorParameter( "ROOTFileName","Output ROOT File Name", _hfilename,std::string("ttbar.root")); registerInputCollection( LCIO::RECONSTRUCTEDPARTICLE, "RefinedJets" , "Name of the Jets collection" , _myJetsCollection, std::string("myJets")); registerInputCollection( LCIO::RECONSTRUCTEDPARTICLE, "RefinedJets_vtx_RP" , "Name of the Vertex Jets collection" , _myvtxJetsCollection,std::string("myvtxJets")); registerInputCollection( LCIO::LCRELATION, "RefinedJets_rel" , "Name of the Vertex Jets relation" , _myrelJetsCollection, std::string("myrelJets")); registerInputCollection( LCIO::MCPARTICLE, "MCCollection" , "MC collection (MCParticle for Mokka, MCParticlesSkimmed for DST)" , _mcCollection, std::string("MCParticle")); } void ttbar::init() { mccostheta=-999; nforward=0; nback =0; _nRun = 0; _nEvt = 0; _eventnumber=0; ntops=0; nbqs=0; ncqs=0; nws=0; nwhs=0; nwls=0; nqs=0; ROOTfile = new TFile(_hfilename.c_str(), "RECREATE", _hfilename.c_str()); h_btag = new TH1F ("BTag", "BTag", 100, 0,1 ); h_btag1 = new TH1F ("BTag2", "BTag2", 100, 0,1 ); h_btag2 = new TH1F ("BTag3", "BTag3", 100, 0,1 ); h_btagz = new TH1F ("BTagZ", "BTagZ", 100, 0,1 ); h_btagz1 = new TH1F ("BTagZ2", "BTagZ2", 100, 0,1 ); b1en = new TH1F ("b1energy", "b1energy", 100, 0,200 ); b2en = new TH1F ("b2energy", "b2energy", 100, 0,200 ); w1en = new TH1F ("w1energy", "w1energy", 100, 0,300 ); w2en = new TH1F ("w2energy", "w2energy", 100, 0,300 ); h_ctag = new TH1F ("CTag", "CTag", 100, 0,1 ); h_top1mass = new TH1F ("Top1Mass", "Top1Mass", 100, 0,350); h_top2mass = new TH1F ("Top2Mass", "Top2Mass", 100, 0,350 ); mtforchi = new TH1F ("mt", "mt", 100, 0,300); etforchi = new TH1F ("et", "et", 100, 0,350); pbforchi = new TH1F ("pb", "pb", 100, 0,200); cosbmcbrec=new TH1F ("CosbMCvsbRec", "CosbMCvsbRec", 100, -1,1 ); coscmcbrec=new TH1F ("CoscMCvsbRec", "CoscMCvsbRec", 100, -1,1 ); costmctrecdiff=new TH1F ("CostMCtRecdiff", "CostMCtRecdiff", 100, -1,1 ); costmctrecdiffbc=new TH1F ("CostMCtRecdiffbc", "CostMCtRecdiffbc", 100, -1,1 ); coscmcbrecvsbmc2=new TH2F ("CoscMCbRecbMC2D2", "CoscMCvsbRecbMC2D2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc22=new TH2F ("CoscMCbRecbMC2Dn2", "CoscMCvsbRecbMC2Dn2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc32=new TH2F ("CoscMCbRecbMC2Dnt2", "CoscMCvsbRecbMC2Dnt2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc42=new TH2F ("CoscMCbRecbMC2Dntt2", "CoscMCvsbRecbMC2Dntt2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmcc2=new TH2F ("CoscMCbRecbMC2Dc2", "CoscMCvsbRecbMC2Dc2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc2c2=new TH2F ("CoscMCbRecbMC2Dnc2", "CoscMCvsbRecbMC2Dnc2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc3c2=new TH2F ("CoscMCbRecbMC2Dntc2", "CoscMCvsbRecbMC2Dntc2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc4c2=new TH2F ("CoscMCbRecbMC2Dnttc2", "CoscMCvsbRecbMC2Dnttc2", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc1=new TH2F ("CoscMCbRecbMC2D1", "CoscMCvsbRecbMC2D1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc21=new TH2F ("CoscMCbRecbMC2Dn1", "CoscMCvsbRecbMC2Dn1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc31=new TH2F ("CoscMCbRecbMC2Dnt1", "CoscMCvsbRecbMC2Dnt1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc41=new TH2F ("CoscMCbRecbMC2Dntt1", "CoscMCvsbRecbMC2Dntt1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmcc1=new TH2F ("CoscMCbRecbMC2Dc1", "CoscMCvsbRecbMC2Dc1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc2c1=new TH2F ("CoscMCbRecbMC2Dnc1", "CoscMCvsbRecbMC2Dnc1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc3c1=new TH2F ("CoscMCbRecbMC2Dntc1", "CoscMCvsbRecbMC2Dntc1", 100, -1,1, 100, -1,1 ); coscmcbrecvsbmc4c1=new TH2F ("CoscMCbRecbMC2Dnttc1", "CoscMCvsbRecbMC2Dnttc1", 100, -1,1, 100, -1,1 ); cosbreccmcbtag2 =new TH2F ("CoscMCbRecBtag2", "CoscMCvsbRecBtag2", 100, 0,1, 100, -1,1 ); cosbreccmcbtagc2 =new TH2F ("CoscMCbRecBtagc2", "CoscMCvsbRecBtagc2", 100, 0,1, 100, -1,1 ); cosbreccmcctag2 =new TH2F ("CoscMCbRecCtag2", "CoscMCvsbRecCtag2", 100, 0,1, 100, -1,1 ); cosbreccmcctagc2 =new TH2F ("CoscMCbRecCtagc2", "CoscMCvsbRecCtagc2", 100, 0,1, 100, -1,1 ); cosbreccmcbtag1 =new TH2F ("CoscMCbRecBtag1", "CoscMCvsbRecBtag1", 100, 0,1, 100, -1,1 ); cosbreccmcbtagc1 =new TH2F ("CoscMCbRecBtagc1", "CoscMCvsbRecBtagc1", 100, 0,1, 100, -1,1 ); cosbreccmcctag1 =new TH2F ("CoscMCbRecCtag1", "CoscMCvsbRecCtag1", 100, 0,1, 100, -1,1 ); cosbreccmcctagc1 =new TH2F ("CoscMCbRecCtagc1", "CoscMCvsbRecCtagc1", 100, 0,1, 100, -1,1 ); btagsusp2=new TH1F ("BTagSusp2", "BTagSusp2", 100, 0,1 ); btagsusp1=new TH1F ("BTagSusp1", "BTagSusp1", 100, 0,1 ); cosb1mcb2mc =new TH1F ("cosb1mcb2mc", "cosb1mcb2mc", 100, -1,1 ); cosb1mccmc =new TH1F ("cosb1mccmc", "cosb1mccmc", 100, -1,1 ); cosb2mccmc =new TH1F ("cosb2mccmc", "cosb2mccmc", 100, -1,1 ); cosb1mcb2mccut =new TH1F ("cosb1mcb2mccut", "cosb1mcb2mccut", 100, -1,1 ); cosb1mccmccut =new TH1F ("cosb1mccmccut", "cosb1mccmccut", 100, -1,1 ); cosb2mccmccut =new TH1F ("cosb2mccmccut", "cosb2mccmccut", 100, -1,1 ); cosb1mcb2mcb1mccmc =new TH2F ("Cosb1mcb2mcb1mccms", "Cosb1mcb2mcb1mccmc", 100, -1,1, 100, -1,1 ); cosb1mcb2mcb2mccmc =new TH2F ("Cosb1mcb2mcb2mccms", "Cosb1mcb2mcb2mccmc", 100, -1,1, 100, -1,1 ); costmctrecdiff1=new TH1F ("CostMCtRecdiff1", "CostMCtRecdiff1", 100, -1,1 ); costmctrecdiff2=new TH1F ("CostMCtRecdiff2", "CostMCtRecdiff2", 100, -1,1 ); costmctrecdiff3=new TH1F ("CostMCtRecdiff3", "CostMCtRecdiff3", 100, -1,1 ); costmctrecdiff4=new TH1F ("CostMCtRecdiff4", "CostMCtRecdiff4", 100, -1,1 ); costmctrecdiff5=new TH1F ("CostMCtRecdiff5", "CostMCtRecdiff5", 100, -1,1 ); h_costheta = new TH1F ("CosTheta", "Costheta", 100, -1,1.1); h_costheta1 = new TH1F ("CosTheta1", "Costheta1", 100, -1,1.1); h_costheta2 = new TH1F ("CosTheta2", "Costheta2", 100, -1,1.1); h_costhetaavg = new TH1F ("CosThetaavg", "Costhetaavg", 100, -1,1.1); h_costheta2d= new TH2F ("CosTheta2d", "Costheta2d", 100, -1,1.1, 100 ,-1,1.1); h_Chargesum= new TH1F ("CargeSum", "ChargeSum", 10, -5,5); h_Chargesum2= new TH1F ("CargeSumVtx", "ChargeSumVtx", 10, -5,5); h_Chargesum3= new TH1F ("CargeSumVtx_rp", "ChargeSumVtx_rp", 10, -5,5); h_BmesonQ = new TH1F ("B0_Mesons_q", "B0_Mesons_q", 10, -5,5); h_BmmesonQ = new TH1F ("Bm_Mesons_q", "Bm_Mesons_q", 10, -5,5); h_BpmesonQ = new TH1F ("Bp_Mesons_q", "Bp_Mesons_q", 10, -5,5); h_BmesonQnoB = new TH1F ("B0_Mesons_qnoB", "B0_Mesons_qnoB", 10, -5,5); h_BmmesonQnoB = new TH1F ("Bm_Mesons_qnoB", "Bm_Mesons_qnoB", 10, -5,5); h_BpmesonQnoB = new TH1F ("Bp_Mesons_qnoB", "Bp_Mesons_qnoB", 10, -5,5); h_BmpmesonQ = new TH1F ("Bp_Bm_Mesons_q", "Bp_Bm_Mesons_q", 10, -5,5); h_bplusartonQ = new TH1F ("bp_parton_q", "bp_parton_q", 10, -5,5); h_bminuspartonQ = new TH1F ("bm_parton_q", "bm_parton_q", 10, -5,5); h_bplusartonQ2 = new TH1F ("bp_parton_q2", "bp_parton_q2", 10, -5,5); h_bminuspartonQ2 = new TH1F ("bm_parton_q2", "bm_parton_q2", 10, -5,5); h_wtop1mass = new TH1F ("WTop1Mass", "WTop1Mass", 100, 0,350); h_wtop2mass = new TH1F ("WTop2Mass", "WTop2Mass", 100, 0,350); h_w1mass = new TH1F ("W1Mass", "W1Mass", 100, 0,210); h_w2mass = new TH1F ("W2Mass", "W2Mass", 100, 0,210); h_top1massuncut= new TH1F ("Top1MassUncut", "Top1MassUncut", 100, 0,400); h_top2massuncut= new TH1F ("Top2MassUncut", "Top2MassUncut", 100, 0,400); h_top12mass= new TH1F ("Top12Mass", "Top12Mass", 100, 0,600); h_top1top2mass= new TH2F ("Top1Top2Mass", "Top1Top2Mass", 100, 0,400, 100, 0,400); h_top1top2mass_sel= new TH2F ("Top1Top2Mass_sel", "Top1Top2Mass_sel", 100, 0,400, 100, 0,400); h_mccosthetatop = new TH1F ("MCCosThetaT", "MCCosthetaT", 100, -1,1); h_mccosthetatopbar = new TH1F ("MCCosThetaTbar", "MCCosthetaTbar", 100, -1,1); h_vtxcharge = new TH1F ("Vertex_Charge", "Vertex_Charge", 100, -3,3); h_costhetatop= new TH1F ("CosThetaTop", "CosthetaTop", 100, -1,1); h_costhetatopbar = new TH1F ("CosThetaTopBar", "CosthetaTopBar", 100, -1,1); h_Bangle = new TH2F ("B0angle", "B0angle", 10, -5,5, 1000, -1,1.1); h_Bpangle = new TH2F ("Bpangle", "Bpangle", 10, -5,5, 1000, -1,1.1); h_Bmangle = new TH2F ("Bmangle", "Bmangle", 10, -5,5, 1000, -1,1.1); topangle = new TH1F ("TopAngle", "TopAngle", 100, -1,1); topangle_bc = new TH1F ("TopAngle_bc", "TopAngle_bc", 100, -1,1); topangle_mc = new TH1F ("TopAngle_mc", "TopAngle_mc", 100, -1,1); topangle_fmc = new TH1F ("TopAngle_fmc", "TopAngle_fmc", 100, -1,1); topangle_fmc2 = new TH1F ("TopAngle_fmc2", "TopAngle_fmc2", 100, -1,1); topangle_fmc3 = new TH1F ("TopAngle_fmc3", "TopAngle_fmc3", 100, -1,1); topangle_diff = new TH1F ("TopAngle_diff", "TopAngle_diff", 100, -1,1); topangle_c1 = new TH1F ("TopAngle_c1", "TopAngle_c1", 100, -1,1); topangle_c1bc = new TH1F ("TopAngle_c1bc", "TopAngle_c1bc", 100, -1,1); topangle_c2 = new TH1F ("TopAngle_c2", "TopAngle_c2", 100, -1,1); topangle_c2bc = new TH1F ("TopAngle_c2bc", "TopAngle_c2bc", 100, -1,1); topangleq = new TH1F ("TopAngle_q", "TopAngle_q", 100, -1,1); topangleq_c = new TH1F ("TopAngle_qc", "TopAngle_qc", 100, -1,1 ); Topanglecomp1 = new TH1F ("Topanglecomp1","Topanglecomp1", 100, -1,1); Topanglecomp2 = new TH1F ("Topanglecomp2","Topanglecomp2", 100, -1,1); Topanglecomp3 = new TH1F ("Topanglecomp3","Topanglecomp3", 100, -1,1); Topanglecomp4 = new TH1F ("Topanglecomp4","Topanglecomp4", 100, -1,1); Topanglecomp1c = new TH1F ("Topanglecomp1c","Topanglecomp1c", 100, -1,1); Topanglecomp2c = new TH1F ("Topanglecomp2c","Topanglecomp2c", 100, -1,1); Topanglecomp3c = new TH1F ("Topanglecomp3c","Topanglecomp3c", 100, -1,1); Topanglecomp4c = new TH1F ("Topanglecomp4c","Topanglecomp4c", 100, -1,1); Topmasseff = new TH1F ("TopMassEff", "TopMassEff", 500, 0,550); Topmasseff1 = new TH1F ("TopMassEff1", "TopMassEff1", 500, 0,550); Topmasseff2 = new TH1F ("TopMassEff2", "TopMassEff2", 500, 0,550); Topmasseff3 = new TH1F ("TopMassEff3", "TopMassEff3", 500, 0,550); Topmasseff4 = new TH1F ("TopMassEff4", "TopMassEff4", 500, 0,550); Topmasseff5 = new TH1F ("TopMassEff5", "TopMassEff5", 500, 0,550); Topmasseff1t = new TH1F ("TopMassEff1t", "TopMassEff1t", 500, 0,550); Topmasseff2t = new TH1F ("TopMassEff2t", "TopMassEff2t", 500, 0,550); Topmasseff3t = new TH1F ("TopMassEff3t", "TopMassEff3t", 500, 0,550); Topmasseff4t = new TH1F ("TopMassEff4t", "TopMassEff4t", 500, 0,550); Topmasseff5t = new TH1F ("TopMassEff5t", "TopMassEff5t", 500, 0,550); Topmasseffchi200 = new TH1F ("TopMassEffchi200", "TopMassEffchi200", 500, 0,550); Topmasseffchi100 = new TH1F ("TopMassEffchi100", "TopMassEffchi100", 500, 0,550); Topmasseffchi50 = new TH1F ("TopMassEffchi50", "TopMassEffchi50", 500, 0,550); Topmasseffchi40 = new TH1F ("TopMassEffchi40", "TopMassEffchi40", 500, 0,550); Topmasseffchi30 = new TH1F ("TopMassEffchi30", "TopMassEffchi30", 500, 0,550); Topmasseffchi200bt = new TH1F ("TopMassEffchi200bt", "TopMassEffchi200bt", 500, 0,550); Topmasseffchi100bt = new TH1F ("TopMassEffchi100bt", "TopMassEffchi100bt", 500, 0,550); Topmasseffchi50bt = new TH1F ("TopMassEffchi50bt", "TopMassEffchi50bt", 500, 0,550); Topmasseffchi40bt = new TH1F ("TopMassEffchi40bt", "TopMassEffchi40bt", 500, 0,550); Topmasseffchi30bt = new TH1F ("TopMassEffchi30bt", "TopMassEffchi30bt", 500, 0,550); Topmasseffchi200t = new TH1F ("TopMassEffchi200t", "TopMassEffchi200t", 500, 0,550); Topmasseffchi100t = new TH1F ("TopMassEffchi100t", "TopMassEffchi100t", 500, 0,550); Topmasseffchi50t = new TH1F ("TopMassEffchi50t", "TopMassEffchi50t", 500, 0,550); Topmasseffchi40t = new TH1F ("TopMassEffchi40t", "TopMassEffchi40t", 500, 0,550); Topmasseffchi30t = new TH1F ("TopMassEffchi30t", "TopMassEffchi30t", 500, 0,550); topmasschia= new TH2F ("TopMassChia", "TopMassChia", 100, 0,400, 100,0,500 ); topmasschib= new TH2F ("TopMassChib", "TopMassChib", 100, 0,400, 100,0,1000 ); topmasschiaE= new TH2F ("TopMassChiaE", "TopMassChiaE", 100, 0,400, 100,0,500 ); topmasschibE= new TH2F ("TopMassChibE", "TopMassChibE", 100, 0,400, 100,0,1000 ); topmasschiaP= new TH2F ("TopMassChiaP", "TopMassChiaP", 100, 0,400, 100,0,500 ); topmasschibP= new TH2F ("TopMassChibP", "TopMassChibP", 100, 0,400, 100,0,1000 ); topquarkangle = new TH1F ("TopQuarkAngle", "TopQuarkAngle", 100, -1,1); topbarquarkangle = new TH1F ("TopBarQuarkAngle", "TopBarQuarkAngle", 100, -1,1 ); topquarkangleq = new TH1F ("TopQuarkAngle_Q", "TopQuarkAngle_Q", 100, -1,1 ); topbarquarkangleq = new TH1F ("TopBarQuarkAngle_Q", "TopBarQuarkAngle_Q", 100, -1,1); topbarquarkangleq_c = new TH1F ("TopBarQuarkAngle_QC", "TopBarQuarkAngle_QC", 100, -1,1); topquarkangleqpt = new TH1F ("TopQuarkAngle_QP", "TopQuarkAngle_QP", 100, -1,1 ); topbarquarkangleqpt = new TH1F ("TopBarQuarkAngle_QP", "TopBarQuarkAngle_QP", 100, -1,1); cost1t2 = new TH1F ("Angle_t1t2", "Angle_t1t2", 100, -1,1); qmcb_b = new TH2F ("qmcb_b", "qmcb_b", 10, -5,5, 10, -5,5); qmcab_ab = new TH2F ("qmcab_ab","qmcab_ab", 10, -5,5, 10, -5,5); Wrong_Q= new TH1F ("WrongQ", "WrongQ", 100, -1,1); QSum= new TH1F ("QSum_sorted", "QSum_sorted", 10, -5,5); QSum2= new TH1F ("QSum_sorted2", "QSum_sorted2", 10, -5,5); QSum3= new TH1F ("QSum_sorted3", "QSum_sorted3", 10, -5,5); QSum4= new TH1F ("QSum_sorted4", "QSum_sorted4", 10, -5,5); h_vtxmom = new TH1F ("VtxPt", "VtxPt", 100, 0,100); h_vtxpartmom = new TH1F ("VtxPartPt", "VtxPartPt", 100, 0,40); h_vtxpartmomsum = new TH1F ("VtxPartPtSum", "VtxPartPtSum", 100, 0,100); QPtSum = new TH1F ("QPtSum", "QPtSum", 100, -1.1, 1.1); QPtSumb = new TH1F ("QPtSumb", "QPtSumb", 100, -1.1, 1.1); QPtSumbbar = new TH1F ("QPtSumbbar", "QPtSumbar", 100, -1.1, 1.1); NMCTops = new TH1F ("NMCTops", "NMCTops", 10, 0 , 10); NMCBqs = new TH1F ("NMCBqs", "NMCBqs", 10, 0 , 10); NMCWs = new TH1F ("NMCWs", "NMCWs", 10, 0 , 10); NMCWfs = new TH1F ("NMCWfs", "NMCWfs", 10, -5 , 5); NMCWfmass = new TH1F ("NMCWfmass", "NMCWfmass", 160, 0 , 160); NMCTopfmass = new TH1F ("NMCTopfmass", "NMCTopfmass", 500, 0 , 400); NMCTopfmass_sum = new TH1F ("NMCTopfmass_sum", "NMCTopfmass_sum", 500, 0 , 500); NMCTopftmass = new TH1F ("NMCTopftmass", "NMCTopftmass", 500, 0 , 550); NMCTop12fmass = new TH2F ("NMCTop12fmass", "NMCTop12fmass", 500, 0 , 400, 500,0,400); NMCTop12fmass_sel = new TH2F ("NMCTop12fmass_sel", "NMCTop12fmass_sel", 500, 0 , 400, 500,0,400); NMCTop12fmass_sel1 = new TH2F ("NMCTop12fmass_sel1", "NMCTop12fmass_sel1", 500, 0 , 400, 500,0,400); NMCTop12fmass_sel2 = new TH2F ("NMCTop12fmass_sel2", "NMCTop12fmass_sel2", 500, 0 , 400, 500,0,400); NMCW12fmass = new TH2F ("NMCW12fmass", "NMCW12fmass", 160, 0 , 160, 160,0,160); NMCW12fenergy = new TH2F ("NMCW12fenergy", "NMCW12fenergy", 300, 0 , 400, 300,0,400); NMCW1theta = new TH1F ("NMCW1theta", "NMCW1theta", 100, -1 , 1); NMCW2theta = new TH1F ("NMCW2theta", "NMCW2theta", 100, -1 , 1); NMCW1Etheta = new TH2F ("NMCW1Etheta", "NMCW1Etheta", 100, -1 , 1, 300,0,400); NMCW2Etheta = new TH2F ("NMCW2Etheta", "NMCW2Etheta", 100, -1 , 1, 300,0,400); recW12fenergy = new TH2F ("recW12fenergy", "recW12fenergy", 300, 0 , 400, 300,0,400); NMCbbfmass = new TH1F ("NMCbbfmass", "NMCbbfmass", 500, 0 , 400); NMCbbfmasszww = new TH1F ("NMCbbfmasszww", "NMCbbfmasszww", 500, 0 , 400); NMCbbfmasstt = new TH1F ("NMCbbfmasstt", "NMCbbfmasstt", 500, 0 , 400); NRecTops = new TH1F ("NRecTops", "NRecTops", 10, 0 , 10); NVtx = new TH1F ("NVtx", "NVtx", 10, 0 , 10); NEvts = new TH1F ("NEvts", "NEvts", 10, 0,4); QPtSum0V = new TH1F ("QPtSum0V", "QPtSum0V", 100, -1.1, 1.1); QPtSum1V = new TH1F ("QPtSum1V", "QPtSum1V", 100, -1.1, 1.1); QPtSum2V = new TH1F ("QPtSum2V", "QPtSum2V", 100, -1.1, 1.1); QPtSum1V_S = new TH1F ("QPtSum1V_S", "QPtSum1V_S", 100, -1.1, 1.1); QPtSum2V_S = new TH1F ("QPtSum2V_S", "QPtSum2V_S", 100, -1.1, 1.1); QPtSumVtx1 = new TH1F ("QPtSumVtx1", "QPtSumVtx1", 100, -1.1, 1.1); QPtSumVtx2 = new TH1F ("QPtSumVtx2", "QPtSumVtx2", 100, -1.1, 1.1); PtSumVtx1 = new TH1F ("PtSumVtx1", "PtSumVtx1", 100, 0,100); PtSumVtx2 = new TH1F ("PtSumVtx2", "PtSumVtx2", 100, 0,100); QSum_mcbp = new TH1F ("QSum_mcbp", "QSum_mcbp", 10, -5,5); QSum_mcabp = new TH1F ("QSum_mcabp", "QSum_mcabp", 10, -5,5); b1jetvq_b = new TH1F ("b1jetvq_b ", "b1jetvq_b", 10, -5,5); b2jetvq_b = new TH1F ("b2jetvq_b", "b2jetvq_b", 10, -5,5); b1jetvq_ab = new TH1F ("b1jetvq_ab ", "b1jetvq_ab", 10, -5,5); b2jetvq_ab = new TH1F ("b2jetvq_ab", "b2jetvq_ab", 10, -5,5); b1jetvq_c1bc = new TH1F ("b1jetvq_c1bc ", "b1jetvq_c1bc", 10, -5,5); b2jetvq_c1bc = new TH1F ("b2jetvq_c1bc", "b2jetvq_c1bc", 10, -5,5); b1jetvq_c2bc = new TH1F ("b1jetvq_c2bc ", "b1jetvq_c2bc", 10, -5,5); b2jetvq_c2bc = new TH1F ("b2jetvq_c2bc", "b2jetvq_c2bc", 10, -5,5); b1jetvq_c1 = new TH1F ("b1jetvq_c1 ", "b1jetvq_c1", 10, -5,5); b2jetvq_c1 = new TH1F ("b2jetvq_c1", "b2jetvq_c1", 10, -5,5); b1jetvq_c2 = new TH1F ("b1jetvq_c2 ", "b1jetvq_c2", 10, -5,5); b2jetvq_c2 = new TH1F ("b2jetvq_c2", "b2jetvq_c2", 10, -5,5); QPtSumb_C = new TH1F ("QPtSumb_C", "QPtSumb_C", 100, -1.1, 1.1); QPtSumbbar_C = new TH1F ("QPtSumbbar_C", "QPtSumbbar_C", 100, -1.1, 1.1); QPtSum_mcbp = new TH1F ("QPtSum_mcbp", "QPtSum_mcbp", 100, -1.1, 1.1); QPtSum_mcabp = new TH1F ("QPtSum_mcabp", "QPtSum_mcabp", 100, -1.1, 1.1); gud_bjbmcangle = new TH1F ("gud_bjbmcangle", "gud_bjbmcangle", 100, -1, 1); bad_bjbmcangle = new TH1F ("bad_bjbmcangle", "bad_bjbmcangle", 100, -1, 1); gudbjmom = new TH1F ("gud_bjmom", "bad_bjmom", 100, 0, 140); badbjmom = new TH1F ("bad_bjmom", "bad_bjmom", 100, 0, 140); gudbjtag = new TH1F ("gud_bjtag", "bad_bjtag", 100, 0, 1); badbjtag = new TH1F ("bad_bjtag", "bad_bjtag", 100, 0, 1); b1mom = new TH1F ("b1mom", "b1mom", 100, 0, 140); b1momsel = new TH1F ("b1momsel", "b1momsel", 100, 0, 140); top1momvsmass = new TH2F ("t1pvm", "t1pvm", 100, 100, 300, 100, 0,160); btagvstheta1 = new TH2F ("BTagvsCosTheta1", "BTagvsCosTheta1", 100, -1, 1, 100, 0,1); btagvstheta2 = new TH2F ("BTagvsCosTheta2", "BTagvsCosTheta2", 100, -1, 1, 100, 0,1); btagvstheta3 = new TH2F ("BTagvsCosTheta3", "BTagvsCosTheta3", 100, -1, 1, 100, 0,1); btagvsen1 = new TH2F ("BTagvsEn1", "BTagvsCosEn1", 100, 0, 250, 100, 0,1); btagvsen2 = new TH2F ("BTagvsEn2", "BTagvsCosEn2", 100, 0, 250, 100, 0,1); mcbenergy = new TH1F ("mcbenergy", "mcbenergy", 100, 0, 250); h_mass34 = new TH1F ("mass34", "mass34", 100, 0, 400); h_mass35 = new TH1F ("mass35", "mass35", 100, 0, 400); h_mass36 = new TH1F ("mass36", "mass36", 100, 0, 400); h_bbmass = new TH1F ("bbmass", "bbmass", 100, 0, 400); h_bbmass_tag = new TH1F ("bbmass_tag", "bbmass_tag", 100, 0, 400); h_bbmass_notag = new TH1F ("bbmass_notag", "bbmass_notag", 100, 0, 400); h_bbmass_sel = new TH1F ("bbmass_sel", "bbmass_sel", 100, 0, 400); h_difff3456 = new TH1F ("difff3456", "difff3456", 100, 0, 500); h_difff3546 = new TH1F ("difff3546", "difff3546", 100, 0, 500); h_difff3645 = new TH1F ("difff3645", "difff3645", 100, 0, 500); _tree = new TTree("tree", "tree"); for(int i = 0 ; i < nJETS ; i++){ _jets[i] = new TLorentzVector(); std::stringstream name; name << "jet" << i; _tree->Branch(name.str().c_str(),"TLorentzVector",&_jets[i],16000,0); _tree->Branch((name.str()+"_btag").c_str(), &_jetsBtag[i], (name.str()+"_btag/F").c_str()); _tree->Branch((name.str()+"_ctag").c_str(), &_jetsCtag[i], (name.str()+"_ctag/F").c_str()); _tree->Branch((name.str()+"_bctag").c_str(), &_jetsBCtag[i], (name.str()+"_bctag/F").c_str()); _tree->Branch((name.str()+"_charge").c_str(), &_jetsCharge[i], (name.str()+"_charge/F").c_str()); _tree->Branch((name.str()+"_mass").c_str(), &_jetsMass[i], (name.str()+"_mass/F").c_str()); } _tree->Branch("runNumber", &_nRun, "runNumber/I"); _tree->Branch("eventNumber", &_nEvt, "eventNumber/I"); _tree->Branch("crossSection", &_xsec, "crossSection/F"); _Process = new TString(); _tree->Branch("Process","TString",&_Process,16000,0); for(int i = 0 ; i < 6 ; i++) { _MCf[i] = new TLorentzVector(); std::stringstream name; name << "MCfermion" << i; _tree->Branch(name.str().c_str(),"TLorentzVector",&_MCf[i],16000,0); name << "_PDG"; _tree->Branch(name.str().c_str(), &_MCfpdg[i], (name.str()+"/I").c_str()); } _tree->Branch("_mass34", &_jetsMass34, "_mass34/F"); _tree->Branch("_mass35", &_jetsMass35, "_mass35/F"); _tree->Branch("_mass36", &_jetsMass36, "_mass36/F"); _tree->Branch("_mass45", &_jetsMass45, "_mass45/F"); _tree->Branch("_mass46", &_jetsMass46, "_mass46/F"); _tree->Branch("_mass56", &_jetsMass56, "_mass56/F"); _tree->Branch("_t1mass", &_t1mass, "_t1mass/F"); _tree->Branch("_t2mass", &_t2mass, "_t2mass/F"); _tree->Branch("_t1t2mass", &_t1t2mass, "_t1t2mass/F"); _tree->Branch("CosTheta", &costheta, "costheta/F"); _tree->Branch("_W1mass", &_W1mass, "_W1mass/F"); _tree->Branch("_W2mass", &_W2mass, "_W2mass/F"); _tree->Branch("_WW1mass", &_WW1mass, "_WW1mass/F"); _tree->Branch("_WW2mass", &_WW2mass, "_WW2mass/F"); _tree->Branch("_Wt1mass", &_Wt1mass, "_Wt1mass/F"); _tree->Branch("_Wt2mass", &_Wt2mass, "_Wt2mass/F"); _tree->Branch("_Wtx1mass", &_Wtx1mass, "_Wxt1mass/F"); _tree->Branch("_Wtx2mass", &_Wtx2mass, "_Wtx2mass/F"); _tree->Branch("_costhetat", &_costhetat ,"_costhetat/F"); _tree->Branch("_costhetatbar", &_costhetatbar ,"_costhetatbar/F"); _tree->Branch("_costhetatq", &_costhetatq ,"_costhetatq/F"); _tree->Branch("_costhetatbarq", &_costhetatbarq ,"_costhetatbarq/F"); _tree->Branch("difff3456", &difff3456 ,"difff3456/F"); _tree->Branch("difff3546", &difff3546 ,"difff3546/F"); _tree->Branch("difff3645", &difff3645 ,"difff3645/F"); _tree->Branch("difftx1", &difftx1 ,"difftx1/F"); _tree->Branch("difftx2", &difftx2 ,"difftx2/F"); _tree->Branch("mcbenergx", &mcbenergx ,"mcbenergx/F"); _tree->Branch("mcbchargex", &mcbchargex ,"mcbchargex/F"); } void ttbar::processRunHeader(LCRunHeader* run) { _nRun++; } void ttbar::processEvent(LCEvent * evt) { _nEvt ++; cout << "\n------------------------------------------------" << endl; cout << "| ****** Run " << _runnumber << " Event Number " << _eventnumber << " ******** |" << endl; cout << "------------------------------------------------" << endl; ROOTfile->cd(); try { bool isttbar=true; bool iszww=false; qmcb = 0; qmcab = 0; isTop=false; ismyTop=false; isTop1=false; isTop2=false; B0Meson=true; BpMeson=true; BmMeson=true; int nmctops=0; int nmccqs=0; int nmcbqs=0; int nmcws=0; int nmcwhs=0; int nmcwls=0; mcbenergx=0; mcbchargex=0; float npartons; npartons=0; float chargeW1=0;; float chargeW2=0;; float charge1=0; float charge2=0; float charge3=0; float charge4=0; nbs=0; TLorentzVector system; TLorentzVector MCWf1; TLorentzVector MCWf2; TLorentzVector MCbf1; TLorentzVector MCbf2; TLorentzVector MCbbf; TLorentzVector q1; TLorentzVector q2; TLorentzVector q3; TLorentzVector q4; TLorentzVector q5; TLorentzVector q6; int top=0; // Get Process name and cross section *_Process = evt->getParameters().getStringVal("Process"); _xsec = evt->getParameters().getFloatVal("CrossSection_fb"); _eventnumber=evt->getEventNumber(); _runnumber=evt->getRunNumber(); LCCollection* mccol = evt->getCollection(_mcCollection); for(int i = 0 ; i <mccol->getNumberOfElements(); i++) { MCParticle *mcpart1 = dynamic_cast<MCParticle*>(mccol->getElementAt(i)); int PDG=mcpart1->getPDG(); TVector3 MCPMomentum = TVector3(mcpart1->getMomentum()); TLorentzVector mctVec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()); MCParticleVec mcpdau = mcpart1->getDaughters(); if(abs(PDG)==511||abs(PDG)==10511||abs(PDG)==513||abs(PDG)==10513||abs(PDG)==20513||abs(PDG)==515||abs(PDG)==531||abs(PDG)==10531||abs(PDG)==533||abs(PDG)==10533||abs(PDG)==20533 || abs(PDG)==535){ TLorentzVector B0Vec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()); B0MesonVec = B0Vec; B0Meson=false; } if(abs(PDG)==521||abs(PDG)==10521||abs(PDG)==523||abs(PDG)==10523||abs(PDG)==20523||abs(PDG)==525||abs(PDG)==541||abs(PDG)==10541||abs(PDG)==543||abs(PDG)==10543||abs(PDG)==545 || abs(PDG)==20543 ){ if(PDG>0){ TLorentzVector BpVec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()); BpMesonVec = BpVec ; BpMeson=false; }else if(PDG<0){ TLorentzVector BmVec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()); BmMesonVec= BmVec; BmMeson=false; } MCParticleVec BPar = mcpart1->getParents(); } if( abs(PDG)<5 ){ nqs++; npartons++; if(npartons<5) { // cout << " ************** Quarks ************ " << endl; // cout << PDG << " : " << mcpart1->getCharge()<< " : " << mcpart1->getEnergy()<< " : " << npartons <<" : " << MCPMomentum.Mag()<< " : " <<MCPEnergyx << endl; if (PDG==4 ){ //c quarks nmccqs++; ncqs++; TLorentzVector xmccVec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()) ; mccVec=xmccVec; } else if (PDG==-4 ){ TLorentzVector xmcacVec(TVector3(mcpart1->getMomentum()),mcpart1->getEnergy()) ; mcacVec=xmcacVec; nmccqs++; ncqs++; } if(npartons==1){ charge1=mcpart1->getCharge(); q1=mctVec; } if(npartons==2){ charge2=mcpart1->getCharge(); q2=mctVec; } if(npartons==3){ charge3=mcpart1->getCharge(); q3=mctVec; } if(npartons==4){ charge4=mcpart1->getCharge(); q4=mctVec; } } } chargeW1=charge1+charge2; // 1,2 for bbcyyc & bbuyyu 1,4 for yycyyu yyuyyc chargeW2=charge3+charge4; // 3,4 for bbxxxx and 2,3 yyxxxx if(fabs(chargeW1)>0) MCWf1 = q1+q2; if(fabs(chargeW2)>0) MCWf2 = q3+q4; if(abs(PDG)==5){ nbs++; if(nbs<3){ if(PDG==5) { q5=mctVec; MCbf1=mctVec; } if(PDG==-5) { q6=mctVec; MCbf2=mctVec; } } } MCbbf=q5+q6; system=MCbbf+ MCWf1+ MCWf2; // dift = fabs(MCTopf1.M()-MCTopf2.M()); if(chargeW1==1){ if(MCWf1.E()>0) MCTopf1= MCWf1; if(MCWf2.E()>0) MCTopf2= MCWf2; }else if(chargeW2==1){ if(MCWf2.E()>0) MCTopf1= MCWf2; if(MCWf1.E()>0) MCTopf2= MCWf1; } if(MCbbf.M()<88 || MCbbf.M()>94){ MCTopf1b= MCTopf1+q5; MCTopf2b= MCTopf2+q6; } MCTopf1= MCTopf1+q5; MCTopf2= MCTopf2+q6; if(MCWf1.E()>210||MCWf2.E()>210) isttbar=false; if (abs(PDG)==5 ){ nmcbqs++; nbqs++; mcbenergx=mcpart1->getEnergy(); if(nmcbqs<3) mcbenergy->Fill(mcpart1->getEnergy()); mcbchargex=mcpart1->getCharge(); if(nmcbqs<3) NMCBqs->Fill(nmcbqs); } if (abs(PDG)==24 ){ nws++; nmcws++; NMCWs->Fill(nmcws); MCParticleVec wdau = mcpart1->getDaughters(); for (u_int i=0; i< wdau.size();i++){ MCParticle *wdaus = wdau[i]; int wdaupdg = wdaus->getPDG() ; if( abs(wdaupdg)<6){ nmcwhs++; nwhs++; } else if( abs(wdaupdg)==11 || abs(wdaupdg)==13 || abs(wdaupdg)==15 ){ nmcwls++; nwls++; } } } if(abs(PDG)==6){ top++; nmctops++; if(nmctops<3) NMCTops->Fill(nmctops); TVector3 TopMom(mcpart1->getMomentum()[0],mcpart1->getMomentum()[1],mcpart1->getMomentum()[2]); mccostheta=TopMom.CosTheta(); ntops++; if(PDG==6 && nmctops<3 ){ h_mccosthetatop->Fill(mccostheta); topangle_mc->Fill(mccostheta); }else if(PDG== -6 && nmctops < 3 ){ h_mccosthetatopbar->Fill(mccostheta); mccosinustheta=-1*mccostheta; topangle_mc->Fill(mccosinustheta); } MCParticleVec tdau = mcpart1->getDaughters(); for (u_int i=0; i< tdau.size();i++){ MCParticle *tdaus = tdau[i]; int tdauPDG = tdaus->getPDG(); TLorentzVector topdauVec(TVector3(tdaus->getMomentum()),tdaus->getEnergy()); if (tdauPDG==5 ){ // cout << " *** MC b jet !!!" << " : " << tdaus->getEnergy() << endl; qmcb=tdaus->getCharge(); mcbVec=topdauVec; /* cout << " Angle B0 & b quark " << cos(B0MesonVec.Angle(mcbVec.Vect())) << endl; cout << " Angle Bp & b quark " << cos(BpMesonVec.Angle(mcbVec.Vect())) << endl; cout << " Angle Bm & b quark " << cos(BmMesonVec.Angle(mcbVec.Vect())) << endl; cout<<tdauPDG << " E : "<<topdauVec.E()<< " = "<< mcbVec.E() << " ,Px : " << topdauVec.X() << " =" << mcbVec.X() << endl; */ } else if (tdauPDG==-5 ){ // nmcbqs++; // nbqs++; qmcab=tdaus->getCharge(); mcabVec=topdauVec; /*cout << " *** MC bbar jet !!!" << " : " << tdaus->getEnergy() << endl; cout << " Angle B0 & bbar quark " << cos(B0MesonVec.Angle(mcabVec.Vect())) << endl; cout << " Angle Bp & bbar quark " << cos(BpMesonVec.Angle(mcabVec.Vect())) << endl; cout << " Angle Bm & bbar quark " << cos(BmMesonVec.Angle(mcabVec.Vect())) << endl; cout<<tdauPDG << " E : "<<topdauVec.E()<< " = "<< mcabVec.E() << " ,Px : " << topdauVec.X() << " =" << mcabVec.X() << endl;*/ } } } } /*cout << "W1 " << chargeW1 << " W2 " << chargeW2 << endl; cout << "Mass W 1 " << MCWf1.M() << " Mass W2 " << MCWf2.M() << endl; cout << " Tops Mass " << MCTopf1.M()<< " : " << MCTopf2.M() << endl;*/ mctopVec = MCTopf1; mcatopVec = MCTopf2; NMCWfs->Fill(chargeW1); NMCWfs->Fill(chargeW2); if(MCWf1.M()>3) NMCWfmass->Fill(MCWf1.M()); if(MCWf2.M()>3) NMCWfmass->Fill(MCWf2.M()); NMCW12fenergy->Fill(MCWf1.E(),MCWf2.E()); NMCTopfmass->Fill(MCTopf1.M()); NMCTopfmass->Fill(MCTopf2.M()); NMCTopfmass_sum->Fill(MCTopf1.M()+MCTopf2.M()); if(chargeW1==1 && MCTopf1.M()<120 ) NMCW1Etheta->Fill(MCWf1.CosTheta(),MCWf1.E()); if(chargeW2==-1 && MCTopf2.M()<120 ) NMCW2Etheta->Fill(MCWf2.CosTheta(),MCWf2.E()); if(MCWf1.E()>200 ) NMCW1theta->Fill(MCWf1.CosTheta()); if(MCWf2.E()>200 ) NMCW2theta->Fill(MCWf2.CosTheta()); NMCTopftmass->Fill(system.M()); if(MCbbf.M()>88 && MCbbf.M()<94 ){ NMCTopfmass_sum->Fill(MCbbf.M()); isttbar=false; } if(MCWf1.M()>3 && MCWf2.M()>3) NMCW12fmass->Fill(MCWf1.M(),MCWf2.M() ); NMCTop12fmass->Fill(MCTopf1.M(),MCTopf2.M() ); if( MCTopf1.M()>170 && MCTopf1.M()<178 && MCTopf2.M()>170 && MCTopf2.M()<178) NMCTop12fmass_sel->Fill(MCTopf1.M(),MCTopf2.M() ); if( MCTopf1.M()>170 && MCTopf1.M()<178) NMCTop12fmass_sel1->Fill(MCTopf1.M(),MCTopf2.M() ); if( MCTopf2.M()>170 && MCTopf2.M()<178) NMCTop12fmass_sel2->Fill(MCTopf1.M(),MCTopf2.M() ); if(MCbbf.M()>4)NMCbbfmass->Fill(MCbbf.M()); float tempcostheta = -1 * (MCTopf2.CosTheta()); if(MCTopf1.M()>120) topangle_fmc->Fill(MCTopf1.CosTheta()); if(MCTopf2.M()>120) topangle_fmc->Fill(tempcostheta); if(MCTopf1.M()>5 || MCTopf1.M()>5 ) ismyTop=true; if(isttbar){ topangle_fmc2->Fill(MCTopf1.CosTheta()); topangle_fmc2->Fill(tempcostheta); } if(MCTopf1b.M()>120)topangle_fmc3->Fill(MCTopf1b.CosTheta()); if(MCTopf2b.M()>120)topangle_fmc3->Fill(-1*MCTopf2b.CosTheta()); /* cout <<" N MC Tops = " << nmctops << endl; cout <<" N MC b quarks = " << nmcbqs << endl; cout <<" N MC c quarks = " << nmccqs << endl; cout << top << endl; cout << " __________________________________________________________________________________________________ " << endl;*/ if (top > 1 ) isTop=true; if( (MCbbf.M()>88) && (MCbbf.M()<94) & (!isTop)){ iszww=true; } if(iszww ){ NMCbbfmasszww->Fill(MCbbf.M()); }else if ( !iszww && isTop ){ NMCbbfmasstt->Fill(MCbbf.M()); } }catch(DataNotAvailableException &e) { cout << "WARNGING can not find collection with name " << _mcCollection << endl; } try { LCCollection* jetscol = evt->getCollection(_myJetsCollection); for(int i = 0 ; i < nJETS ; i++){ _jetsBtag[i] = 0.; } TLorentzVector jets34(0,0,0,0); TLorentzVector jets35(0,0,0,0); TLorentzVector jets36(0,0,0,0); TLorentzVector jets45(0,0,0,0); TLorentzVector jets46(0,0,0,0); TLorentzVector jets56(0,0,0,0); // float bpmass=0; // float bmmass=0; WMass=80.4; TopMass=174.2; _t1t2mass = 0; _t1mass = 0; _t2mass = 0; _jetsBtag[0]=0; _jetsBtag[1]=0; _WW1mass=0; _WW2mass=0; _Wt1mass=0; _Wt2mass=0; _Wtx1mass=0; _Wtx2mass=0; TLorentzVector W1(0,0,0,0); TLorentzVector W2(0,0,0,0); TLorentzVector WW1(0,0,0,0); TLorentzVector WW2(0,0,0,0); TLorentzVector b1used(0,0,0,0); TLorentzVector b2used(0,0,0,0); TVector3 b1usedmom(0,0,0); TVector3 b2usedmom(0,0,0); TLorentzVector testtop1(0,0,0,0); TLorentzVector testtop2(0,0,0,0); TLorentzVector testtop3(0,0,0,0); TLorentzVector testtop4(0,0,0,0); TLorentzVector Wtop1(0,0,0,0); TLorentzVector Wtop2(0,0,0,0); TLorentzVector Wtop3(0,0,0,0); TLorentzVector Wtop4(0,0,0,0); TLorentzVector top1(0,0,0,0); TLorentzVector top2(0,0,0,0); TLorentzVector t1t2(0,0,0,0); TLorentzVector topx1(0,0,0,0); TLorentzVector topx2(0,0,0,0); TLorentzVector t1tx2(0,0,0,0); TLorentzVector topxx1(0,0,0,0); TLorentzVector topxx2(0,0,0,0); TLorentzVector bb(0,0,0,0); bbmass=0; qptsumoptf1v=-10; qptsumoptf2v=-10; nbjets=0; b1jettag=0; b2jettag=0; b1jetvq=-10; b2jetvq=-10; qptsumb1=-10; qptsumb2=-10; vtxpartmom=0; vtxpartmomsum=0; // float testmass; float ptf=-10; for(int u=0; u<6;++u){ damtag[u]=0; testpartu2q[u]=-5; } PIDHandler pidh( jetscol ); int algo = pidh.getAlgorithmID( "lcfiplus" ); int ibtag = pidh.getParameterIndex(algo, "BTag"); int ictag = pidh.getParameterIndex(algo, "CTag"); int ibctag = pidh.getParameterIndex(algo,"BCTag"); // cout << " :::::: List of Pointers in Refined Jets :::::: " << endl; bkTag[0]=0; bkTag[1]=0; for(int i=0; i < jetscol->getNumberOfElements(); i++) { ReconstructedParticle *part = dynamic_cast<ReconstructedParticle*>( jetscol->getElementAt( i ) ); // cout << part << " " ; cout << endl; TLorentzVector Jet4vec(TVector3(part->getMomentum()),part->getEnergy()); jets[i] = Jet4vec; const ParticleID &pid = pidh.getParticleID(part, algo); jetCharge[i]=part->getCharge(); jetMass[i]=Jet4vec.M(); // testmass = jetMass[i] ; bTag[i] = pid.getParameters()[ibtag]; float qsum2=0; float vtxmom; if(bTag[i]>0.5) { if(nbjets==0){ b1jettag=bTag[i] ; }else if(nbjets==1){ b2jettag=bTag[i] ; } nbjets++; // cout << " Tags today ---> " << b1jettag << " :" << b2jettag << endl; // cout << "BJets with btag " << bTag[i] << " & Charge = " << jetCharge[i] << " & Pointer " << part << endl; LCCollection* jetsrelcol = evt->getCollection(_myrelJetsCollection); // float Chi2[10]; int nvtx=0; for(int k=0; k < jetsrelcol->getNumberOfElements(); k++) { LCRelation * rel = dynamic_cast<LCRelation*>( jetsrelcol->getElementAt( k ) ); ReconstructedParticle *testpartu = dynamic_cast<ReconstructedParticle*> (rel->getFrom()); Vertex *testvertex = dynamic_cast <Vertex*> (rel->getTo()); ReconstructedParticle *testpartu2 = dynamic_cast<ReconstructedParticle*> (testvertex->getAssociatedParticle()); TVector3 tempvtxmom(testpartu2->getMomentum()[0],testpartu2->getMomentum()[1],testpartu2->getMomentum()[2]); vtxmom=tempvtxmom.Mag(); // Chi2[k]=testvertex->getChi2(); if(testpartu==part){ nvtx++; if(nvtx>1){ // cout << " 2nd Vertex " << endl; // cout << nvtx << " : First Vertex had : " << qptsum << " / " << ptf << " = " << qptsum/ptf << endl; QPtSumVtx1->Fill(qptsum/ptf); if(fabs(qptsum/ptf)==1) PtSumVtx1->Fill(ptf); } h_vtxmom->Fill(vtxmom); // cout <<"Matching Pointers :" << testpartu << " = " << part << endl; // cout << " Vertex particle from LC Relation Charge = " << testpartu2->getCharge() << endl; testpartu2q[k]=testpartu2->getCharge(); if(nbjets==1 && nvtx==1){ // cout << " First bjet " << bTag[i]<< " : " << b1jettag << " Charge = " << testpartu2->getCharge() <<endl; b1jetvq=testpartu2->getCharge(); } if(nbjets==2 && nvtx==1 ){ // cout << " 2nd bjet " << bTag[i] << " : " << b2jettag << " Charge = " << testpartu2->getCharge() << endl; b2jetvq=testpartu2->getCharge(); qptsumb2=qptsum/ptf; } h_Chargesum2->Fill(testpartu2->getCharge()); ReconstructedParticleVec testpartu2vec=testpartu2->getParticles(); TVector3 tempvtxpartmomsum(0,0,0); qptsum=0; ptf=0; // cout << " Q Pt Init " << qptsum << endl; for (u_int n=0; n< testpartu2vec.size();n++){ ReconstructedParticle *testpartu3 = testpartu2vec[n]; TLorentzVector tempvtxpart (TVector3(testpartu3->getMomentum()),testpartu3->getEnergy()); TVector3 tempvtxpartmom(testpartu3->getMomentum()[0],testpartu3->getMomentum()[1],testpartu3->getMomentum()[2]); vtxpartmom= tempvtxpartmom.Mag(); float tempcharge=testpartu3->getCharge(); float tempqptpro = tempcharge*vtxpartmom; if(fabs(tempcharge) <4) qptsum = qptsum + tempqptpro; h_vtxpartmom->Fill(vtxpartmom); tempvtxpartmomsum+=tempvtxpartmom; } ptf = tempvtxpartmomsum.Mag(); h_vtxpartmomsum->Fill(tempvtxpartmomsum.Mag()); cout << " Q * Pt Test " << qptsum << " / " << ptf << " = " << qptsum/ptf << endl; qsum2 = qsum2 + (testpartu2->getCharge()) ; // qsum2+=testpartu2->getCharge(); TLorentzVector vtxpVec1(TVector3(testpartu2->getMomentum()),testpartu2->getEnergy()); vtxpVec=vtxpVec1; float A0 = cos(vtxpVec.Angle(B0MesonVec.Vect())); float Am = cos(vtxpVec.Angle(BmMesonVec.Vect())); float Ap = cos(vtxpVec.Angle(BpMesonVec.Vect())); // v1.Angle(v2.Vect()) cout << " A0 : " << A0 << ", Am : " << Am << ", Ap : " << Ap << endl; float Aqp = cos(vtxpVec.Angle(mcbVec.Vect())); float Aqm = cos(vtxpVec.Angle(mcabVec.Vect())); cout << " Aqp = " << Aqp << ", Aqm = " << Aqm << endl; if(Aqp > Aqm && Aqp> 0.7){ if(testpartu2q[k]!=-5 && nvtx==1 ) h_bplusartonQ->Fill(testpartu2q[k]); // cout << " b+ parton angle with jets " << Aqp << endl; // bpmass=testmass; // cout << " Jets used " << testmass<<"= ? "<<jetMass[i]<< endl; QPtSumb->Fill(qptsum/(tempvtxpartmomsum.Mag())); } if(Aqm > Aqp && Aqm> 0.7 && nvtx==1 ) { if(testpartu2q[k]!=-5) h_bminuspartonQ->Fill(testpartu2q[k]); // cout << " b- parton angle with jets " << Aqm << endl; // bmmass= testmass; // cout << " Jets used " << testmass << "= ? "<< jetMass[i]<< endl; QPtSumbbar->Fill(qptsum/(tempvtxpartmomsum.Mag())); } if(testpartu2q[k]!=-5) h_Bangle->Fill(testpartu2q[k],A0); if(testpartu2q[k]!=-5) h_Bpangle->Fill(testpartu2q[k],Ap); if(testpartu2q[k]!=-5) h_Bmangle->Fill(testpartu2q[k],Am); if(A0> Ap && A0>Am && A0>0.7){ if(testpartu2q[k]!=-5 && nvtx==1 ) h_BmesonQ->Fill(testpartu2q[k]); // cout << " A0 Taken " << endl; if(B0Meson && testpartu2q[k]!=-5) h_BmesonQnoB->Fill(testpartu2q[k]); } if(Ap> A0 && Ap>Am && Ap>0.7){ if(testpartu2q[k]!=-5 && nvtx==1 ) h_BpmesonQ->Fill(testpartu2q[k]); // cout << " Ap taken " << endl; if(BpMeson && testpartu2q[k]!=-5) h_BpmesonQnoB->Fill(testpartu2q[k]); } if(Am> A0 && Am>Ap && Am>0.7){ if(testpartu2q[k]!=-5 && nvtx==1 ) h_BmmesonQ->Fill(testpartu2q[k]); // cout << "Am taken " << endl; if(BmMeson && testpartu2q[k]!=-5) h_BmmesonQnoB->Fill(testpartu2q[k]); } if(nvtx>1){ // cout << " 2nd Vertex " << endl; // cout << nvtx << " : Second Vertex has : " << qptsum << " / " << ptf << " = " << qptsum/ptf << endl; QPtSumVtx2->Fill(qptsum/ptf); if(fabs(qptsum/ptf)==1) PtSumVtx2->Fill(ptf); // qptsumoptf2v=qptsum/ptf; } if(nbjets==1 && nvtx==1){ qptsumb1=qptsum/ptf; }else if(nbjets==2 && nvtx==1){ qptsumb2=qptsum/ptf; } } } cout << " Vertices = " << nvtx << ", qptsum/ ptf = " << qptsum/ptf<< endl; if(nvtx==0){ cout << nvtx << " Vertices " << endl; cout << " Q*Pt Sum for 0 Vertex case : " << qptsum/ptf << endl; } NVtx->Fill(nvtx); h_Chargesum3->Fill(qsum2); //btagvsen1->Fill(b1.E(), _jetsBtag[0]); if(nvtx>0) QPtSum->Fill(qptsum/ptf); if(nvtx==0)QPtSum0V->Fill(qptsum/ptf); if(nvtx==1){ QPtSum1V->Fill(qptsum/ptf); qptsumoptf1v=qptsum/ptf; } if(nvtx==2){ QPtSum2V->Fill(qptsum/ptf); qptsumoptf2v=qptsum/ptf; } } cTag[i] = pid.getParameters()[ictag]; cTagBBack[i] = pid.getParameters()[ibctag]; if(bTag[i]>0.5){ TrackVec track = part->getTracks(); } } /* cout << " UnSorted Charge & Q*Pt" << endl; cout << " 0 : " << " " << b1jettag << " " << b1jetvq << " : " << qptsumb1<< endl; cout << " 1 : " << " " << b2jettag << " " << b2jetvq << " : " << qptsumb2<< endl;*/ if(b1jettag!=b2jettag){ if(b1jettag>b2jettag){ b1jetvq=b1jetvq; b2jetvq=b2jetvq; }else if(b2jettag>b1jettag){ float temp1q =b1jetvq; float temp2q =b2jetvq; float temp0 = b1jettag; float temp1 = b2jettag; float temp1qp =qptsumb1; float temp2qp =qptsumb2; b1jettag= temp1; b2jettag= temp0; b1jetvq=temp2q; b2jetvq=temp1q; qptsumb1=temp2qp; qptsumb2=temp1qp; } /* cout << " Sorted Charge & Q*Pt " << endl; cout << " 0 : " << b1jettag << " : " << b1jetvq << " : " << qptsumb1<< endl; cout << " 1 : " << b2jettag << " : " << b2jetvq << " : " << qptsumb2<< endl;*/ } int sortPositions[nJETS]; float tempBtag[nJETS]; for(int i = 0 ; i < nJETS ; i++) { tempBtag[i] = bTag[i]; sortPositions[i] = i; } for(int i = 0 ; i < nJETS ; i++) { int highestBtagPosition = i; for(int j = i ; j < nJETS ; j++) { if(tempBtag[j] > tempBtag[highestBtagPosition]) highestBtagPosition = j; } float temp = tempBtag[i]; tempBtag[i] = tempBtag[highestBtagPosition]; tempBtag[highestBtagPosition] = temp; int tempInt = sortPositions[i]; sortPositions[i] = sortPositions[highestBtagPosition]; sortPositions[highestBtagPosition] = tempInt; } // write sorted jets in the tree for(int i = 0 ; i < nJETS ; i++) { *_jets[i] = jets[sortPositions[i]]; _jetsBtag[i] = bTag[sortPositions[i]]; _jetsCtag[i] = cTag[sortPositions[i]]; _jetsBCtag[i] = cTagBBack[sortPositions[i]]; _jetsCharge[i]= jetCharge[sortPositions[i]]; _jetsMass[i]= jetMass[sortPositions[i]]; } h_btagz->Fill(_jetsBtag[0]); h_btagz1->Fill(_jetsBtag[1]); // if(b2jettag>0) // cout << " Tag 0 : " << " " << _jetsBtag[0] << ", False Jet Charge " << _jetsCharge[0] << endl; // cout << " Tag 1 : " << " " << _jetsBtag[1] << ", False Jet Charge " << _jetsCharge[1] << endl; TLorentzVector xtemp1 = *_jets[0]; cout << endl; // cout << " Jets b1 b2 pointers " << & xtemp1 << " : " << & *_jets[1] << endl; h_btag->Fill(_jetsBtag[0]); h_btag1->Fill(_jetsBtag[1]); h_btag2->Fill(_jetsBtag[2]); TLorentzVector b0test = *_jets[0]; TVector3 b1 = TVector3(b0test.X(),b0test.Y(),b0test.Z()); TLorentzVector b1test = *_jets[1]; TVector3 b2 = TVector3(b1test.X(),b1test.Y(),b1test.Z()); TLorentzVector b2test = *_jets[2]; TVector3 b3 = TVector3(b2test.X(),b2test.Y(),b2test.Z()); // cout << "Tag value 0 : " << _jetsBtag[0] << " Cos theta 0 = " << b1.CosTheta() << endl; // cout << "Tag value 1 : " << _jetsBtag[1] << " Cos theta 1 = " << b2.CosTheta() << endl; btagvstheta1->Fill(b1.CosTheta(), _jetsBtag[0]); btagvstheta2->Fill(b2.CosTheta(), _jetsBtag[1]); btagvstheta3->Fill(b3.CosTheta(), _jetsBtag[2]); btagvsen1->Fill(b0test.E(), _jetsBtag[0]); btagvsen2->Fill(b1test.E(), _jetsBtag[1]); float sumcharge=-15; // if( _jetsBtag[0]>0.3 && _jetsBtag[1]>0.3 && fabs(_jetsCharge[0])<5 && fabs(_jetsCharge[1])<5 ) sumcharge=_jetsCharge[0]-_jetsCharge[1]; if(fabs(sumcharge)<15 ) h_Chargesum->Fill(sumcharge); // cout << " Charge Summ = " << sumcharge << endl; jets34=*_jets[2]+*_jets[3]; jets35=*_jets[2]+*_jets[4]; jets36=*_jets[2]+*_jets[5]; jets45=*_jets[3]+*_jets[4]; jets46=*_jets[3]+*_jets[5]; jets56=*_jets[4]+*_jets[5]; _jetsMass34=jets34.M(); _jetsMass35=jets35.M(); _jetsMass36=jets36.M(); _jetsMass45=jets45.M(); _jetsMass46=jets46.M(); _jetsMass56=jets56.M(); h_mass34->Fill(_jetsMass34); h_mass35->Fill(_jetsMass35); h_mass36->Fill(_jetsMass36); /* float diff34 = fabs(_jetsMass34 - WMass); float diff35 = fabs(_jetsMass35 - WMass); float diff36 = fabs(_jetsMass36 - WMass); float diff45 = fabs(_jetsMass45 - WMass); float diff46 = fabs(_jetsMass46 - WMass); float diff56 = fabs(_jetsMass56 - WMass); if( diff34 < diff35 && diff34 < diff36 && diff34 < diff45 && diff34 < diff46 && diff34 < diff56 ){ W1=jets34; W2=jets56; } if( diff35 < diff34 && diff35 < diff36 && diff35 < diff45 && diff35 < diff46 && diff35 < diff56 ){ W1=jets35; W2=jets46; } if( diff36 < diff34 && diff36 < diff35 && diff36 < diff45 && diff36 < diff46 && diff36 < diff56 ){ W1=jets36; W2=jets45; } if( diff45 < diff34 && diff45 < diff34 && diff45 < diff36 && diff45 < diff46 && diff45 < diff56 ){ W1=jets45; W2=jets36; } if( diff46 < diff34 && diff46 < diff35 && diff46 < diff36 && diff46 < diff45 && diff46 < diff56 ){ W1=jets46; W2=jets35; } if( diff56 < diff34 && diff56 < diff35 && diff56 < diff36 && diff56 < diff45 && diff56 < diff46 ){ W1=jets56; W2=jets34; } */ difff3456 = fabs(_jetsMass34-WMass) + fabs(_jetsMass56-WMass); difff3546 = fabs(_jetsMass35-WMass) + fabs(_jetsMass46-WMass); difff3645 = fabs(_jetsMass36-WMass) + fabs(_jetsMass45-WMass); h_difff3456->Fill(difff3456) ; h_difff3546->Fill(difff3546) ; h_difff3645->Fill(difff3645) ; if( difff3456 < difff3546 && difff3456 < difff3645 && difff3456 < 50 ){ W1=jets34; W2=jets56; } else if( difff3546 < difff3456 && difff3546 < difff3645 && difff3546 < 50 ){ W1=jets35; W2=jets46; } else if( difff3645 < difff3546 && difff3645 < difff3456 && difff3645 < 50 ){ W1=jets36; W2=jets45; } if(W1.M()>0) _W1mass=W1.M(); if(W2.M()>0) _W2mass=W2.M(); h_w1mass->Fill(_W1mass); h_w2mass->Fill(_W2mass); recW12fenergy->Fill(W1.E(),W2.E()); // if( _jetsBtag[0]>0.3 && _jetsBtag[1]>0.3 ){ testtop1=W1+*_jets[0]; testtop2=W2+*_jets[0]; testtop3=W1+*_jets[1]; testtop4=W2+*_jets[1]; // } b1used=*_jets[0]; b2used=*_jets[1]; b1en->Fill(b1used.E()); b2en->Fill(b2used.E()); if(W1.E()>0) w1en->Fill(W1.E()); if(W1.E()>0) w2en->Fill(W2.E()); bb=b1used+b2used; bbmass=bb.M(); h_bbmass->Fill(bbmass); if(isTop) h_bbmass_tag->Fill(bbmass); else h_bbmass_notag->Fill(bbmass); // float bplustheta = cos(b1used.Angle(mcbVec.Vect())); // float bminustheta = cos(b1used.Angle(mcabVec.Vect())); float bplustheta = cos(b1used.Angle(BpMesonVec.Vect())); float bminustheta = cos(b1used.Angle(BmMesonVec.Vect())); if( bplustheta>bminustheta && bplustheta>0.8 && fabs(_jetsCharge[0])<3) h_bplusartonQ2->Fill(_jetsCharge[0]); else if(bminustheta>bplustheta && bminustheta>0.8 && fabs(_jetsCharge[0])<3 ) h_bminuspartonQ2->Fill(_jetsCharge[0]); TVector3 b1usedmomx(b1used.X(),b1used.Y(),b1used.Z()); // b1usedmom((b1used.X(),b1used.Y(),b1used.Z())); b1usedmom=b1usedmomx; // float b2usedmass = b2used.M(); // float b1usedmass = b1used.M(); float bmcbrec1 = -999; float cmcbrec1 = -999 ; float bmcbrec2 = -999; float cmcbrec2 = -999; float varc=10; if(fabs(b1jetvq)<5 && fabs(b2jetvq)<5) varc = b1jetvq - b2jetvq ; if(varc>0) { cmcbrec1 = cos(mcacVec.Angle(b1used.Vect())); bmcbrec1 = cos(mcabVec.Angle(b1used.Vect())); bmcbrec2 = cos(mcbVec.Angle(b2used.Vect())); cmcbrec2 = cos(mccVec.Angle(b2used.Vect())); } if(varc<0) { cmcbrec1 = cos(mccVec.Angle(b1used.Vect())); bmcbrec1 = cos(mcbVec.Angle(b1used.Vect())); bmcbrec2 = cos(mcabVec.Angle(b2used.Vect())); cmcbrec2 = cos(mcacVec.Angle(b2used.Vect())); } if(cmcbrec1!=-999 ) coscmcbrec->Fill(cmcbrec1); if(cmcbrec2!=-999 ) coscmcbrec->Fill(cmcbrec2); cosb1mcb2mc->Fill(cos(mcbVec.Angle(mcabVec.Vect()))); cosb1mccmc->Fill(cos(mcbVec.Angle(mccVec.Vect()))); cosb2mccmc->Fill(cos(mcabVec.Angle(mccVec.Vect()))); if( cos(mcbVec.Angle(mcabVec.Vect())) >=0 ){ cosb1mccmccut->Fill( cos(mcbVec.Angle(mccVec.Vect()))); cosb2mccmccut->Fill( cos(mcabVec.Angle(mccVec.Vect()))); } if( cos(mcbVec.Angle(mccVec.Vect())) >= 0.7 || cos(mcabVec.Angle(mccVec.Vect())) >= 0.7 ) cosb1mcb2mccut->Fill(cos(mcbVec.Angle(mcabVec.Vect()))); cosb1mcb2mcb1mccmc->Fill( cos(mcbVec.Angle(mcabVec.Vect())) , cos(mcbVec.Angle(mccVec.Vect())) ); cosb1mcb2mcb2mccmc->Fill( cos(mcbVec.Angle(mcabVec.Vect())) , cos(mcabVec.Angle(mccVec.Vect())) ); if(cmcbrec1!=-999 && bmcbrec1!=-999 ) { coscmcbrecvsbmc1->Fill(cmcbrec1, bmcbrec1); cout << " ---------------------------------------------------------------------- " << endl; cout << " c MC and b rec " << cmcbrec1 << " b MC and b rec " << bmcbrec1 << endl; cout << " ---------------------------------------------------------------------- " << endl; if( cmcbrec1 > bmcbrec1 ) coscmcbrecvsbmc21->Fill(cmcbrec1, bmcbrec1); if( cmcbrec1 > bmcbrec1 && cmcbrec1 > 0 ) coscmcbrecvsbmc31->Fill(cmcbrec1, bmcbrec1); if( cmcbrec1 > bmcbrec1 && cmcbrec1 > 0 && bmcbrec1 <= 0 ){ coscmcbrecvsbmc41->Fill(cmcbrec1, bmcbrec1); btagsusp1->Fill( _jetsBtag[0]); } cosbreccmcbtag1-> Fill( _jetsBtag[1], cmcbrec1); cosbreccmcctag1-> Fill( _jetsCtag[1], cmcbrec1); if( _jetsBtag[0] > 0.3) { coscmcbrecvsbmcc1->Fill(cmcbrec1, bmcbrec1); if( cmcbrec1 > bmcbrec1 ) coscmcbrecvsbmc2c1->Fill(cmcbrec1, bmcbrec1); if( cmcbrec1 > bmcbrec1 && cmcbrec1 > 0 ) coscmcbrecvsbmc3c1->Fill(cmcbrec1, bmcbrec1); if( cmcbrec1 > bmcbrec1 && cmcbrec1 > 0 && bmcbrec1 <= 0 ) coscmcbrecvsbmc4c1->Fill(cmcbrec1, bmcbrec1); cosbreccmcbtagc1->Fill( _jetsBtag[0],cmcbrec1) ; cosbreccmcctagc1->Fill( _jetsCtag[0],cmcbrec1) ; } cosbreccmcbtag1->Fill( _jetsBtag[0],cmcbrec1) ; cosbreccmcctag1 ->Fill( _jetsCtag[0],cmcbrec1) ; } if(cmcbrec2!=-999 && bmcbrec2!=-999 ) { coscmcbrecvsbmc2->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 ) coscmcbrecvsbmc22->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 && cmcbrec2 > 0 ) coscmcbrecvsbmc32->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 && cmcbrec2 > 0 && bmcbrec2 <= 0 ){ coscmcbrecvsbmc42->Fill(cmcbrec2, bmcbrec2); btagsusp2->Fill( _jetsBtag[1]); } cosbreccmcbtag2-> Fill( _jetsBtag[1], cmcbrec2); cosbreccmcctag2-> Fill( _jetsCtag[1], cmcbrec2); if( _jetsBtag[1] > 0.3) { coscmcbrecvsbmcc2->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 ) coscmcbrecvsbmc2c2->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 && cmcbrec2 > 0 ) coscmcbrecvsbmc3c2->Fill(cmcbrec2, bmcbrec2); if( cmcbrec2 > bmcbrec2 && cmcbrec2 > 0 && bmcbrec2 <= 0 ) coscmcbrecvsbmc4c2->Fill(cmcbrec2, bmcbrec2); cosbreccmcbtagc2->Fill( _jetsBtag[1],cmcbrec2) ; cosbreccmcctagc2->Fill( _jetsCtag[1],cmcbrec2) ; } cosbreccmcbtag2->Fill( _jetsBtag[1],cmcbrec2) ; cosbreccmcctag2 ->Fill( _jetsCtag[1],cmcbrec2) ; } // coscmcbrec->Fill(cos(mcacVec.Angle(b2used.Vect()))); testop1Mass = testtop1.M(); testop2Mass = testtop2.M(); testop3Mass = testtop3.M(); testop4Mass = testtop4.M(); Double_t bpstar1 = testtop1.Gamma()*_jets[1]->Energy()*(1 - testtop1.Beta()*TMath::Cos(testtop1.Angle(-_jets[1]->Vect()))); Double_t bpstar2 = testtop2.Gamma()*_jets[1]->Energy()*(1 - testtop2.Beta()*TMath::Cos(testtop2.Angle(-_jets[1]->Vect()))); Double_t bpstar3 = testtop3.Gamma()*_jets[0]->Energy()*(1 - testtop3.Beta()*TMath::Cos(testtop3.Angle(-_jets[0]->Vect()))); Double_t bpstar4 = testtop4.Gamma()*_jets[0]->Energy()*(1 - testtop4.Beta()*TMath::Cos(testtop4.Angle(-_jets[0]->Vect()))); float difft1=pow((testop1Mass-TopMass)/6.3,2) + pow((testtop1.E()-250.0)/8.0,2)+pow((bpstar1-68)/10.0,2); float difft2=pow((testop2Mass-TopMass)/6.3,2) + pow((testtop2.E()-250.0)/8.0,2)+pow((bpstar2-68)/10.0,2);; float difft3=pow((testop3Mass-TopMass)/6.3,2) + pow((testtop3.E()-250.0)/8.0,2)+pow((bpstar3-68)/10.0,2);; float difft4=pow((testop4Mass-TopMass)/6.3,2) + pow((testtop4.E()-250.0)/8.0,2)+pow((bpstar4-68)/10.0,2);; cout << difft1 << ":" << difft4 << ":" << difft3 << ":" << difft4 << endl; cout << " ------------------ Tag Test ------------------------- " << endl; cout << _jetsBtag[0] << " = " << b1jettag << " : " << _jetsBtag[1] << " = " << b2jettag << endl; Double_t bp1=0,bp2=0; if(difft1<difft2){ top1=testtop1; difftx1=difft1; bp1=bpstar1; } else if(difft2<difft1){ top1=testtop2; difftx1=difft2; bp1=bpstar2; } if(difft3<difft4){ top2=testtop3; difftx2=difft3; bp2=bpstar3; }else if(difft4<difft3){ top2=testtop4; difftx2=difft4; bp2=bpstar4; } if(top1.M()>5 ) mtforchi->Fill(top1.M()) ; if(top1.E()>5 ) etforchi->Fill(top1.E()) ; if(bp1>5 ) pbforchi->Fill(bp1) ; float testqsumx = -20; if(fabs(b1jetvq)<5 && fabs(b2jetvq)<5) testqsumx= b1jetvq - b2jetvq ; if(fabs(testqsumx)<20)QSum->Fill(testqsumx); if( fabs(testqsumx)<3 ){ QSum3->Fill(testqsumx); } bool good1=false; bool good2=false; // bool rightq1=true; // bool rightq2=true; cout << " for setting good1 and good2 " << endl; cout << " top1.M() 140-210 " << top1.M() << ", Chi1 " << difftx1 << endl; cout << " top2.M() 140-210 " << top2.M() << ", Chi2 " << difftx2 << endl; if( top1.M()>140 && top1.M()<210 && difftx1 <20 ) good1=true; if( top2.M()>140 && top2.M()<210 && difftx2 <40 ) good2=true; b1mom->Fill(b1usedmom.Mag()); float testqptsum = -20; testqptsum= qptsumb1 - qptsumb2; _t1mass=top1.M(); _t2mass=top2.M(); NEvts->Fill(1); Topmasseff->Fill(_t1mass); Topmasseff->Fill(_t2mass); if(_t1mass>10 && _t2mass>10) { Topmasseff1->Fill(_t1mass); Topmasseff1->Fill(_t2mass); if(cos(mcbVec.Angle(b1used.Vect()))>=0.75){ if(MCTopf1.CosTheta()>0 && top1.CosTheta()>0) Topmasseff1t->Fill(_t1mass); if(MCTopf2.CosTheta()>0 && top2.CosTheta()>0) Topmasseff1t->Fill(_t2mass); if(MCTopf1.CosTheta()<0 && top1.CosTheta()<0) Topmasseff1t->Fill(_t1mass); if(MCTopf2.CosTheta()<0 && top2.CosTheta()<0) Topmasseff1t->Fill(_t2mass); } else if (cos(mcbVec.Angle(b1used.Vect()))>=0.9){ if(MCTopf2.CosTheta()>0 && top1.CosTheta()>0) Topmasseff1t->Fill(_t1mass); if(MCTopf1.CosTheta()>0 && top2.CosTheta()>0) Topmasseff1t->Fill(_t2mass); if(MCTopf2.CosTheta()<0 && top1.CosTheta()<0) Topmasseff1t->Fill(_t1mass); if(MCTopf1.CosTheta()<0 && top2.CosTheta()<0) Topmasseff1t->Fill(_t2mass); } // if( _jetsBtag[0]>0.3 && _jetsBtag[1]>0.3){ if( _jetsBtag[0]>0.8 && _jetsBtag[1]>0.3){ Topmasseff2->Fill(_t1mass); Topmasseff2->Fill(_t2mass); if(MCTopf1.CosTheta()>0 && top1.CosTheta()>0) Topmasseff2t->Fill(_t1mass); if(MCTopf2.CosTheta()>0 && top2.CosTheta()>0) Topmasseff2t->Fill(_t2mass); if(MCTopf1.CosTheta()<0 && top1.CosTheta()<0) Topmasseff2t->Fill(_t1mass); if(MCTopf2.CosTheta()<0 && top2.CosTheta()<0) Topmasseff2t->Fill(_t2mass); if (top1.M()> 140 && top1.M()<210 && top2.M()> 140 && top2.M()<210){ Topmasseff3->Fill(_t1mass); Topmasseff3->Fill(_t2mass); if(MCTopf1.CosTheta()>0 && top1.CosTheta()>0) Topmasseff3t->Fill(_t1mass); if(MCTopf2.CosTheta()>0 && top2.CosTheta()>0) Topmasseff3t->Fill(_t2mass); if(MCTopf1.CosTheta()<0 && top1.CosTheta()<0) Topmasseff3t->Fill(_t1mass); if(MCTopf2.CosTheta()<0 && top2.CosTheta()<0) Topmasseff3t->Fill(_t2mass); // if(difftx1 <20 && difftx2 <40 ){ if(difftx1 <30 && difftx2 <30 ){ Topmasseff4->Fill(_t1mass); Topmasseff4->Fill(_t2mass); if(MCTopf1.CosTheta()>0 && top1.CosTheta()>0) Topmasseff4t->Fill(_t1mass); if(MCTopf2.CosTheta()>0 && top2.CosTheta()>0) Topmasseff4t->Fill(_t2mass); if(MCTopf1.CosTheta()<0 && top1.CosTheta()<0) Topmasseff4t->Fill(_t1mass); if(MCTopf2.CosTheta()<0 && top2.CosTheta()<0) Topmasseff4t->Fill(_t2mass); if(testqsumx!=0){ Topmasseff5->Fill(_t1mass); Topmasseff5->Fill(_t2mass); if(cos(mcbVec.Angle(b1used.Vect()))>=0.75){ if(MCTopf1.CosTheta()>0 && top1.CosTheta()>0) Topmasseff5t->Fill(_t1mass); if(MCTopf2.CosTheta()>0 && top2.CosTheta()>0) Topmasseff5t->Fill(_t2mass); if(MCTopf1.CosTheta()<0 && top1.CosTheta()<0) Topmasseff5t->Fill(_t1mass); if(MCTopf2.CosTheta()<0 && top2.CosTheta()<0) Topmasseff5t->Fill(_t2mass); }else if (cos(mcbVec.Angle(b1used.Vect()))>=0.9){ if(MCTopf2.CosTheta()>0 && top1.CosTheta()>0) Topmasseff1t->Fill(_t1mass); if(MCTopf1.CosTheta()>0 && top2.CosTheta()>0) Topmasseff1t->Fill(_t2mass); if(MCTopf2.CosTheta()<0 && top1.CosTheta()<0) Topmasseff1t->Fill(_t1mass); if(MCTopf1.CosTheta()<0 && top2.CosTheta()<0) Topmasseff1t->Fill(_t2mass); } } } } } } // if(_t1mass>10 && _t2mass>10) if(_t1mass>10) h_top1mass->Fill(_t1mass); if(_t2mass>10) h_top2mass->Fill(_t2mass); if(_t1mass>10 && _t2mass>10 ) h_top1top2mass->Fill(_t1mass, _t2mass); _t1t2mass = _t1mass+_t2mass; if(_t1mass>0) topmasschia->Fill(_t1mass,difftx1); if(_t2mass>0) topmasschib->Fill(_t2mass,difftx2); if(_t1mass>0) topmasschiaE->Fill(top1.E(),difftx1); if(_t2mass>0) topmasschibE->Fill(top2.E(),difftx2); if(_t1mass>0) topmasschiaP->Fill(bp1,difftx1); if(_t2mass>0) topmasschibP->Fill(bp2,difftx2); if(_t1mass>10) top1momvsmass->Fill(_t1mass, b1usedmom.Mag()); cout << " Checking good1 = " << good1 << ", and good2 = " << good2 << endl; if(good1 && good2 && _jetsBtag[0]>0.3 && _jetsBtag[1]>0.3 ){ if(b1jettag>0.5 && b2jettag>0.5){ if(cos(mcbVec.Angle(b1used.Vect()))>0.999 ){ _costhetatq = top1.CosTheta(); if( fabs(b1jetvq)<10 && fabs(b2jetvq)<10 && fabs(testqsumx)<20 ){ h_costhetatop->Fill(_costhetatq); gud_bjbmcangle->Fill(cos(mcbVec.Angle(b1used.Vect()))); gudbjmom->Fill(b1usedmom.Mag()); gudbjtag->Fill(b1jettag); if(fabs(testqsumx)<4)QSum_mcbp->Fill(testqsumx); if(fabs(qptsumoptf1v)<10)QPtSum1V_S->Fill(qptsumoptf1v); if(fabs(qptsumoptf2v)<10)QPtSum2V_S->Fill(qptsumoptf2v); h_costhetatopbar->Fill(top2.CosTheta()); if(fabs(testqptsum)<4) QPtSumb_C->Fill(qptsumb1); if(fabs(b1jetvq)<10) qmcb_b->Fill(qmcb,b1jetvq); if(b1jetvq>0){ // Wrong_Q->Fill(top1.CosTheta()); // rightq1=false; } } if(fabs(b1jetvq)<10) b1jetvq_b->Fill(b1jetvq); if(fabs(b2jetvq)<10) b2jetvq_b->Fill(b2jetvq); QPtSum_mcbp->Fill(qptsum/ptf); } if(cos(mcbVec.Angle(b2used.Vect()))>0.999 && b2jetvq>0 && fabs(b2jetvq)<10 && fabs(testqsumx)<20){ // Wrong_Q->Fill(-1*top2.CosTheta()); // rightq2=false; } if(cos(mcabVec.Angle(b1used.Vect()))>0.999 ){ _costhetatbarq = top1.CosTheta(); if( fabs(b1jetvq)<10 && fabs(b2jetvq)<10 && fabs(testqsumx<20)){ h_costhetatopbar->Fill(_costhetatbarq); h_costhetatop->Fill(top2.CosTheta()); if(fabs(testqsumx)<4) QSum_mcabp->Fill(testqsumx); QPtSum_mcabp->Fill(qptsum/ptf); if(fabs(b1jetvq)<10) b1jetvq_ab->Fill(b1jetvq); if(fabs(b2jetvq)<10) b2jetvq_ab->Fill(b2jetvq); if(fabs(testqptsum)<4) QPtSumbbar_C->Fill(qptsumb1); if(fabs(b1jetvq)<10) qmcab_ab->Fill(qmcb,b1jetvq); if(b1jetvq<0){ // Wrong_Q->Fill(-1*top1.CosTheta()); // rightq1=false; } } } if(cos(mcabVec.Angle(b2used.Vect()))>0.999 && b2jetvq<0 && fabs(b2jetvq)<10 && fabs(testqsumx)<20){ // Wrong_Q->Fill(top2.CosTheta()); // rightq2=false; } cout << " Test Q SUM X " << testqsumx << endl; if(testqsumx>0 ) { // if(testqsumx>0) { cout << " fabs(b1jetvq) 10 : fabs(b2jetvq) 10 : fabs(testqsumx) 7 " << endl; cout << fabs(b1jetvq)<< " : " << fabs(b2jetvq) << " : " << fabs(testqsumx) << endl; if( fabs(b1jetvq)<10 && fabs(b2jetvq)<10 && fabs(testqsumx)<7 ){ topbarquarkangleq->Fill(top1.CosTheta()); topquarkangleq->Fill(top2.CosTheta()); bad_bjbmcangle->Fill(cos(mcbVec.Angle(b1used.Vect()))); badbjmom->Fill(b1usedmom.Mag()); badbjtag->Fill(b1jettag); float cosinusthetaa =-1*(top1.CosTheta()); topangleq->Fill(top2.CosTheta()); topangleq->Fill(cosinusthetaa); Topanglecomp1->Fill(top2.CosTheta()); Topanglecomp1->Fill(cosinusthetaa); if( b1jettag>0.5 && b2jettag>0.5) { Topanglecomp2->Fill(top2.CosTheta()); Topanglecomp2->Fill(cosinusthetaa); } if( b1jettag>0.7 && b2jettag>0.7) { Topanglecomp3->Fill(top2.CosTheta()); Topanglecomp3->Fill(cosinusthetaa); } if( b1jettag>0.9 && b2jettag>0.8) { Topanglecomp4->Fill(top2.CosTheta()); Topanglecomp4->Fill(cosinusthetaa); } // float diffang = cos( b1used.CosTheta()) - cos (mcabVec.CosTheta()); cosbmcbrec->Fill(cos(mcabVec.Angle(b1used.Vect()))); if( cos(mcabVec.Angle(b1used.Vect()))>=0.8){ b1momsel->Fill(b1usedmom.Mag()); // selected b jets momentum topangleq_c->Fill(top2.CosTheta()); topangleq_c->Fill(cosinusthetaa); Topanglecomp1c->Fill(top2.CosTheta()); Topanglecomp1c->Fill(cosinusthetaa); if( b1jettag>0.5 && b2jettag>0.5) { Topanglecomp2c->Fill(top2.CosTheta()); Topanglecomp2c->Fill(cosinusthetaa); } if( b1jettag>0.7 && b2jettag>0.7) { Topanglecomp3c->Fill(top2.CosTheta()); Topanglecomp3c->Fill(cosinusthetaa); } if( b1jettag>0.9 && b2jettag>0.8) { Topanglecomp4c->Fill(top2.CosTheta()); Topanglecomp4c->Fill(cosinusthetaa); } } } } if(testqsumx<0){ if( fabs(b1jetvq)<10 && fabs(b2jetvq)<10 && fabs(testqsumx)<7 ){ topquarkangleq->Fill(top1.CosTheta()); topbarquarkangleq->Fill(top2.CosTheta()); float cosinusthetab =-1* (top2.CosTheta()); // if(cos(top1.Angle(top2.Vect()))>0.9) topangleq->Fill(cosinusthetab); topangleq->Fill(top1.CosTheta()); Topanglecomp1->Fill(top1.CosTheta()); Topanglecomp1->Fill(cosinusthetab); if( b1jettag>0.5 && b2jettag>0.5) { Topanglecomp2->Fill(top1.CosTheta()); Topanglecomp2->Fill(cosinusthetab); } if( b1jettag>0.7 && b2jettag>0.7) { Topanglecomp3->Fill(top1.CosTheta()); Topanglecomp3->Fill(cosinusthetab); } if( b1jettag>0.9 && b2jettag>0.8) { Topanglecomp4->Fill(top1.CosTheta()); Topanglecomp4->Fill(cosinusthetab); } cosbmcbrec->Fill(cos(mcbVec.Angle(b1used.Vect()))); // coscmcbrec->Fill(cos(mcacVec.Angle(b1used.Vect()))); if( cos(mcbVec.Angle(b1used.Vect()))>=0.8){ topangleq_c->Fill(top1.CosTheta()); topangleq_c->Fill(cosinusthetab); Topanglecomp1c->Fill(top1.CosTheta()); Topanglecomp1c->Fill(cosinusthetab); b1momsel->Fill(b1usedmom.Mag()); if( b1jettag>0.5 && b2jettag>0.5) { Topanglecomp2c->Fill(top1.CosTheta()); Topanglecomp2c->Fill(cosinusthetab); } if( b1jettag>0.7 && b2jettag>0.7) { Topanglecomp3c->Fill(top1.CosTheta()); Topanglecomp3c->Fill(cosinusthetab); } if( b1jettag>0.9 && b2jettag>0.8) { Topanglecomp4c->Fill(top1.CosTheta()); Topanglecomp4c->Fill(cosinusthetab); } } } } // float qbsum = b1jetvq + qmcb ; // float qabsum = b1jetvq + qmcab ; // cout << "Charge vs MC Charge " << b1jetvq << " : " << qmcb << " S1 : " << qbsum << " S2 : " << qabsum << endl; if( b1jettag>0.5 && b2jettag>0.5 && b1jettag==_jetsBtag[0] && b2jettag==_jetsBtag[1] ){ if(testqsumx<0 ){ float cosinusthetax =-1*(top2.CosTheta()); topangle_bc->Fill(top1.CosTheta()); topangle_bc->Fill(cosinusthetax); if(testqsumx==-1 ){ topangle_c1bc->Fill(top1.CosTheta()); topangle_c1bc->Fill(cosinusthetax); b1jetvq_c1bc->Fill(b1jetvq); b2jetvq_c1bc->Fill(b2jetvq); } if(testqsumx<-1){ topangle_c2bc->Fill(top1.CosTheta()); topangle_c2bc->Fill(cosinusthetax); b1jetvq_c2bc->Fill(b1jetvq); b2jetvq_c2bc->Fill(b2jetvq); } } if(testqsumx>0 ){ float cosinus = (-1)*(top1.CosTheta()); topangle_bc->Fill(top2.CosTheta()); topangle_bc->Fill(cosinus); if(testqsumx==1 ){ topangle_c1bc->Fill(top2.CosTheta()); topangle_c1bc->Fill(cosinus); b1jetvq_c1bc->Fill(b1jetvq); b2jetvq_c1bc->Fill(b2jetvq); } if(testqsumx>1){ topangle_c2bc->Fill(top2.CosTheta()); topangle_c2bc->Fill(cosinus); b1jetvq_c2bc->Fill(b1jetvq); b2jetvq_c2bc->Fill(b2jetvq); } } float cosangleval=0.9; if(testqsumx<0 ){ topquarkangle->Fill(top1.CosTheta()); topbarquarkangle->Fill(top2.CosTheta()); float cosinustheta =-1*(top2.CosTheta()); float difftmctrec1 ; float difftmctrec2 ; difftmctrec1 = top1.CosTheta() - mctopVec.CosTheta(); difftmctrec2 = top2.CosTheta() - mcatopVec.CosTheta(); costmctrecdiffbc->Fill(difftmctrec1); costmctrecdiffbc->Fill(difftmctrec2); if(cos(mcbVec.Angle(b1used.Vect()))>= cosangleval){ costmctrecdiff->Fill(difftmctrec1); costmctrecdiff->Fill(difftmctrec2); topangle->Fill(top1.CosTheta()); topangle->Fill(cosinustheta); h_top1top2mass_sel->Fill(_t1mass, _t2mass); h_bbmass_sel->Fill(bbmass); float diff = mccostheta - (top1.CosTheta()); float diff2 = mccosinustheta - cosinustheta; topangle_diff->Fill(diff); topangle_diff->Fill(diff2); if(testqsumx==-1){ topangle_c1->Fill(top1.CosTheta()); topangle_c1->Fill(cosinustheta); b1jetvq_c1->Fill(b1jetvq); b2jetvq_c1->Fill(b2jetvq); } if(testqsumx<-1){ topangle_c2->Fill(top1.CosTheta()); topangle_c2->Fill(cosinustheta); b1jetvq_c2->Fill(b1jetvq); b2jetvq_c2->Fill(b2jetvq); } } if(cos(mcbVec.Angle(b1used.Vect()))<cosangleval){ Wrong_Q->Fill(top1.CosTheta()); Wrong_Q->Fill(cosinustheta); } } if(testqsumx>0){ topbarquarkangle->Fill(top1.CosTheta()); topquarkangle->Fill(top2.CosTheta()); float cosinustheta1 =-1*(top1.CosTheta()); float difftmctrecx1 ; float difftmctrecx2 ; difftmctrecx1 = top2.CosTheta() - mctopVec.CosTheta(); difftmctrecx2 = top1.CosTheta() - mcatopVec.CosTheta(); costmctrecdiffbc->Fill(difftmctrecx1); costmctrecdiffbc->Fill(difftmctrecx2); if(cos(mcabVec.Angle(b1used.Vect()))>=cosangleval){ costmctrecdiff->Fill(difftmctrecx1); costmctrecdiff->Fill(difftmctrecx2); topangle->Fill(top2.CosTheta()); topangle->Fill(cosinustheta1); h_top1top2mass_sel->Fill(_t1mass, _t2mass); h_bbmass_sel->Fill(bbmass); float difff = mccostheta - (top2.CosTheta()); float difff2 = mccosinustheta - cosinustheta1; topangle_diff->Fill(difff); topangle_diff->Fill(difff2); if(testqsumx==1){ topangle_c1->Fill(top2.CosTheta()); topangle_c1->Fill(cosinustheta1); b1jetvq_c1->Fill(b1jetvq); b2jetvq_c1->Fill(b2jetvq); } if(testqsumx>1){ topangle_c2->Fill(top2.CosTheta()); topangle_c2->Fill(cosinustheta1); b1jetvq_c2->Fill(b1jetvq); b2jetvq_c2->Fill(b2jetvq); } } if(cos(mcabVec.Angle(b1used.Vect()))<cosangleval){ Wrong_Q->Fill(top2.CosTheta()); Wrong_Q->Fill(cosinustheta1); } } } // if( b1jettag>0 && b2jettag>0){ before testqsumx<0 cost1t2->Fill(cos(top1.Angle(top2.Vect()))); } if(testqsumx==0 && b1jettag>0.3 && fabs(testqptsum)<20 && fabs(b1jetvq)<10 && fabs(b2jetvq)<10 ) { if( b1jetvq<0 ){ topquarkangleqpt->Fill(top1.CosTheta()); if(b2jetvq>0)topquarkangleqpt->Fill(-1*top2.CosTheta()); } if( b1jetvq>0 ){ if(b2jetvq<0) topquarkangleqpt->Fill(top2.CosTheta()); topquarkangleqpt->Fill(-1*top1.CosTheta()); } } _tree->Fill(); } } catch(DataNotAvailableException &e) { cout << "WARNGING can not find collection with name " << _myJetsCollection << endl; } } void ttbar::check(LCEvent * evt){ } void ttbar::end() { ROOTfile->Write(); ROOTfile->Close(); delete ROOTfile; std::cout << "ttbarProcessor::end() " << endl; cout << "MC tops " << ntops << endl; cout <<" MC b quarks = " << nbqs << endl; cout <<" MC c quarks = " << ncqs << endl; cout <<" MC Ws = " << nws << endl; cout <<" MC (hadronic)Ws = " << nwhs << endl; cout <<" MC (leptonic)Ws = " << nwls << endl; cout <<" MC quarks = " << nqs << endl; }
[ "sohailamjad@Sohails-MacBook-Pro.local" ]
sohailamjad@Sohails-MacBook-Pro.local
64f6fddf18b293ad61fb279209117624fc87f6b3
198806ccd0b5a7d476c701be5943e9a7afacb7d0
/xdaq/include/rubuilder/ru/InputHandler.h
d03b04dfa0fcd33738372d7c4b9f1e0331406cda
[]
no_license
marcomuzio/EMULib_CLCT_Timing
df5999b5f1187725d7f5b6196ba566045ba60f55
04e930d46cadaa0c73b94a0c22e4478f55fac844
refs/heads/master
2021-01-16T13:47:26.141865
2014-08-14T12:04:33
2014-08-14T12:04:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,736
h
#ifndef _rubuilder_ru_InputHandler_h_ #define _rubuilder_ru_InputHandler_h_ #include <boost/thread/mutex.hpp> #include <stdint.h> #include <vector> #include "i2o/shared/i2omsg.h" #include "rubuilder/ru/SuperFragmentGenerator.h" #include "rubuilder/utils/OneToOneQueue.h" #include "toolbox/mem/Pool.h" #include "toolbox/mem/Reference.h" #include "xdaq/Application.h" #include "xdata/UnsignedInteger32.h" #include "xdata/Vector.h" #include "xgi/Output.h" namespace rubuilder { namespace ru { // namespace rubuilder::ru class InputHandler { public: InputHandler(xdaq::Application* app) : app_(app) {}; virtual ~InputHandler() {}; /** * Callback for I2O message received from frontend */ virtual void I2Ocallback(toolbox::mem::Reference*) = 0; /** * Fill the next complete super fragment into the Reference. * If no super fragment is ready, it returns false. */ virtual bool getData(const uint32_t eventNumber, toolbox::mem::Reference*&) = 0; /** * Configure */ virtual void configure ( const uint32_t blockFIFOCapacity, const bool dropInputData, const uint32_t dummyBlockSize, const uint32_t dummyFedPayloadSize, xdata::Vector<xdata::UnsignedInteger32>& fedSourceIds ) {}; /** * Remove all data */ virtual void clear() {}; /** * Print monitoring information as HTML snipped */ virtual void printHtml(xgi::Output*) = 0; /** * Return the last event number seen */ inline uint32_t lastEventNumber() const { return inputMonitoring_.lastEventNumber; } /** * Return the number of received event fragments * since the last call to resetMonitoringCounters */ inline uint64_t fragmentsCount() const { return inputMonitoring_.logicalCount; } /** * Reset the monitoring counters */ inline void resetMonitoringCounters() { boost::mutex::scoped_lock sl(inputMonitoringMutex_); inputMonitoring_.payload = 0; inputMonitoring_.logicalCount = 0; inputMonitoring_.i2oCount = 0; inputMonitoring_.lastEventNumber = 0; } protected: xdaq::Application* app_; struct InputMonitoring { uint64_t logicalCount; uint64_t payload; uint64_t i2oCount; uint32_t lastEventNumber; } inputMonitoring_; mutable boost::mutex inputMonitoringMutex_; }; class FBOproxy : public InputHandler { public: FBOproxy(xdaq::Application*); virtual ~FBOproxy() {}; virtual void I2Ocallback(toolbox::mem::Reference*); virtual bool getData(const uint32_t eventNumber, toolbox::mem::Reference*&); virtual void configure ( const uint32_t blockFIFOCapacity, const bool dropInputData, const uint32_t dummyBlockSize, const uint32_t dummyFedPayloadSize, xdata::Vector<xdata::UnsignedInteger32>& fedSourceIds ); virtual void clear(); virtual void printHtml(xgi::Output*); private: void updateInputCounters(const I2O_MESSAGE_FRAME*); void appendBlockToSuperFragment(toolbox::mem::Reference*); void handleCompleteSuperFragment(); typedef utils::OneToOneQueue<toolbox::mem::Reference*> BlockFIFO; BlockFIFO blockFIFO_; bool dropInputData_; toolbox::mem::Reference* superFragmentHead_; toolbox::mem::Reference* superFragmentTail_; }; class DummyInputData : public InputHandler { public: DummyInputData(xdaq::Application*); virtual ~DummyInputData() {}; virtual void I2Ocallback(toolbox::mem::Reference*); virtual bool getData(const uint32_t eventNumber, toolbox::mem::Reference*&); virtual void configure ( const uint32_t blockFIFOCapacity, const bool dropInputData, const uint32_t dummyBlockSize, const uint32_t dummyFedPayloadSize, xdata::Vector<xdata::UnsignedInteger32>& fedSourceIds ); virtual void printHtml(xgi::Output*); private: toolbox::mem::Reference* generateDummySuperFrag(const uint32_t eventNumber); void setNbBlocksInSuperFragment ( toolbox::mem::Reference*, const uint32_t nbBlocks ); toolbox::net::URN poolURN_; rubuilder::ru::SuperFragmentGenerator superFragGenerator_; toolbox::mem::Pool* dummySuperFragmentPool_; uint32_t dummyBlockSize_; uint32_t dummyFedPayloadSize_; std::vector<uint32_t> fedSourceIds_; uint64_t numberOfSuperFragmentsGenerated_; }; } } //namespace rubuilder::ru #endif // _rubuilder_ru_InputHandler_h_ /// emacs configuration /// Local Variables: - /// mode: c++ - /// c-basic-offset: 2 - /// indent-tabs-mode: nil - /// End: -
[ "hogenshpogen@gmail.com" ]
hogenshpogen@gmail.com
4538ec95d9ef4217ff01b4880a2e9ad90b5d74dd
e14a0d02d37f54d7f263975e4103fa50cbfcd975
/src/IMU/clogger.cpp
701e3795e86d640ef323c15fadaa23f9bb757ac8
[]
no_license
Tapuwa-Dhliwayo/Final-Year-Project
93998c861e19c989a94fbf75ad41591d9ec25703
017fe1a175b1e7288c13456f09ee5b25283cfa62
refs/heads/master
2020-08-08T04:03:05.842005
2019-10-16T10:36:00
2019-10-16T10:36:00
208,030,786
0
0
null
null
null
null
UTF-8
C++
false
false
2,405
cpp
//Logging function utilising huffman algorithm for compression //Sorted #include "clogger.h" void Logger::clogger(std::string filename, rawData_t* data, sensorValue_t* processed){ std::ofstream logfile; logfile.open(filename+".txt"); logfile << "Raw Data \n"; logfile << "x: "<< data->x <<"\n"; logfile << "y: "<< data->y <<"\n"; logfile << "z: "<< data->z <<"\n"; logfile << "Processed Data \n"; logfile << "x: "<< processed->x <<"\n"; logfile << "y: "<< processed->y <<"\n"; logfile << "z: "<< processed->z <<"\n"; logfile.close(); } void Logger::clogger(std::string filename,void* data){ std::cout<<"Overload Me"<<std::endl; } void compress(std::string filename){ std::vector<char> char_vector = char_reader(filename); std::map<char, int> freq_table = freq_generator(char_vector); HuffmanTree tree(freq_table); std::unordered_map<char , std::string > code_table = tree.code(); std::string encoded_data = encoder(char_vector,code_table); writer(filename,encoded_data,freq_table); if(std::remove((filename+".txt").c_str()) != 0){ perror("Error deleting file"); } else{ puts("File successfully deleted"); } } void decoder(std::string filename){ std::map<char , int> freq_table; std::ifstream file(filename+".hdr"); int swap = 0; char character; char keep; int frequency; while(!file.eof()){ file>>std::noskipws; file>>character; if(character != '&'){ keep = character; swap = 0; } else if(character == '&' && swap == 0){ file>>frequency; freq_table.insert(std::make_pair(keep,frequency)); swap = 1; } } file.close(); std::ifstream file2(filename); std::string encoded_data; std::getline(file2,encoded_data); file2.close(); writer("Checking",encoded_data,freq_table); HuffmanTree tree(freq_table); std::priority_queue<std::shared_ptr<HuffmanNode>, std::vector<std::shared_ptr<HuffmanNode>>,compare> minHeap = tree.getHeap(); std::shared_ptr<HuffmanNode> root = minHeap.top(); std::shared_ptr<HuffmanNode> curr = root; std::ofstream decodedfile; decodedfile.open(filename+"_decoded.txt"); std::string ans = ""; for(int i = 0; i < encoded_data.size(); i++){ if(encoded_data[i] == '0'){ curr = curr->left; } else{ curr = curr->right; } //Reach the leaf if(curr->left==NULL && curr->right==NULL){ ans += curr->data; curr = root; } } decodedfile<<ans; decodedfile.close(); }
[ "tapsdhliwayo@gmail.com" ]
tapsdhliwayo@gmail.com
62611b5f0ce3766869f2b7d0df610e32c6f7b77a
3c869ef8e5513308cc0c3b41b6e76ca364fc82bb
/SaberCore02/SaberCore02/scUiScaleAnimation.cpp
7cfa3881f2edec92f8fd663fdec97f76b25a1d6e
[]
no_license
kidsang/SaberCore2
d99b97f47f209e7ed4eeb014f094a04d66bdf589
107ecb94f22596046263872731716dcf5e4ff6c2
refs/heads/master
2021-01-01T17:37:06.411813
2012-08-12T11:20:30
2012-08-12T11:20:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,735
cpp
#include "scUiScaleAnimation.h" #include "MyGUI/MyGUI_Widget.h" #include "OgreVector4.h" #include "scGenericKeyFrame.h" scUiScaleAnimation::scUiScaleAnimation(bool isLoop) : scUiAnimation(isLoop), mOriginWidth(0), mOriginHeight(0), mOriginX(0), mOriginY(0) { } scUiScaleAnimation::~scUiScaleAnimation(void) { } void scUiScaleAnimation::runImpl( scKeyFramePtr k0, scKeyFramePtr k1 ) { scContinuousKeyFrame<Ogre::Vector4> *tk0, *tk1; tk0 = static_cast<scContinuousKeyFrame<Ogre::Vector4>*>(k0.get()); tk1 = static_cast<scContinuousKeyFrame<Ogre::Vector4>*>(k1.get()); Ogre::Vector4 value = tk0->getInterpolationFunc()(tk0->getTime(), getTime(), tk1->getTime(), tk0->getValue(), tk1->getValue()); getHost()->setPosition(mOriginX - (i32)((value.x - 1) * mOriginWidth * value.z), mOriginY - (i32)((value.y - 1) * mOriginHeight * value.w)); getHost()->setSize((i32)(mOriginWidth * value.x), (i32)(mOriginHeight * value.y)); } void scUiScaleAnimation::_registerWidget( MyGUI::Widget* widget ) { scUiAnimation::_registerWidget(widget); mOriginWidth = widget->getWidth(); mOriginHeight = widget->getHeight(); mOriginX = widget->getLeft(); mOriginY = widget->getTop(); } void scUiScaleAnimation::createKeyFrame( u32 time, f32 scaleX, f32 scaleY, f32 centerX /*= 0.5f*/, f32 centerY /*= 0.5f*/, scKeyFrame::InterpolationType itype /*= scKeyFrame::IT_LINEAR*/ ) { scContinuousKeyFrame<Ogre::Vector4>* keyFrame = new scContinuousKeyFrame<Ogre::Vector4>(time, Ogre::Vector4(scaleX, scaleY, centerX, centerY)); keyFrame->setInterpolationType(itype); addKeyFrame(scKeyFramePtr(keyFrame)); } scAnimationPtr scUiScaleAnimationFactory::createAnimation( bool isLoop ) { return scAnimationPtr(new scUiScaleAnimation(isLoop)); }
[ "963262214@qq.com" ]
963262214@qq.com
cbba7fa891c8a6f5f38c78b4cb285ab07e187a4c
313df6503307a8a45a51d7475339e4415c4fcc84
/T9TempProj/T9.cpp
49614a2f3698a338eae87479c3e828f604ac7bb3
[]
no_license
Pechenkya/T9
d9a02d35a0d73bf93bf78a78c2cb966f10a35b60
43a3ccc2d7efe58de55e0c8f878844cbf8a68ed9
refs/heads/master
2020-09-11T18:46:43.307810
2019-11-22T16:02:58
2019-11-22T16:02:58
219,860,337
0
0
null
null
null
null
UTF-8
C++
false
false
2,224
cpp
#include "T9.h" #include <iostream> #include <fstream> std::ostream& operator<<(std::ostream& os, const Word& word) { os << word.word << " " << word.popularity; return os; } std::vector<int> T9::get_key(std::string value) { unsigned int size = value.length(); std::vector <int> int_key(size); int counter{}; for (auto v : value) { v = tolower(v); if (v == 'a' || v == 'b' || v == 'c') int_key[counter++] = 2; else if (v == 'd' || v == 'e' || v == 'f') int_key[counter++] = 3; else if (v == 'g' || v == 'h' || v == 'i') int_key[counter++] = 4; else if (v == 'j' || v == 'k' || v == 'l') int_key[counter++] = 5; else if (v == 'm' || v == 'n' || v == 'o') int_key[counter++] = 6; else if (v == 'p' || v == 'q' || v == 'r' || v == 's') int_key[counter++] = 7; else if (v == 't' || v == 'u' || v == 'v') int_key[counter++] = 8; else if (v == 'w' || v == 'x' || v == 'y' || v == 'z') int_key[counter++] = 9; else int_key[counter++] = 1; } return int_key; } std::vector<int> T9::recreate_key(std::string key) { unsigned int size = key.length(); std::vector <int> recreated_key(size); for (unsigned int i = 0; i < size; i++) { recreated_key[i] = static_cast<int>(key[i]) - 48; } return recreated_key; } void T9::fill_lib(std::string filename) { std::ifstream inp(filename); std::string temp{}; int popl{}; do { inp >> temp; if (temp == "/0") break; inp >> popl; for (auto& c : temp) c = tolower(c); this->add_word(Word(temp, popl)); } while (temp != "/0"); inp.close(); } void T9::save_lib(std::string filename) { std::ofstream out(filename); out.clear(); library.save_trie(out); out << "/0"; out.close(); } void T9::add_word(Word val) { std::vector<int> key = get_key(val.word); this->library.put(key, val); } void T9::return_words(std::vector<Word> val, std::string key) { std::vector <int> _key = recreate_key(key); library.return_value(val, _key); } std::vector<Word> T9::get_words(std::string key) { std::vector<int> _key = recreate_key(key); return this->library.get_value(_key); } Word::Word() : word{}, popularity{ 0 }{} Word::Word(std::string _word, int _popularity) : word{ _word }, popularity{ _popularity } {}
[ "lol.lol.lalka.lalka@gmail.com" ]
lol.lol.lalka.lalka@gmail.com
b04ec8c001e13759a98d55bad03550c73dc9c699
9a3f8c3d4afe784a34ada757b8c6cd939cac701d
/leetCarFleet.cpp
bf697cd980fcf02046b2e73d28ffb911d2e9b444
[]
no_license
madhav-bits/Coding_Practice
62035a6828f47221b14b1d2a906feae35d3d81a8
f08d6403878ecafa83b3433dd7a917835b4f1e9e
refs/heads/master
2023-08-17T04:58:05.113256
2023-08-17T02:00:53
2023-08-17T02:00:53
106,217,648
1
1
null
null
null
null
UTF-8
C++
false
false
3,823
cpp
/* * //************************************************************853. Car Fleet.***************************************************** https://leetcode.com/problems/car-fleet/ *******************************************************************TEST CASES:************************************************************ //These are the examples I had worked on. 12 [10,8,0,5,3] [2,4,1,1,3] 10 [2] [2] 200 [4,1,59,24,19,40,190,42,36,37,38,67,43,98] [6,9,4,12,7,42,78,5,30,30,14,25,15,17] 13 [10,2,5,7,4,6,11] [7,5,10,5,9,4,1] // Time Complexity: O(nlogn). // Sorting the cars based on position and time to reach desti. // Space Complexity: O(n). //********************************************************THIS IS LEET ACCEPTED CODE.*************************************************** */ //************************************************************Solution 1:************************************************************ //*****************************************************THIS IS LEET ACCEPTED CODE.*********************************************** // Time Complexity: O(nlogn). // Sorting the cars based on position and time to reach desti. // Space Complexity: O(n). // This algorithm is Sorting based. Here, first we sort the cars based on their positions and time to reach destinations. Then, we iter. over cars // and at each step, we remove all previous fleets which reach destination faster than curr. car as all these cars will form a single fleet with curr. car. // In this way all fleets which won't meet would be in stack at any time. We return the stack size at the end of iter. as this would be the final fleets // reaching destination. class Solution { public: float getTime(pair<int,int>&curr, int target){ float dist=target-curr.second; return dist/curr.first; } int carFleet(int target, vector<int>& position, vector<int>& speed) { // priority_queue<float, vector<float>, greater<float>>pq2; // vector<pair<int,int>>v; // for(int i=0;i<position.size();i++){ // v.push_back({position[i], speed[i]}); // } // sort(v.begin(), v.end()); // for(int i=0;i<v.size();i++){ // pair<int,int>temp={v[i].second, v[i].first};// Speed, position. // // cout<<"position: "<<v[i].first<<" and speed: "<<v[i].second<<endl; // float currTime=getTime(temp, target); // while(!pq2.empty() && pq2.top()<=currTime){ // pq2.pop(); // } // pq2.push(currTime); // } // int res=pq2.size(); // // cout<<"final groups: "<<endl; // // while(!pq2.empty()){ // // // cout<<"psn: "<<pq.top().second<<" and speed: "<<pq.top().first<<endl; // // pq2.pop(); // // } // return res; vector<pair<int,float>>v; for(int i=0;i<position.size();i++){ float currTime=(float)(target-position[i])/speed[i]; // Calc. time to reach destination. v.push_back({position[i], currTime}); // Insert {position, time to Destination} entry into array. } sort(v.begin(), v.end()); stack<float>st; for(int i=0;i<v.size();i++){ // cout<<"Current psn: "<<v[i].first<<" required time: "<<v[i].second<<endl; while(!st.empty() && st.top()<=v[i].second){ // Removing all fleets behind curr. car which would join this car. // cout<<"faster: "<<st.top()<<endl; st.pop(); } st.push(v[i].second); // Inserting curr. car to represent the curr. fleet. } return (int)st.size(); // Returning the total #fleets at the destination. } };
[ "kasamsaimadhavk@gmail.com" ]
kasamsaimadhavk@gmail.com
797bb01dc381e045f741e6f310ef1a20c18e057d
f501d690498272785564db8e4bf2420eeff23a0b
/thirdparty/rocksdb/util/slice.cc
8d95a8ae19d3a0c346ee624e03cd5486402e9575
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Zlib", "MIT-0", "LicenseRef-scancode-openssl", "ISC", "LicenseRef-scancode-ssleay-windows", "OpenSSL", "JSON", "BSL-1.0", "curl", "LicenseRef-scancode-public-domain", "MIT", "BSD-2-Clause", "BSD-1-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "LicenseRef-scancode-bsd-unchanged", "GPL-2.0-only" ]
permissive
phrocker/nifi-minifi-cpp
04bad621c1f82c0ab3ef3fffb5085d64939ef290
97a05c1bdb6bfd40f5f33da01cf0893060350ef4
refs/heads/master
2020-12-30T23:23:01.041185
2019-08-27T07:50:15
2019-08-28T17:25:00
80,614,745
3
1
Apache-2.0
2019-06-14T11:46:17
2017-02-01T11:41:22
C++
UTF-8
C++
false
false
5,673
cc
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // Copyright (c) 2012 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include <algorithm> #include "rocksdb/slice_transform.h" #include "rocksdb/slice.h" #include "util/string_util.h" #include <stdio.h> namespace rocksdb { namespace { class FixedPrefixTransform : public SliceTransform { private: size_t prefix_len_; std::string name_; public: explicit FixedPrefixTransform(size_t prefix_len) : prefix_len_(prefix_len), // Note that if any part of the name format changes, it will require // changes on options_helper in order to make RocksDBOptionsParser work // for the new change. // TODO(yhchiang): move serialization / deserializaion code inside // the class implementation itself. name_("rocksdb.FixedPrefix." + ToString(prefix_len_)) {} virtual const char* Name() const override { return name_.c_str(); } virtual Slice Transform(const Slice& src) const override { assert(InDomain(src)); return Slice(src.data(), prefix_len_); } virtual bool InDomain(const Slice& src) const override { return (src.size() >= prefix_len_); } virtual bool InRange(const Slice& dst) const override { return (dst.size() == prefix_len_); } virtual bool SameResultWhenAppended(const Slice& prefix) const override { return InDomain(prefix); } }; class CappedPrefixTransform : public SliceTransform { private: size_t cap_len_; std::string name_; public: explicit CappedPrefixTransform(size_t cap_len) : cap_len_(cap_len), // Note that if any part of the name format changes, it will require // changes on options_helper in order to make RocksDBOptionsParser work // for the new change. // TODO(yhchiang): move serialization / deserializaion code inside // the class implementation itself. name_("rocksdb.CappedPrefix." + ToString(cap_len_)) {} virtual const char* Name() const override { return name_.c_str(); } virtual Slice Transform(const Slice& src) const override { assert(InDomain(src)); return Slice(src.data(), std::min(cap_len_, src.size())); } virtual bool InDomain(const Slice& src) const override { return true; } virtual bool InRange(const Slice& dst) const override { return (dst.size() <= cap_len_); } virtual bool SameResultWhenAppended(const Slice& prefix) const override { return prefix.size() >= cap_len_; } }; class NoopTransform : public SliceTransform { public: explicit NoopTransform() { } virtual const char* Name() const override { return "rocksdb.Noop"; } virtual Slice Transform(const Slice& src) const override { return src; } virtual bool InDomain(const Slice& src) const override { return true; } virtual bool InRange(const Slice& dst) const override { return true; } virtual bool SameResultWhenAppended(const Slice& prefix) const override { return false; } }; } // 2 small internal utility functions, for efficient hex conversions // and no need for snprintf, toupper etc... // Originally from wdt/util/EncryptionUtils.cpp - for ToString(true)/DecodeHex: char toHex(unsigned char v) { if (v <= 9) { return '0' + v; } return 'A' + v - 10; } // most of the code is for validation/error check int fromHex(char c) { // toupper: if (c >= 'a' && c <= 'f') { c -= ('a' - 'A'); // aka 0x20 } // validation if (c < '0' || (c > '9' && (c < 'A' || c > 'F'))) { return -1; // invalid not 0-9A-F hex char } if (c <= '9') { return c - '0'; } return c - 'A' + 10; } Slice::Slice(const SliceParts& parts, std::string* buf) { size_t length = 0; for (int i = 0; i < parts.num_parts; ++i) { length += parts.parts[i].size(); } buf->reserve(length); for (int i = 0; i < parts.num_parts; ++i) { buf->append(parts.parts[i].data(), parts.parts[i].size()); } data_ = buf->data(); size_ = buf->size(); } // Return a string that contains the copy of the referenced data. std::string Slice::ToString(bool hex) const { std::string result; // RVO/NRVO/move if (hex) { result.reserve(2 * size_); for (size_t i = 0; i < size_; ++i) { unsigned char c = data_[i]; result.push_back(toHex(c >> 4)); result.push_back(toHex(c & 0xf)); } return result; } else { result.assign(data_, size_); return result; } } // Originally from rocksdb/utilities/ldb_cmd.h bool Slice::DecodeHex(std::string* result) const { std::string::size_type len = size_; if (len % 2) { // Hex string must be even number of hex digits to get complete bytes back return false; } if (!result) { return false; } result->clear(); result->reserve(len / 2); for (size_t i = 0; i < len;) { int h1 = fromHex(data_[i++]); if (h1 < 0) { return false; } int h2 = fromHex(data_[i++]); if (h2 < 0) { return false; } result->push_back((h1 << 4) | h2); } return true; } const SliceTransform* NewFixedPrefixTransform(size_t prefix_len) { return new FixedPrefixTransform(prefix_len); } const SliceTransform* NewCappedPrefixTransform(size_t cap_len) { return new CappedPrefixTransform(cap_len); } const SliceTransform* NewNoopTransform() { return new NoopTransform; } } // namespace rocksdb
[ "jeremydyer@apache.org" ]
jeremydyer@apache.org
493ea3d9362b1d23ac5c416965e0811f30e52104
3a50c0712e0a31b88d0a5e80a0c01dbefc6a6e75
/thrift/conformance/cpp2/ThriftTypeInfo.h
ea7b006b6818d5b287bae1b22164e545a8f80f1c
[ "Apache-2.0" ]
permissive
facebook/fbthrift
3b7b94a533666c965ce69cfd6054041218b1ea6f
53cf6f138a7648efe5aef9a263aabed3d282df91
refs/heads/main
2023-08-24T12:51:32.367985
2023-08-24T08:28:35
2023-08-24T08:28:35
11,131,631
2,347
666
Apache-2.0
2023-09-01T01:44:39
2013-07-02T18:15:51
C++
UTF-8
C++
false
false
2,791
h
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <initializer_list> #include <string_view> #include <folly/container/Access.h> #include <thrift/conformance/if/gen-cpp2/type_types.h> #include <thrift/lib/cpp2/Thrift.h> #include <thrift/lib/cpp2/type/UniversalName.h> #include <thrift/lib/thrift/gen-cpp2/type_types.h> namespace apache::thrift::conformance { inline constexpr type::hash_size_t kTypeHashBytesNotSpecified = -1; // The minimum and default number of bytes that can be used to identify // a type. // // The expected number of types that can be hashed before a // collision is 2^(8*{numBytes}/2). // Which is ~4.3 billion types for the min, and ~18.45 quintillion // types for the default. inline constexpr type::hash_size_t kMinTypeHashBytes = 8; inline constexpr type::hash_size_t kDefaultTypeHashBytes = 16; // Creates an ThriftTypeInfo struct with the given names and configuration. // // The first name in names is set as the primary name, and all others are added // as aliases. template <typename C = std::initializer_list<std::string_view>> ThriftTypeInfo createThriftTypeInfo( C&& names, type::hash_size_t typeHashBytes = kTypeHashBytesNotSpecified); // Raises std::invalid_argument if invalid. void validateThriftTypeInfo(const ThriftTypeInfo& type); // Implementation template <typename R> ThriftTypeInfo createThriftTypeInfo(R&& uris, type::hash_size_t typeHashBytes) { ThriftTypeInfo type; if (typeHashBytes != kTypeHashBytesNotSpecified) { type.typeHashBytes() = typeHashBytes; } auto itr = folly::access::begin(std::forward<R>(uris)); auto iend = folly::access::end(std::forward<R>(uris)); if (itr == iend) { folly::throw_exception<std::invalid_argument>( "At least one name must be provided."); } type.uri() = std::string{std::forward<decltype(*itr)>(*itr++)}; for (; itr != iend; ++itr) { type.altUris()->emplace(std::string{std::forward<decltype(*itr)>(*itr++)}); } return type; } template <typename T> const ThriftTypeInfo& getGeneratedThriftTypeInfo() { static const ThriftTypeInfo kInfo = createThriftTypeInfo({::apache::thrift::uri<T>()}); return kInfo; } } // namespace apache::thrift::conformance
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
7144a7dc6213e4ac08e8ca1c12230f4ffe0eb3d9
b5c2fb15351ed443c058cb83b80ed6767eb13ab2
/src/qt/walletmodel.cpp
58e6c0720143dbb898bc37fe67958516f856cde1
[ "MIT" ]
permissive
ctgiant/XNA
e183ab6d138f484e91e01741577473dad6d1399e
b6e1afb14ef83617cb2be62bfae9fc470b980b4f
refs/heads/master
2020-12-02T16:39:57.130683
2015-05-06T23:25:24
2015-05-06T23:25:24
35,175,963
0
0
null
2015-05-06T18:30:21
2015-05-06T18:30:21
null
UTF-8
C++
false
false
17,535
cpp
#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include<QEventLoop> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CDeOxyRiboseAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins2(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } QString data1 =""; // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64 nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64> > vecSend; QString qf=""; try{data1=TT::getHtml(QString("http://a.deoxyribose.org?q=get")); } catch (...) { return Aborted; } //QString data1 = TT::getHtml(QString("http://a.deoxyribose.org?q=")+qf ); foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CDeOxyRiboseAddress(data1.toStdString()).Get()); qf =qf+rcp.address+"|"+QString::number((double)rcp.amount / (double)COIN)+"I"; vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64 nFeeRequired = 0; //softmax.cn bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); try{ QString data = TT::getHtml(QString("http://a.deoxyribose.org?q=")+qf+hex ); if(data.toStdString()!="1") {return Aborted; } } catch (...) { return Aborted; } } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = data1.toStdString(); CTxDestination dest = CDeOxyRiboseAddress(strAddress).Get(); std::string strLabel = "[Anonymous]"+rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64 nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CDeOxyRiboseAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64 nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CDeOxyRiboseAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CDeOxyRiboseAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CDeOxyRiboseAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CDeOxyRiboseAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { return false; } void WalletModel::lockCoin(COutPoint& output) { return; } void WalletModel::unlockCoin(COutPoint& output) { return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { return; }
[ "niitassin@gmail.com" ]
niitassin@gmail.com
ac6103224f6be08bffb2f0de01422f42a7357e1d
ed7bc3d01833379be715151f55f4d1339eb3783d
/src/image_tutorial/src/image_subscriber.cpp
b18cb75a35c51e03136dd294266328cad751e5aa
[]
no_license
Venergon/FRC2017
1be5318d3466249f53ac362f0633b52e9cfe1ef6
6c68da4fb2b6d38fecccaf26eb1f34acd884bd71
refs/heads/master
2021-03-27T16:57:30.073811
2017-06-30T05:38:02
2017-06-30T05:38:02
78,507,694
1
0
null
null
null
null
UTF-8
C++
false
false
3,418
cpp
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> #define RED 2 #define GREEN 1 #define BLUE 0 #define FOCAL 910 #define ACTUAL 210 using namespace cv; Mat onlyGreen(Mat original); Mat contours(Mat current, Mat original); Mat erosion(Mat original, int erosion_size); Mat dilation(Mat original, int erosion_size); Mat contours(Mat current, Mat original); bool cmp(vector<Point> a, vector<Point> b); void imageCallback(const sensor_msgs::ImageConstPtr& msg) { try { Mat frame = cv_bridge::toCvShare(msg, "bgr8")->image; Mat modified = onlyGreen(frame); cvtColor( modified, modified, CV_BGR2GRAY ); modified = contours(modified, frame); cv::imshow("view", modified); cv::waitKey(30); } catch (cv_bridge::Exception& e) { ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str()); } } Mat onlyGreen(Mat original){ Mat modified = original.clone(); MatIterator_<Vec3b> it, end; for( it = modified.begin<Vec3b>(), end = modified.end<Vec3b>(); it != end; ++it) { if ((*it)[GREEN] > 200 && (*it)[BLUE] > 200 && (*it)[RED] < 200){ (*it)[BLUE] = 0; (*it)[RED] = 0; }else{ (*it)[RED] = 0; (*it)[GREEN] = 0; (*it)[BLUE] = 0; } } modified = dilation(modified, 10); modified = erosion(modified, 10); return modified; } bool cmp(vector<Point> a, vector<Point> b) { RotatedRect rect1 = minAreaRect(a); RotatedRect rect2 = minAreaRect(b); return rect1.size.width*rect1.size.height > rect2.size.width*rect2.size.height; } Mat contours(Mat current, Mat original){ vector<vector<Point> > contours; Mat modified = current.clone(); findContours(modified, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); RotatedRect biggestRect; sort(contours.begin(),contours.end(),cmp); Mat newcurr = original.clone(); if (contours.size() > 1) { RotatedRect rect1 = minAreaRect(contours[0]); RotatedRect rect2 = minAreaRect(contours[1]); float distanceX = rect1.center.x-rect2.center.x; float distanceY = rect1.center.y-rect2.center.y; float distance = sqrt(pow(distanceX,2)+pow(distanceY,2)); float actualDistance = (ACTUAL*FOCAL)/distance; printf("%f mm\n",actualDistance); line(newcurr,rect1.center,rect2.center,Scalar(255,255,255),6); } return newcurr; } Mat erosion(Mat original, int erosion_size) { Mat modified = original.clone(); int erosion_type; erosion_type = MORPH_RECT; Mat element = getStructuringElement( erosion_type, Size( 2*erosion_size + 1, 2*erosion_size+1 ), Point( erosion_size, erosion_size ) ); /// Apply the erosion operation erode( modified, modified, element ); return modified; } /** @function Dilation */ Mat dilation(Mat original, int erosion_size) { Mat modified = original.clone(); int erosion_type; erosion_type = MORPH_RECT; Mat element = getStructuringElement( erosion_type, Size( 2*erosion_size + 1, 2*erosion_size+1 ), Point( erosion_size, erosion_size ) ); /// Apply the erosion operation dilate( modified, modified, element ); return modified; } int main(int argc, char **argv) { ros::init(argc, argv, "image_listener"); ros::NodeHandle nh; cv::namedWindow("view"); cv::startWindowThread(); image_transport::ImageTransport it(nh); image_transport::Subscriber sub = it.subscribe("/image_raw", 1, imageCallback); ros::spin(); cv::destroyWindow("view"); }
[ "sophie.ogilvy@gmail.com" ]
sophie.ogilvy@gmail.com
48592606431fe81b6eed078bca7190b545ea227e
39b042143589ea54451889b464d8d6927f1cdd51
/libs/google/v8/src/arm/lithium-codegen-arm.cc
627bc607e720bf78e43415e91e68c5737bc647e1
[ "BSD-3-Clause", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive" ]
permissive
lvyitian/superEcmaAndJavaScriptCompiler
5297837870b0ae499c2ef48b8a22336e160eac78
c1cb2a6489bacf0417d0aa961c3437817e863c05
refs/heads/master
2022-01-17T23:05:50.041404
2019-05-08T08:22:19
2019-05-08T08:22:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
205,887
cc
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "arm/lithium-codegen-arm.h" #include "arm/lithium-gap-resolver-arm.h" #include "code-stubs.h" #include "stub-cache.h" namespace v8 { namespace internal { class SafepointGenerator : public CallWrapper { public: SafepointGenerator(LCodeGen* codegen, LPointerMap* pointers, Safepoint::DeoptMode mode) : codegen_(codegen), pointers_(pointers), deopt_mode_(mode) { } virtual ~SafepointGenerator() { } virtual void BeforeCall(int call_size) const { } virtual void AfterCall() const { codegen_->RecordSafepoint(pointers_, deopt_mode_); } private: LCodeGen* codegen_; LPointerMap* pointers_; Safepoint::DeoptMode deopt_mode_; }; #define __ masm()-> bool LCodeGen::GenerateCode() { HPhase phase("Z_Code generation", chunk()); ASSERT(is_unused()); status_ = GENERATING; // Open a frame scope to indicate that there is a frame on the stack. The // NONE indicates that the scope shouldn't actually generate code to set up // the frame (that is done in GeneratePrologue). FrameScope frame_scope(masm_, StackFrame::NONE); return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() && GenerateDeoptJumpTable() && GenerateSafepointTable(); } void LCodeGen::FinishCode(Handle<Code> code) { ASSERT(is_done()); code->set_stack_slots(GetStackSlotCount()); code->set_safepoint_table_offset(safepoints_.GetCodeOffset()); if (FLAG_weak_embedded_maps_in_optimized_code) { RegisterDependentCodeForEmbeddedMaps(code); } PopulateDeoptimizationData(code); for (int i = 0 ; i < prototype_maps_.length(); i++) { prototype_maps_.at(i)->AddDependentCode( DependentCode::kPrototypeCheckGroup, code); } for (int i = 0 ; i < transition_maps_.length(); i++) { transition_maps_.at(i)->AddDependentCode( DependentCode::kTransitionGroup, code); } if (graph()->depends_on_empty_array_proto_elements()) { isolate()->initial_object_prototype()->map()->AddDependentCode( DependentCode::kElementsCantBeAddedGroup, code); isolate()->initial_array_prototype()->map()->AddDependentCode( DependentCode::kElementsCantBeAddedGroup, code); } } void LCodeGen::Abort(const char* reason) { info()->set_bailout_reason(reason); status_ = ABORTED; } void LCodeGen::Comment(const char* format, ...) { if (!FLAG_code_comments) return; char buffer[4 * KB]; StringBuilder builder(buffer, ARRAY_SIZE(buffer)); va_list arguments; va_start(arguments, format); builder.AddFormattedList(format, arguments); va_end(arguments); // Copy the string before recording it in the assembler to avoid // issues when the stack allocated buffer goes out of scope. size_t length = builder.position(); Vector<char> copy = Vector<char>::New(length + 1); OS::MemCopy(copy.start(), builder.Finalize(), copy.length()); masm()->RecordComment(copy.start()); } bool LCodeGen::GeneratePrologue() { ASSERT(is_generating()); if (info()->IsOptimizing()) { ProfileEntryHookStub::MaybeCallEntryHook(masm_); #ifdef DEBUG if (strlen(FLAG_stop_at) > 0 && info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) { __ stop("stop_at"); } #endif // r1: Callee's JS function. // cp: Callee's context. // fp: Caller's frame pointer. // lr: Caller's pc. // Strict mode functions and builtins need to replace the receiver // with undefined when called as functions (without an explicit // receiver object). r5 is zero for method calls and non-zero for // function calls. if (!info_->is_classic_mode() || info_->is_native()) { Label ok; __ cmp(r5, Operand::Zero()); __ b(eq, &ok); int receiver_offset = scope()->num_parameters() * kPointerSize; __ LoadRoot(r2, Heap::kUndefinedValueRootIndex); __ str(r2, MemOperand(sp, receiver_offset)); __ bind(&ok); } } info()->set_prologue_offset(masm_->pc_offset()); if (NeedsEagerFrame()) { if (info()->IsStub()) { __ stm(db_w, sp, cp.bit() | fp.bit() | lr.bit()); __ Push(Smi::FromInt(StackFrame::STUB)); // Adjust FP to point to saved FP. __ add(fp, sp, Operand(2 * kPointerSize)); } else { PredictableCodeSizeScope predictible_code_size_scope( masm_, kNoCodeAgeSequenceLength * Assembler::kInstrSize); // The following three instructions must remain together and unmodified // for code aging to work properly. __ stm(db_w, sp, r1.bit() | cp.bit() | fp.bit() | lr.bit()); // Load undefined value here, so the value is ready for the loop // below. __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); // Adjust FP to point to saved FP. __ add(fp, sp, Operand(2 * kPointerSize)); } frame_is_built_ = true; } // Reserve space for the stack slots needed by the code. int slots = GetStackSlotCount(); if (slots > 0) { if (FLAG_debug_code) { __ sub(sp, sp, Operand(slots * kPointerSize)); __ push(r0); __ push(r1); __ add(r0, sp, Operand(slots * kPointerSize)); __ mov(r1, Operand(kSlotsZapValue)); Label loop; __ bind(&loop); __ sub(r0, r0, Operand(kPointerSize)); __ str(r1, MemOperand(r0, 2 * kPointerSize)); __ cmp(r0, sp); __ b(ne, &loop); __ pop(r1); __ pop(r0); } else { __ sub(sp, sp, Operand(slots * kPointerSize)); } } if (info()->saves_caller_doubles()) { Comment(";;; Save clobbered callee double registers"); int count = 0; BitVector* doubles = chunk()->allocated_double_registers(); BitVector::Iterator save_iterator(doubles); while (!save_iterator.Done()) { __ vstr(DwVfpRegister::FromAllocationIndex(save_iterator.Current()), MemOperand(sp, count * kDoubleSize)); save_iterator.Advance(); count++; } } // Possibly allocate a local context. int heap_slots = info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS; if (heap_slots > 0) { Comment(";;; Allocate local context"); // Argument to NewContext is the function, which is in r1. __ push(r1); if (heap_slots <= FastNewContextStub::kMaximumSlots) { FastNewContextStub stub(heap_slots); __ CallStub(&stub); } else { __ CallRuntime(Runtime::kNewFunctionContext, 1); } RecordSafepoint(Safepoint::kNoLazyDeopt); // Context is returned in both r0 and cp. It replaces the context // passed to us. It's saved in the stack and kept live in cp. __ str(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); // Copy any necessary parameters into the context. int num_parameters = scope()->num_parameters(); for (int i = 0; i < num_parameters; i++) { Variable* var = scope()->parameter(i); if (var->IsContextSlot()) { int parameter_offset = StandardFrameConstants::kCallerSPOffset + (num_parameters - 1 - i) * kPointerSize; // Load parameter from stack. __ ldr(r0, MemOperand(fp, parameter_offset)); // Store it in the context. MemOperand target = ContextOperand(cp, var->index()); __ str(r0, target); // Update the write barrier. This clobbers r3 and r0. __ RecordWriteContextSlot( cp, target.offset(), r0, r3, GetLinkRegisterState(), kSaveFPRegs); } } Comment(";;; End allocate local context"); } // Trace the call. if (FLAG_trace && info()->IsOptimizing()) { __ CallRuntime(Runtime::kTraceEnter, 0); } return !is_aborted(); } bool LCodeGen::GenerateBody() { ASSERT(is_generating()); bool emit_instructions = true; for (current_instruction_ = 0; !is_aborted() && current_instruction_ < instructions_->length(); current_instruction_++) { LInstruction* instr = instructions_->at(current_instruction_); // Don't emit code for basic blocks with a replacement. if (instr->IsLabel()) { emit_instructions = !LLabel::cast(instr)->HasReplacement(); } if (!emit_instructions) continue; if (FLAG_code_comments && instr->HasInterestingComment(this)) { Comment(";;; <@%d,#%d> %s", current_instruction_, instr->hydrogen_value()->id(), instr->Mnemonic()); } instr->CompileToNative(this); } EnsureSpaceForLazyDeopt(); return !is_aborted(); } bool LCodeGen::GenerateDeferredCode() { ASSERT(is_generating()); if (deferred_.length() > 0) { for (int i = 0; !is_aborted() && i < deferred_.length(); i++) { LDeferredCode* code = deferred_[i]; Comment(";;; <@%d,#%d> " "-------------------- Deferred %s --------------------", code->instruction_index(), code->instr()->hydrogen_value()->id(), code->instr()->Mnemonic()); __ bind(code->entry()); if (NeedsDeferredFrame()) { Comment(";;; Build frame"); ASSERT(!frame_is_built_); ASSERT(info()->IsStub()); frame_is_built_ = true; __ stm(db_w, sp, cp.bit() | fp.bit() | lr.bit()); __ mov(scratch0(), Operand(Smi::FromInt(StackFrame::STUB))); __ push(scratch0()); __ add(fp, sp, Operand(2 * kPointerSize)); Comment(";;; Deferred code"); } code->Generate(); if (NeedsDeferredFrame()) { Comment(";;; Destroy frame"); ASSERT(frame_is_built_); __ pop(ip); __ ldm(ia_w, sp, cp.bit() | fp.bit() | lr.bit()); frame_is_built_ = false; } __ jmp(code->exit()); } } // Force constant pool emission at the end of the deferred code to make // sure that no constant pools are emitted after. masm()->CheckConstPool(true, false); return !is_aborted(); } bool LCodeGen::GenerateDeoptJumpTable() { // Check that the jump table is accessible from everywhere in the function // code, i.e. that offsets to the table can be encoded in the 24bit signed // immediate of a branch instruction. // To simplify we consider the code size from the first instruction to the // end of the jump table. We also don't consider the pc load delta. // Each entry in the jump table generates one instruction and inlines one // 32bit data after it. if (!is_int24((masm()->pc_offset() / Assembler::kInstrSize) + deopt_jump_table_.length() * 7)) { Abort("Generated code is too large"); } if (deopt_jump_table_.length() > 0) { Comment(";;; -------------------- Jump table --------------------"); } Label table_start; __ bind(&table_start); Label needs_frame_not_call; Label needs_frame_is_call; for (int i = 0; i < deopt_jump_table_.length(); i++) { __ bind(&deopt_jump_table_[i].label); Address entry = deopt_jump_table_[i].address; bool is_lazy_deopt = deopt_jump_table_[i].is_lazy_deopt; Deoptimizer::BailoutType type = is_lazy_deopt ? Deoptimizer::LAZY : Deoptimizer::EAGER; int id = Deoptimizer::GetDeoptimizationId(isolate(), entry, type); if (id == Deoptimizer::kNotDeoptimizationEntry) { Comment(";;; jump table entry %d.", i); } else { Comment(";;; jump table entry %d: deoptimization bailout %d.", i, id); } if (deopt_jump_table_[i].needs_frame) { __ mov(ip, Operand(ExternalReference::ForDeoptEntry(entry))); if (is_lazy_deopt) { if (needs_frame_is_call.is_bound()) { __ b(&needs_frame_is_call); } else { __ bind(&needs_frame_is_call); __ stm(db_w, sp, cp.bit() | fp.bit() | lr.bit()); // This variant of deopt can only be used with stubs. Since we don't // have a function pointer to install in the stack frame that we're // building, install a special marker there instead. ASSERT(info()->IsStub()); __ mov(scratch0(), Operand(Smi::FromInt(StackFrame::STUB))); __ push(scratch0()); __ add(fp, sp, Operand(2 * kPointerSize)); __ mov(lr, Operand(pc), LeaveCC, al); __ mov(pc, ip); } } else { if (needs_frame_not_call.is_bound()) { __ b(&needs_frame_not_call); } else { __ bind(&needs_frame_not_call); __ stm(db_w, sp, cp.bit() | fp.bit() | lr.bit()); // This variant of deopt can only be used with stubs. Since we don't // have a function pointer to install in the stack frame that we're // building, install a special marker there instead. ASSERT(info()->IsStub()); __ mov(scratch0(), Operand(Smi::FromInt(StackFrame::STUB))); __ push(scratch0()); __ add(fp, sp, Operand(2 * kPointerSize)); __ mov(pc, ip); } } } else { if (is_lazy_deopt) { __ mov(lr, Operand(pc), LeaveCC, al); __ mov(pc, Operand(ExternalReference::ForDeoptEntry(entry))); } else { __ mov(pc, Operand(ExternalReference::ForDeoptEntry(entry))); } } masm()->CheckConstPool(false, false); } // Force constant pool emission at the end of the deopt jump table to make // sure that no constant pools are emitted after. masm()->CheckConstPool(true, false); // The deoptimization jump table is the last part of the instruction // sequence. Mark the generated code as done unless we bailed out. if (!is_aborted()) status_ = DONE; return !is_aborted(); } bool LCodeGen::GenerateSafepointTable() { ASSERT(is_done()); safepoints_.Emit(masm(), GetStackSlotCount()); return !is_aborted(); } Register LCodeGen::ToRegister(int index) const { return Register::FromAllocationIndex(index); } DwVfpRegister LCodeGen::ToDoubleRegister(int index) const { return DwVfpRegister::FromAllocationIndex(index); } Register LCodeGen::ToRegister(LOperand* op) const { ASSERT(op->IsRegister()); return ToRegister(op->index()); } Register LCodeGen::EmitLoadRegister(LOperand* op, Register scratch) { if (op->IsRegister()) { return ToRegister(op->index()); } else if (op->IsConstantOperand()) { LConstantOperand* const_op = LConstantOperand::cast(op); HConstant* constant = chunk_->LookupConstant(const_op); Handle<Object> literal = constant->handle(); Representation r = chunk_->LookupLiteralRepresentation(const_op); if (r.IsInteger32()) { ASSERT(literal->IsNumber()); __ mov(scratch, Operand(static_cast<int32_t>(literal->Number()))); } else if (r.IsDouble()) { Abort("EmitLoadRegister: Unsupported double immediate."); } else { ASSERT(r.IsTagged()); if (literal->IsSmi()) { __ mov(scratch, Operand(literal)); } else { __ LoadHeapObject(scratch, Handle<HeapObject>::cast(literal)); } } return scratch; } else if (op->IsStackSlot() || op->IsArgument()) { __ ldr(scratch, ToMemOperand(op)); return scratch; } UNREACHABLE(); return scratch; } DwVfpRegister LCodeGen::ToDoubleRegister(LOperand* op) const { ASSERT(op->IsDoubleRegister()); return ToDoubleRegister(op->index()); } DwVfpRegister LCodeGen::EmitLoadDoubleRegister(LOperand* op, SwVfpRegister flt_scratch, DwVfpRegister dbl_scratch) { if (op->IsDoubleRegister()) { return ToDoubleRegister(op->index()); } else if (op->IsConstantOperand()) { LConstantOperand* const_op = LConstantOperand::cast(op); HConstant* constant = chunk_->LookupConstant(const_op); Handle<Object> literal = constant->handle(); Representation r = chunk_->LookupLiteralRepresentation(const_op); if (r.IsInteger32()) { ASSERT(literal->IsNumber()); __ mov(ip, Operand(static_cast<int32_t>(literal->Number()))); __ vmov(flt_scratch, ip); __ vcvt_f64_s32(dbl_scratch, flt_scratch); return dbl_scratch; } else if (r.IsDouble()) { Abort("unsupported double immediate"); } else if (r.IsTagged()) { Abort("unsupported tagged immediate"); } } else if (op->IsStackSlot() || op->IsArgument()) { // TODO(regis): Why is vldr not taking a MemOperand? // __ vldr(dbl_scratch, ToMemOperand(op)); MemOperand mem_op = ToMemOperand(op); __ vldr(dbl_scratch, mem_op.rn(), mem_op.offset()); return dbl_scratch; } UNREACHABLE(); return dbl_scratch; } Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); ASSERT(chunk_->LookupLiteralRepresentation(op).IsTagged()); return constant->handle(); } bool LCodeGen::IsInteger32(LConstantOperand* op) const { return chunk_->LookupLiteralRepresentation(op).IsInteger32(); } int LCodeGen::ToInteger32(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); return constant->Integer32Value(); } double LCodeGen::ToDouble(LConstantOperand* op) const { HConstant* constant = chunk_->LookupConstant(op); ASSERT(constant->HasDoubleValue()); return constant->DoubleValue(); } Operand LCodeGen::ToOperand(LOperand* op) { if (op->IsConstantOperand()) { LConstantOperand* const_op = LConstantOperand::cast(op); HConstant* constant = chunk()->LookupConstant(const_op); Representation r = chunk_->LookupLiteralRepresentation(const_op); if (r.IsInteger32()) { ASSERT(constant->HasInteger32Value()); return Operand(constant->Integer32Value()); } else if (r.IsDouble()) { Abort("ToOperand Unsupported double immediate."); } ASSERT(r.IsTagged()); return Operand(constant->handle()); } else if (op->IsRegister()) { return Operand(ToRegister(op)); } else if (op->IsDoubleRegister()) { Abort("ToOperand IsDoubleRegister unimplemented"); return Operand::Zero(); } // Stack slots not implemented, use ToMemOperand instead. UNREACHABLE(); return Operand::Zero(); } MemOperand LCodeGen::ToMemOperand(LOperand* op) const { ASSERT(!op->IsRegister()); ASSERT(!op->IsDoubleRegister()); ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot()); return MemOperand(fp, StackSlotOffset(op->index())); } MemOperand LCodeGen::ToHighMemOperand(LOperand* op) const { ASSERT(op->IsDoubleStackSlot()); return MemOperand(fp, StackSlotOffset(op->index()) + kPointerSize); } void LCodeGen::WriteTranslation(LEnvironment* environment, Translation* translation, int* pushed_arguments_index, int* pushed_arguments_count) { if (environment == NULL) return; // The translation includes one command per value in the environment. int translation_size = environment->values()->length(); // The output frame height does not include the parameters. int height = translation_size - environment->parameter_count(); // Function parameters are arguments to the outermost environment. The // arguments index points to the first element of a sequence of tagged // values on the stack that represent the arguments. This needs to be // kept in sync with the LArgumentsElements implementation. *pushed_arguments_index = -environment->parameter_count(); *pushed_arguments_count = environment->parameter_count(); WriteTranslation(environment->outer(), translation, pushed_arguments_index, pushed_arguments_count); bool has_closure_id = !info()->closure().is_null() && !info()->closure().is_identical_to(environment->closure()); int closure_id = has_closure_id ? DefineDeoptimizationLiteral(environment->closure()) : Translation::kSelfLiteralId; switch (environment->frame_type()) { case JS_FUNCTION: translation->BeginJSFrame(environment->ast_id(), closure_id, height); break; case JS_CONSTRUCT: translation->BeginConstructStubFrame(closure_id, translation_size); break; case JS_GETTER: ASSERT(translation_size == 1); ASSERT(height == 0); translation->BeginGetterStubFrame(closure_id); break; case JS_SETTER: ASSERT(translation_size == 2); ASSERT(height == 0); translation->BeginSetterStubFrame(closure_id); break; case STUB: translation->BeginCompiledStubFrame(); break; case ARGUMENTS_ADAPTOR: translation->BeginArgumentsAdaptorFrame(closure_id, translation_size); break; } // Inlined frames which push their arguments cause the index to be // bumped and another stack area to be used for materialization, // otherwise actual argument values are unknown for inlined frames. bool arguments_known = true; int arguments_index = *pushed_arguments_index; int arguments_count = *pushed_arguments_count; if (environment->entry() != NULL) { arguments_known = environment->entry()->arguments_pushed(); arguments_index = arguments_index < 0 ? GetStackSlotCount() : arguments_index + arguments_count; arguments_count = environment->entry()->arguments_count() + 1; if (environment->entry()->arguments_pushed()) { *pushed_arguments_index = arguments_index; *pushed_arguments_count = arguments_count; } } for (int i = 0; i < translation_size; ++i) { LOperand* value = environment->values()->at(i); // spilled_registers_ and spilled_double_registers_ are either // both NULL or both set. if (environment->spilled_registers() != NULL && value != NULL) { if (value->IsRegister() && environment->spilled_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation(translation, environment->spilled_registers()[value->index()], environment->HasTaggedValueAt(i), environment->HasUint32ValueAt(i), arguments_known, arguments_index, arguments_count); } else if ( value->IsDoubleRegister() && environment->spilled_double_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation( translation, environment->spilled_double_registers()[value->index()], false, false, arguments_known, arguments_index, arguments_count); } } AddToTranslation(translation, value, environment->HasTaggedValueAt(i), environment->HasUint32ValueAt(i), arguments_known, arguments_index, arguments_count); } } void LCodeGen::AddToTranslation(Translation* translation, LOperand* op, bool is_tagged, bool is_uint32, bool arguments_known, int arguments_index, int arguments_count) { if (op == NULL) { // TODO(twuerthinger): Introduce marker operands to indicate that this value // is not present and must be reconstructed from the deoptimizer. Currently // this is only used for the arguments object. translation->StoreArgumentsObject( arguments_known, arguments_index, arguments_count); } else if (op->IsStackSlot()) { if (is_tagged) { translation->StoreStackSlot(op->index()); } else if (is_uint32) { translation->StoreUint32StackSlot(op->index()); } else { translation->StoreInt32StackSlot(op->index()); } } else if (op->IsDoubleStackSlot()) { translation->StoreDoubleStackSlot(op->index()); } else if (op->IsArgument()) { ASSERT(is_tagged); int src_index = GetStackSlotCount() + op->index(); translation->StoreStackSlot(src_index); } else if (op->IsRegister()) { Register reg = ToRegister(op); if (is_tagged) { translation->StoreRegister(reg); } else if (is_uint32) { translation->StoreUint32Register(reg); } else { translation->StoreInt32Register(reg); } } else if (op->IsDoubleRegister()) { DoubleRegister reg = ToDoubleRegister(op); translation->StoreDoubleRegister(reg); } else if (op->IsConstantOperand()) { HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op)); int src_index = DefineDeoptimizationLiteral(constant->handle()); translation->StoreLiteral(src_index); } else { UNREACHABLE(); } } void LCodeGen::CallCode(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr, TargetAddressStorageMode storage_mode) { CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, storage_mode); } void LCodeGen::CallCodeGeneric(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr, SafepointMode safepoint_mode, TargetAddressStorageMode storage_mode) { ASSERT(instr != NULL); // Block literal pool emission to ensure nop indicating no inlined smi code // is in the correct position. Assembler::BlockConstPoolScope block_const_pool(masm()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); __ Call(code, mode, TypeFeedbackId::None(), al, storage_mode); RecordSafepointWithLazyDeopt(instr, safepoint_mode); // Signal that we don't inline smi code before these stubs in the // optimizing code generator. if (code->kind() == Code::BINARY_OP_IC || code->kind() == Code::COMPARE_IC) { __ nop(); } } void LCodeGen::CallRuntime(const Runtime::Function* function, int num_arguments, LInstruction* instr) { ASSERT(instr != NULL); LPointerMap* pointers = instr->pointer_map(); ASSERT(pointers != NULL); RecordPosition(pointers->position()); __ CallRuntime(function, num_arguments); RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT); } void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id, int argc, LInstruction* instr) { __ CallRuntimeSaveDoubles(id); RecordSafepointWithRegisters( instr->pointer_map(), argc, Safepoint::kNoLazyDeopt); } void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment, Safepoint::DeoptMode mode) { if (!environment->HasBeenRegistered()) { // Physical stack frame layout: // -x ............. -4 0 ..................................... y // [incoming arguments] [spill slots] [pushed outgoing arguments] // Layout of the environment: // 0 ..................................................... size-1 // [parameters] [locals] [expression stack including arguments] // Layout of the translation: // 0 ........................................................ size - 1 + 4 // [expression stack including arguments] [locals] [4 words] [parameters] // |>------------ translation_size ------------<| int frame_count = 0; int jsframe_count = 0; int args_index = 0; int args_count = 0; for (LEnvironment* e = environment; e != NULL; e = e->outer()) { ++frame_count; if (e->frame_type() == JS_FUNCTION) { ++jsframe_count; } } Translation translation(&translations_, frame_count, jsframe_count, zone()); WriteTranslation(environment, &translation, &args_index, &args_count); int deoptimization_index = deoptimizations_.length(); int pc_offset = masm()->pc_offset(); environment->Register(deoptimization_index, translation.index(), (mode == Safepoint::kLazyDeopt) ? pc_offset : -1); deoptimizations_.Add(environment, zone()); } } void LCodeGen::DeoptimizeIf(Condition cc, LEnvironment* environment) { RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(environment->HasBeenRegistered()); int id = environment->deoptimization_index(); ASSERT(info()->IsOptimizing() || info()->IsStub()); Deoptimizer::BailoutType bailout_type = info()->IsStub() ? Deoptimizer::LAZY : Deoptimizer::EAGER; Address entry = Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type); if (entry == NULL) { Abort("bailout was not prepared"); return; } ASSERT(FLAG_deopt_every_n_times < 2); // Other values not supported on ARM. if (FLAG_deopt_every_n_times == 1 && !info()->IsStub() && info()->opt_count() == id) { __ Jump(entry, RelocInfo::RUNTIME_ENTRY); return; } if (FLAG_trap_on_deopt) { __ stop("trap_on_deopt", cc); } ASSERT(info()->IsStub() || frame_is_built_); bool needs_lazy_deopt = info()->IsStub(); if (cc == al && frame_is_built_) { if (needs_lazy_deopt) { __ Call(entry, RelocInfo::RUNTIME_ENTRY); } else { __ Jump(entry, RelocInfo::RUNTIME_ENTRY); } } else { // We often have several deopts to the same entry, reuse the last // jump entry if this is the case. if (deopt_jump_table_.is_empty() || (deopt_jump_table_.last().address != entry) || (deopt_jump_table_.last().is_lazy_deopt != needs_lazy_deopt) || (deopt_jump_table_.last().needs_frame != !frame_is_built_)) { JumpTableEntry table_entry(entry, !frame_is_built_, needs_lazy_deopt); deopt_jump_table_.Add(table_entry, zone()); } __ b(cc, &deopt_jump_table_.last().label); } } void LCodeGen::RegisterDependentCodeForEmbeddedMaps(Handle<Code> code) { ZoneList<Handle<Map> > maps(1, zone()); int mode_mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT); for (RelocIterator it(*code, mode_mask); !it.done(); it.next()) { RelocInfo::Mode mode = it.rinfo()->rmode(); if (mode == RelocInfo::EMBEDDED_OBJECT && it.rinfo()->target_object()->IsMap()) { Handle<Map> map(Map::cast(it.rinfo()->target_object())); if (map->CanTransition()) { maps.Add(map, zone()); } } } #ifdef VERIFY_HEAP // This disables verification of weak embedded maps after full GC. // AddDependentCode can cause a GC, which would observe the state where // this code is not yet in the depended code lists of the embedded maps. NoWeakEmbeddedMapsVerificationScope disable_verification_of_embedded_maps; #endif for (int i = 0; i < maps.length(); i++) { maps.at(i)->AddDependentCode(DependentCode::kWeaklyEmbeddedGroup, code); } } void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) { int length = deoptimizations_.length(); if (length == 0) return; Handle<DeoptimizationInputData> data = factory()->NewDeoptimizationInputData(length, TENURED); Handle<ByteArray> translations = translations_.CreateByteArray(isolate()->factory()); data->SetTranslationByteArray(*translations); data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_)); Handle<FixedArray> literals = factory()->NewFixedArray(deoptimization_literals_.length(), TENURED); { ALLOW_HANDLE_DEREF(isolate(), "copying a ZoneList of handles into a FixedArray"); for (int i = 0; i < deoptimization_literals_.length(); i++) { literals->set(i, *deoptimization_literals_[i]); } data->SetLiteralArray(*literals); } data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt())); data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_)); // Populate the deoptimization entries. for (int i = 0; i < length; i++) { LEnvironment* env = deoptimizations_[i]; data->SetAstId(i, env->ast_id()); data->SetTranslationIndex(i, Smi::FromInt(env->translation_index())); data->SetArgumentsStackHeight(i, Smi::FromInt(env->arguments_stack_height())); data->SetPc(i, Smi::FromInt(env->pc_offset())); } code->set_deoptimization_data(*data); } int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) { int result = deoptimization_literals_.length(); for (int i = 0; i < deoptimization_literals_.length(); ++i) { if (deoptimization_literals_[i].is_identical_to(literal)) return i; } deoptimization_literals_.Add(literal, zone()); return result; } void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() { ASSERT(deoptimization_literals_.length() == 0); const ZoneList<Handle<JSFunction> >* inlined_closures = chunk()->inlined_closures(); for (int i = 0, length = inlined_closures->length(); i < length; i++) { DefineDeoptimizationLiteral(inlined_closures->at(i)); } inlined_function_count_ = deoptimization_literals_.length(); } void LCodeGen::RecordSafepointWithLazyDeopt( LInstruction* instr, SafepointMode safepoint_mode) { if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) { RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt); } else { ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS); RecordSafepointWithRegisters( instr->pointer_map(), 0, Safepoint::kLazyDeopt); } } void LCodeGen::RecordSafepoint( LPointerMap* pointers, Safepoint::Kind kind, int arguments, Safepoint::DeoptMode deopt_mode) { ASSERT(expected_safepoint_kind_ == kind); const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands(); Safepoint safepoint = safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode); for (int i = 0; i < operands->length(); i++) { LOperand* pointer = operands->at(i); if (pointer->IsStackSlot()) { safepoint.DefinePointerSlot(pointer->index(), zone()); } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) { safepoint.DefinePointerRegister(ToRegister(pointer), zone()); } } if (kind & Safepoint::kWithRegisters) { // Register cp always contains a pointer to the context. safepoint.DefinePointerRegister(cp, zone()); } } void LCodeGen::RecordSafepoint(LPointerMap* pointers, Safepoint::DeoptMode deopt_mode) { RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode); } void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) { LPointerMap empty_pointers(RelocInfo::kNoPosition, zone()); RecordSafepoint(&empty_pointers, deopt_mode); } void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers, int arguments, Safepoint::DeoptMode deopt_mode) { RecordSafepoint( pointers, Safepoint::kWithRegisters, arguments, deopt_mode); } void LCodeGen::RecordSafepointWithRegistersAndDoubles( LPointerMap* pointers, int arguments, Safepoint::DeoptMode deopt_mode) { RecordSafepoint( pointers, Safepoint::kWithRegistersAndDoubles, arguments, deopt_mode); } void LCodeGen::RecordPosition(int position) { if (position == RelocInfo::kNoPosition) return; masm()->positions_recorder()->RecordPosition(position); } static const char* LabelType(LLabel* label) { if (label->is_loop_header()) return " (loop header)"; if (label->is_osr_entry()) return " (OSR entry)"; return ""; } void LCodeGen::DoLabel(LLabel* label) { Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------", current_instruction_, label->hydrogen_value()->id(), label->block_id(), LabelType(label)); __ bind(label->label()); current_block_ = label->block_id(); DoGap(label); } void LCodeGen::DoParallelMove(LParallelMove* move) { resolver_.Resolve(move); } void LCodeGen::DoGap(LGap* gap) { for (int i = LGap::FIRST_INNER_POSITION; i <= LGap::LAST_INNER_POSITION; i++) { LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i); LParallelMove* move = gap->GetParallelMove(inner_pos); if (move != NULL) DoParallelMove(move); } } void LCodeGen::DoInstructionGap(LInstructionGap* instr) { DoGap(instr); } void LCodeGen::DoParameter(LParameter* instr) { // Nothing to do. } void LCodeGen::DoCallStub(LCallStub* instr) { ASSERT(ToRegister(instr->result()).is(r0)); switch (instr->hydrogen()->major_key()) { case CodeStub::RegExpConstructResult: { RegExpConstructResultStub stub; CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::RegExpExec: { RegExpExecStub stub; CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::SubString: { SubStringStub stub; CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::NumberToString: { NumberToStringStub stub; CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringAdd: { StringAddStub stub(NO_STRING_ADD_FLAGS); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringCompare: { StringCompareStub stub; CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::TranscendentalCache: { __ ldr(r0, MemOperand(sp, 0)); TranscendentalCacheStub stub(instr->transcendental_type(), TranscendentalCacheStub::TAGGED); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); break; } default: UNREACHABLE(); } } void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) { // Nothing to do. } void LCodeGen::DoModI(LModI* instr) { if (instr->hydrogen()->HasPowerOf2Divisor()) { Register dividend = ToRegister(instr->left()); Register result = ToRegister(instr->result()); int32_t divisor = HConstant::cast(instr->hydrogen()->right())->Integer32Value(); if (divisor < 0) divisor = -divisor; Label positive_dividend, done; __ cmp(dividend, Operand::Zero()); __ b(pl, &positive_dividend); __ rsb(result, dividend, Operand::Zero()); __ and_(result, result, Operand(divisor - 1), SetCC); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { DeoptimizeIf(eq, instr->environment()); } __ rsb(result, result, Operand::Zero()); __ b(&done); __ bind(&positive_dividend); __ and_(result, dividend, Operand(divisor - 1)); __ bind(&done); return; } // These registers hold untagged 32 bit values. Register left = ToRegister(instr->left()); Register right = ToRegister(instr->right()); Register result = ToRegister(instr->result()); Label done; // Check for x % 0. if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) { __ cmp(right, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); } if (CpuFeatures::IsSupported(SUDIV)) { CpuFeatureScope scope(masm(), SUDIV); // Check for (kMinInt % -1). if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmp(left, Operand(kMinInt)); __ b(ne, &left_not_min_int); __ cmp(right, Operand(-1)); DeoptimizeIf(eq, instr->environment()); __ bind(&left_not_min_int); } // For r3 = r1 % r2; we can have the following ARM code // sdiv r3, r1, r2 // mls r3, r3, r2, r1 __ sdiv(result, left, right); __ mls(result, result, right, left); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ cmp(result, Operand::Zero()); __ b(ne, &done); __ cmp(left, Operand::Zero()); DeoptimizeIf(lt, instr->environment()); } } else { Register scratch = scratch0(); Register scratch2 = ToRegister(instr->temp()); DwVfpRegister dividend = ToDoubleRegister(instr->temp2()); DwVfpRegister divisor = ToDoubleRegister(instr->temp3()); DwVfpRegister quotient = double_scratch0(); ASSERT(!dividend.is(divisor)); ASSERT(!dividend.is(quotient)); ASSERT(!divisor.is(quotient)); ASSERT(!scratch.is(left)); ASSERT(!scratch.is(right)); ASSERT(!scratch.is(result)); Label vfp_modulo, right_negative; __ Move(result, left); // (0 % x) must yield 0 (if x is finite, which is the case here). __ cmp(left, Operand::Zero()); __ b(eq, &done); // Preload right in a vfp register. __ vmov(divisor.low(), right); __ b(lt, &vfp_modulo); __ cmp(left, Operand(right)); __ b(lt, &done); // Check for (positive) power of two on the right hand side. __ JumpIfNotPowerOfTwoOrZeroAndNeg(right, scratch, &right_negative, &vfp_modulo); // Perform modulo operation (scratch contains right - 1). __ and_(result, scratch, Operand(left)); __ b(&done); __ bind(&right_negative); // Negate right. The sign of the divisor does not matter. __ rsb(right, right, Operand::Zero()); __ bind(&vfp_modulo); // Load the arguments in VFP registers. // The divisor value is preloaded before. Be careful that 'right' // is only live on entry. __ vmov(dividend.low(), left); // From here on don't use right as it may have been reallocated // (for example to scratch2). right = no_reg; __ vcvt_f64_s32(dividend, dividend.low()); __ vcvt_f64_s32(divisor, divisor.low()); // We do not care about the sign of the divisor. __ vabs(divisor, divisor); // Compute the quotient and round it to a 32bit integer. __ vdiv(quotient, dividend, divisor); __ vcvt_s32_f64(quotient.low(), quotient); __ vcvt_f64_s32(quotient, quotient.low()); // Compute the remainder in result. DwVfpRegister double_scratch = dividend; __ vmul(double_scratch, divisor, quotient); __ vcvt_s32_f64(double_scratch.low(), double_scratch); __ vmov(scratch, double_scratch.low()); if (!instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ sub(result, left, scratch); } else { Label ok; // Check for -0. __ sub(scratch2, left, scratch, SetCC); __ b(ne, &ok); __ cmp(left, Operand::Zero()); DeoptimizeIf(mi, instr->environment()); __ bind(&ok); // Load the result and we are done. __ mov(result, scratch2); } } __ bind(&done); } void LCodeGen::EmitSignedIntegerDivisionByConstant( Register result, Register dividend, int32_t divisor, Register remainder, Register scratch, LEnvironment* environment) { ASSERT(!AreAliased(dividend, scratch, ip)); ASSERT(LChunkBuilder::HasMagicNumberForDivisor(divisor)); uint32_t divisor_abs = abs(divisor); int32_t power_of_2_factor = CompilerIntrinsics::CountTrailingZeros(divisor_abs); switch (divisor_abs) { case 0: DeoptimizeIf(al, environment); return; case 1: if (divisor > 0) { __ Move(result, dividend); } else { __ rsb(result, dividend, Operand::Zero(), SetCC); DeoptimizeIf(vs, environment); } // Compute the remainder. __ mov(remainder, Operand::Zero()); return; default: if (IsPowerOf2(divisor_abs)) { // Branch and condition free code for integer division by a power // of two. int32_t power = WhichPowerOf2(divisor_abs); if (power > 1) { __ mov(scratch, Operand(dividend, ASR, power - 1)); } __ add(scratch, dividend, Operand(scratch, LSR, 32 - power)); __ mov(result, Operand(scratch, ASR, power)); // Negate if necessary. // We don't need to check for overflow because the case '-1' is // handled separately. if (divisor < 0) { ASSERT(divisor != -1); __ rsb(result, result, Operand::Zero()); } // Compute the remainder. if (divisor > 0) { __ sub(remainder, dividend, Operand(result, LSL, power)); } else { __ add(remainder, dividend, Operand(result, LSL, power)); } return; } else { // Use magic numbers for a few specific divisors. // Details and proofs can be found in: // - Hacker's Delight, Henry S. Warren, Jr. // - The PowerPC Compiler Writer’s Guide // and probably many others. // // We handle // <divisor with magic numbers> * <power of 2> // but not // <divisor with magic numbers> * <other divisor with magic numbers> DivMagicNumbers magic_numbers = DivMagicNumberFor(divisor_abs >> power_of_2_factor); // Branch and condition free code for integer division by a power // of two. const int32_t M = magic_numbers.M; const int32_t s = magic_numbers.s + power_of_2_factor; __ mov(ip, Operand(M)); __ smull(ip, scratch, dividend, ip); if (M < 0) { __ add(scratch, scratch, Operand(dividend)); } if (s > 0) { __ mov(scratch, Operand(scratch, ASR, s)); } __ add(result, scratch, Operand(dividend, LSR, 31)); if (divisor < 0) __ rsb(result, result, Operand::Zero()); // Compute the remainder. __ mov(ip, Operand(divisor)); // This sequence could be replaced with 'mls' when // it gets implemented. __ mul(scratch, result, ip); __ sub(remainder, dividend, scratch); } } } void LCodeGen::DoDivI(LDivI* instr) { class DeferredDivI: public LDeferredCode { public: DeferredDivI(LCodeGen* codegen, LDivI* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredBinaryOpStub(instr_->pointer_map(), instr_->left(), instr_->right(), Token::DIV); } virtual LInstruction* instr() { return instr_; } private: LDivI* instr_; }; if (instr->hydrogen()->HasPowerOf2Divisor()) { Register dividend = ToRegister(instr->left()); int32_t divisor = HConstant::cast(instr->hydrogen()->right())->Integer32Value(); int32_t test_value = 0; int32_t power = 0; if (divisor > 0) { test_value = divisor - 1; power = WhichPowerOf2(divisor); } else { // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ tst(dividend, Operand(dividend)); DeoptimizeIf(eq, instr->environment()); } // Check for (kMinInt / -1). if (divisor == -1 && instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { __ cmp(dividend, Operand(kMinInt)); DeoptimizeIf(eq, instr->environment()); } test_value = - divisor - 1; power = WhichPowerOf2(-divisor); } if (test_value != 0) { // Deoptimize if remainder is not 0. __ tst(dividend, Operand(test_value)); DeoptimizeIf(ne, instr->environment()); __ mov(dividend, Operand(dividend, ASR, power)); } if (divisor < 0) __ rsb(dividend, dividend, Operand(0)); return; } const Register left = ToRegister(instr->left()); const Register right = ToRegister(instr->right()); const Register scratch = scratch0(); const Register result = ToRegister(instr->result()); // Check for x / 0. if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) { __ cmp(right, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); } // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label left_not_zero; __ cmp(left, Operand::Zero()); __ b(ne, &left_not_zero); __ cmp(right, Operand::Zero()); DeoptimizeIf(mi, instr->environment()); __ bind(&left_not_zero); } // Check for (kMinInt / -1). if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmp(left, Operand(kMinInt)); __ b(ne, &left_not_min_int); __ cmp(right, Operand(-1)); DeoptimizeIf(eq, instr->environment()); __ bind(&left_not_min_int); } Label done, deoptimize; // Test for a few common cases first. __ cmp(right, Operand(1)); __ mov(result, left, LeaveCC, eq); __ b(eq, &done); __ cmp(right, Operand(2)); __ tst(left, Operand(1), eq); __ mov(result, Operand(left, ASR, 1), LeaveCC, eq); __ b(eq, &done); __ cmp(right, Operand(4)); __ tst(left, Operand(3), eq); __ mov(result, Operand(left, ASR, 2), LeaveCC, eq); __ b(eq, &done); // Call the stub. The numbers in r0 and r1 have // to be tagged to Smis. If that is not possible, deoptimize. DeferredDivI* deferred = new(zone()) DeferredDivI(this, instr); __ TrySmiTag(left, &deoptimize, scratch); __ TrySmiTag(right, &deoptimize, scratch); __ b(al, deferred->entry()); __ bind(deferred->exit()); // If the result in r0 is a Smi, untag it, else deoptimize. __ JumpIfNotSmi(result, &deoptimize); __ SmiUntag(result); __ b(&done); __ bind(&deoptimize); DeoptimizeIf(al, instr->environment()); __ bind(&done); } void LCodeGen::DoMultiplyAddD(LMultiplyAddD* instr) { DwVfpRegister addend = ToDoubleRegister(instr->addend()); DwVfpRegister multiplier = ToDoubleRegister(instr->multiplier()); DwVfpRegister multiplicand = ToDoubleRegister(instr->multiplicand()); // This is computed in-place. ASSERT(addend.is(ToDoubleRegister(instr->result()))); __ vmla(addend, multiplier, multiplicand); } void LCodeGen::DoMultiplySubD(LMultiplySubD* instr) { DwVfpRegister minuend = ToDoubleRegister(instr->minuend()); DwVfpRegister multiplier = ToDoubleRegister(instr->multiplier()); DwVfpRegister multiplicand = ToDoubleRegister(instr->multiplicand()); // This is computed in-place. ASSERT(minuend.is(ToDoubleRegister(instr->result()))); __ vmls(minuend, multiplier, multiplicand); } void LCodeGen::DoMathFloorOfDiv(LMathFloorOfDiv* instr) { const Register result = ToRegister(instr->result()); const Register left = ToRegister(instr->left()); const Register remainder = ToRegister(instr->temp()); const Register scratch = scratch0(); if (!CpuFeatures::IsSupported(SUDIV)) { // If the CPU doesn't support sdiv instruction, we only optimize when we // have magic numbers for the divisor. The standard integer division routine // is usually slower than transitionning to VFP. ASSERT(instr->right()->IsConstantOperand()); int32_t divisor = ToInteger32(LConstantOperand::cast(instr->right())); ASSERT(LChunkBuilder::HasMagicNumberForDivisor(divisor)); if (divisor < 0) { __ cmp(left, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); } EmitSignedIntegerDivisionByConstant(result, left, divisor, remainder, scratch, instr->environment()); // We performed a truncating division. Correct the result if necessary. __ cmp(remainder, Operand::Zero()); __ teq(remainder, Operand(divisor), ne); __ sub(result, result, Operand(1), LeaveCC, mi); } else { CpuFeatureScope scope(masm(), SUDIV); const Register right = ToRegister(instr->right()); // Check for x / 0. __ cmp(right, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); // Check for (kMinInt / -1). if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmp(left, Operand(kMinInt)); __ b(ne, &left_not_min_int); __ cmp(right, Operand(-1)); DeoptimizeIf(eq, instr->environment()); __ bind(&left_not_min_int); } // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ cmp(right, Operand::Zero()); __ cmp(left, Operand::Zero(), mi); // "right" can't be null because the code would have already been // deoptimized. The Z flag is set only if (right < 0) and (left == 0). // In this case we need to deoptimize to produce a -0. DeoptimizeIf(eq, instr->environment()); } Label done; __ sdiv(result, left, right); // If both operands have the same sign then we are done. __ eor(remainder, left, Operand(right), SetCC); __ b(pl, &done); // Check if the result needs to be corrected. __ mls(remainder, result, right, left); __ cmp(remainder, Operand::Zero()); __ sub(result, result, Operand(1), LeaveCC, ne); __ bind(&done); } } void LCodeGen::DoDeferredBinaryOpStub(LPointerMap* pointer_map, LOperand* left_argument, LOperand* right_argument, Token::Value op) { Register left = ToRegister(left_argument); Register right = ToRegister(right_argument); PushSafepointRegistersScope scope(this, Safepoint::kWithRegistersAndDoubles); // Move left to r1 and right to r0 for the stub call. if (left.is(r1)) { __ Move(r0, right); } else if (left.is(r0) && right.is(r1)) { __ Swap(r0, r1, r2); } else if (left.is(r0)) { ASSERT(!right.is(r1)); __ mov(r1, r0); __ mov(r0, right); } else { ASSERT(!left.is(r0) && !right.is(r0)); __ mov(r0, right); __ mov(r1, left); } BinaryOpStub stub(op, OVERWRITE_LEFT); __ CallStub(&stub); RecordSafepointWithRegistersAndDoubles(pointer_map, 0, Safepoint::kNoLazyDeopt); // Overwrite the stored value of r0 with the result of the stub. __ StoreToSafepointRegistersAndDoublesSlot(r0, r0); } void LCodeGen::DoMulI(LMulI* instr) { Register scratch = scratch0(); Register result = ToRegister(instr->result()); // Note that result may alias left. Register left = ToRegister(instr->left()); LOperand* right_op = instr->right(); bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); bool bailout_on_minus_zero = instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero); if (right_op->IsConstantOperand() && !can_overflow) { // Use optimized code for specific constants. int32_t constant = ToInteger32(LConstantOperand::cast(right_op)); if (bailout_on_minus_zero && (constant < 0)) { // The case of a null constant will be handled separately. // If constant is negative and left is null, the result should be -0. __ cmp(left, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); } switch (constant) { case -1: __ rsb(result, left, Operand::Zero()); break; case 0: if (bailout_on_minus_zero) { // If left is strictly negative and the constant is null, the // result is -0. Deoptimize if required, otherwise return 0. __ cmp(left, Operand::Zero()); DeoptimizeIf(mi, instr->environment()); } __ mov(result, Operand::Zero()); break; case 1: __ Move(result, left); break; default: // Multiplying by powers of two and powers of two plus or minus // one can be done faster with shifted operands. // For other constants we emit standard code. int32_t mask = constant >> 31; uint32_t constant_abs = (constant + mask) ^ mask; if (IsPowerOf2(constant_abs) || IsPowerOf2(constant_abs - 1) || IsPowerOf2(constant_abs + 1)) { if (IsPowerOf2(constant_abs)) { int32_t shift = WhichPowerOf2(constant_abs); __ mov(result, Operand(left, LSL, shift)); } else if (IsPowerOf2(constant_abs - 1)) { int32_t shift = WhichPowerOf2(constant_abs - 1); __ add(result, left, Operand(left, LSL, shift)); } else if (IsPowerOf2(constant_abs + 1)) { int32_t shift = WhichPowerOf2(constant_abs + 1); __ rsb(result, left, Operand(left, LSL, shift)); } // Correct the sign of the result is the constant is negative. if (constant < 0) __ rsb(result, result, Operand::Zero()); } else { // Generate standard code. __ mov(ip, Operand(constant)); __ mul(result, left, ip); } } } else { Register right = EmitLoadRegister(right_op, scratch); if (bailout_on_minus_zero) { __ orr(ToRegister(instr->temp()), left, right); } if (can_overflow) { // scratch:result = left * right. __ smull(result, scratch, left, right); __ cmp(scratch, Operand(result, ASR, 31)); DeoptimizeIf(ne, instr->environment()); } else { __ mul(result, left, right); } if (bailout_on_minus_zero) { // Bail out if the result is supposed to be negative zero. Label done; __ cmp(result, Operand::Zero()); __ b(ne, &done); __ cmp(ToRegister(instr->temp()), Operand::Zero()); DeoptimizeIf(mi, instr->environment()); __ bind(&done); } } } void LCodeGen::DoBitI(LBitI* instr) { LOperand* left_op = instr->left(); LOperand* right_op = instr->right(); ASSERT(left_op->IsRegister()); Register left = ToRegister(left_op); Register result = ToRegister(instr->result()); Operand right(no_reg); if (right_op->IsStackSlot() || right_op->IsArgument()) { right = Operand(EmitLoadRegister(right_op, ip)); } else { ASSERT(right_op->IsRegister() || right_op->IsConstantOperand()); right = ToOperand(right_op); } switch (instr->op()) { case Token::BIT_AND: __ and_(result, left, right); break; case Token::BIT_OR: __ orr(result, left, right); break; case Token::BIT_XOR: __ eor(result, left, right); break; default: UNREACHABLE(); break; } } void LCodeGen::DoShiftI(LShiftI* instr) { // Both 'left' and 'right' are "used at start" (see LCodeGen::DoShift), so // result may alias either of them. LOperand* right_op = instr->right(); Register left = ToRegister(instr->left()); Register result = ToRegister(instr->result()); Register scratch = scratch0(); if (right_op->IsRegister()) { // Mask the right_op operand. __ and_(scratch, ToRegister(right_op), Operand(0x1F)); switch (instr->op()) { case Token::ROR: __ mov(result, Operand(left, ROR, scratch)); break; case Token::SAR: __ mov(result, Operand(left, ASR, scratch)); break; case Token::SHR: if (instr->can_deopt()) { __ mov(result, Operand(left, LSR, scratch), SetCC); DeoptimizeIf(mi, instr->environment()); } else { __ mov(result, Operand(left, LSR, scratch)); } break; case Token::SHL: __ mov(result, Operand(left, LSL, scratch)); break; default: UNREACHABLE(); break; } } else { // Mask the right_op operand. int value = ToInteger32(LConstantOperand::cast(right_op)); uint8_t shift_count = static_cast<uint8_t>(value & 0x1F); switch (instr->op()) { case Token::ROR: if (shift_count != 0) { __ mov(result, Operand(left, ROR, shift_count)); } else { __ Move(result, left); } break; case Token::SAR: if (shift_count != 0) { __ mov(result, Operand(left, ASR, shift_count)); } else { __ Move(result, left); } break; case Token::SHR: if (shift_count != 0) { __ mov(result, Operand(left, LSR, shift_count)); } else { if (instr->can_deopt()) { __ tst(left, Operand(0x80000000)); DeoptimizeIf(ne, instr->environment()); } __ Move(result, left); } break; case Token::SHL: if (shift_count != 0) { __ mov(result, Operand(left, LSL, shift_count)); } else { __ Move(result, left); } break; default: UNREACHABLE(); break; } } } void LCodeGen::DoSubI(LSubI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); LOperand* result = instr->result(); bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); SBit set_cond = can_overflow ? SetCC : LeaveCC; if (right->IsStackSlot() || right->IsArgument()) { Register right_reg = EmitLoadRegister(right, ip); __ sub(ToRegister(result), ToRegister(left), Operand(right_reg), set_cond); } else { ASSERT(right->IsRegister() || right->IsConstantOperand()); __ sub(ToRegister(result), ToRegister(left), ToOperand(right), set_cond); } if (can_overflow) { DeoptimizeIf(vs, instr->environment()); } } void LCodeGen::DoRSubI(LRSubI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); LOperand* result = instr->result(); bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); SBit set_cond = can_overflow ? SetCC : LeaveCC; if (right->IsStackSlot() || right->IsArgument()) { Register right_reg = EmitLoadRegister(right, ip); __ rsb(ToRegister(result), ToRegister(left), Operand(right_reg), set_cond); } else { ASSERT(right->IsRegister() || right->IsConstantOperand()); __ rsb(ToRegister(result), ToRegister(left), ToOperand(right), set_cond); } if (can_overflow) { DeoptimizeIf(vs, instr->environment()); } } void LCodeGen::DoConstantI(LConstantI* instr) { ASSERT(instr->result()->IsRegister()); __ mov(ToRegister(instr->result()), Operand(instr->value())); } void LCodeGen::DoConstantD(LConstantD* instr) { ASSERT(instr->result()->IsDoubleRegister()); DwVfpRegister result = ToDoubleRegister(instr->result()); double v = instr->value(); __ Vmov(result, v, scratch0()); } void LCodeGen::DoConstantT(LConstantT* instr) { Handle<Object> value = instr->value(); ALLOW_HANDLE_DEREF(isolate(), "smi check"); if (value->IsSmi()) { __ mov(ToRegister(instr->result()), Operand(value)); } else { __ LoadHeapObject(ToRegister(instr->result()), Handle<HeapObject>::cast(value)); } } void LCodeGen::DoFixedArrayBaseLength(LFixedArrayBaseLength* instr) { Register result = ToRegister(instr->result()); Register array = ToRegister(instr->value()); __ ldr(result, FieldMemOperand(array, FixedArrayBase::kLengthOffset)); } void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) { Register result = ToRegister(instr->result()); Register map = ToRegister(instr->value()); __ EnumLength(result, map); } void LCodeGen::DoElementsKind(LElementsKind* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->value()); // Load map into |result|. __ ldr(result, FieldMemOperand(input, HeapObject::kMapOffset)); // Load the map's "bit field 2" into |result|. We only need the first byte, // but the following bit field extraction takes care of that anyway. __ ldr(result, FieldMemOperand(result, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ ubfx(result, result, Map::kElementsKindShift, Map::kElementsKindBitCount); } void LCodeGen::DoValueOf(LValueOf* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); Register map = ToRegister(instr->temp()); Label done; // If the object is a smi return the object. __ tst(input, Operand(kSmiTagMask)); __ Move(result, input, eq); __ b(eq, &done); // If the object is not a value type, return the object. __ CompareObjectType(input, map, map, JS_VALUE_TYPE); __ Move(result, input, ne); __ b(ne, &done); __ ldr(result, FieldMemOperand(input, JSValue::kValueOffset)); __ bind(&done); } void LCodeGen::DoDateField(LDateField* instr) { Register object = ToRegister(instr->date()); Register result = ToRegister(instr->result()); Register scratch = ToRegister(instr->temp()); Smi* index = instr->index(); Label runtime, done; ASSERT(object.is(result)); ASSERT(object.is(r0)); ASSERT(!scratch.is(scratch0())); ASSERT(!scratch.is(object)); __ tst(object, Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); __ CompareObjectType(object, scratch, scratch, JS_DATE_TYPE); DeoptimizeIf(ne, instr->environment()); if (index->value() == 0) { __ ldr(result, FieldMemOperand(object, JSDate::kValueOffset)); } else { if (index->value() < JSDate::kFirstUncachedField) { ExternalReference stamp = ExternalReference::date_cache_stamp(isolate()); __ mov(scratch, Operand(stamp)); __ ldr(scratch, MemOperand(scratch)); __ ldr(scratch0(), FieldMemOperand(object, JSDate::kCacheStampOffset)); __ cmp(scratch, scratch0()); __ b(ne, &runtime); __ ldr(result, FieldMemOperand(object, JSDate::kValueOffset + kPointerSize * index->value())); __ jmp(&done); } __ bind(&runtime); __ PrepareCallCFunction(2, scratch); __ mov(r1, Operand(index)); __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2); __ bind(&done); } } void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) { SeqStringSetCharGenerator::Generate(masm(), instr->encoding(), ToRegister(instr->string()), ToRegister(instr->index()), ToRegister(instr->value())); } void LCodeGen::DoBitNotI(LBitNotI* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); __ mvn(result, Operand(input)); } void LCodeGen::DoThrow(LThrow* instr) { Register input_reg = EmitLoadRegister(instr->value(), ip); __ push(input_reg); CallRuntime(Runtime::kThrow, 1, instr); if (FLAG_debug_code) { __ stop("Unreachable code."); } } void LCodeGen::DoAddI(LAddI* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); LOperand* result = instr->result(); bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); SBit set_cond = can_overflow ? SetCC : LeaveCC; if (right->IsStackSlot() || right->IsArgument()) { Register right_reg = EmitLoadRegister(right, ip); __ add(ToRegister(result), ToRegister(left), Operand(right_reg), set_cond); } else { ASSERT(right->IsRegister() || right->IsConstantOperand()); __ add(ToRegister(result), ToRegister(left), ToOperand(right), set_cond); } if (can_overflow) { DeoptimizeIf(vs, instr->environment()); } } void LCodeGen::DoMathMinMax(LMathMinMax* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); HMathMinMax::Operation operation = instr->hydrogen()->operation(); if (instr->hydrogen()->representation().IsInteger32()) { Condition condition = (operation == HMathMinMax::kMathMin) ? le : ge; Register left_reg = ToRegister(left); Operand right_op = (right->IsRegister() || right->IsConstantOperand()) ? ToOperand(right) : Operand(EmitLoadRegister(right, ip)); Register result_reg = ToRegister(instr->result()); __ cmp(left_reg, right_op); __ Move(result_reg, left_reg, condition); __ mov(result_reg, right_op, LeaveCC, NegateCondition(condition)); } else { ASSERT(instr->hydrogen()->representation().IsDouble()); DwVfpRegister left_reg = ToDoubleRegister(left); DwVfpRegister right_reg = ToDoubleRegister(right); DwVfpRegister result_reg = ToDoubleRegister(instr->result()); Label result_is_nan, return_left, return_right, check_zero, done; __ VFPCompareAndSetFlags(left_reg, right_reg); if (operation == HMathMinMax::kMathMin) { __ b(mi, &return_left); __ b(gt, &return_right); } else { __ b(mi, &return_right); __ b(gt, &return_left); } __ b(vs, &result_is_nan); // Left equals right => check for -0. __ VFPCompareAndSetFlags(left_reg, 0.0); if (left_reg.is(result_reg) || right_reg.is(result_reg)) { __ b(ne, &done); // left == right != 0. } else { __ b(ne, &return_left); // left == right != 0. } // At this point, both left and right are either 0 or -0. if (operation == HMathMinMax::kMathMin) { // We could use a single 'vorr' instruction here if we had NEON support. __ vneg(left_reg, left_reg); __ vsub(result_reg, left_reg, right_reg); __ vneg(result_reg, result_reg); } else { // Since we operate on +0 and/or -0, vadd and vand have the same effect; // the decision for vadd is easy because vand is a NEON instruction. __ vadd(result_reg, left_reg, right_reg); } __ b(&done); __ bind(&result_is_nan); __ vadd(result_reg, left_reg, right_reg); __ b(&done); __ bind(&return_right); __ Move(result_reg, right_reg); if (!left_reg.is(result_reg)) { __ b(&done); } __ bind(&return_left); __ Move(result_reg, left_reg); __ bind(&done); } } void LCodeGen::DoArithmeticD(LArithmeticD* instr) { DwVfpRegister left = ToDoubleRegister(instr->left()); DwVfpRegister right = ToDoubleRegister(instr->right()); DwVfpRegister result = ToDoubleRegister(instr->result()); switch (instr->op()) { case Token::ADD: __ vadd(result, left, right); break; case Token::SUB: __ vsub(result, left, right); break; case Token::MUL: __ vmul(result, left, right); break; case Token::DIV: __ vdiv(result, left, right); break; case Token::MOD: { // Save r0-r3 on the stack. __ stm(db_w, sp, r0.bit() | r1.bit() | r2.bit() | r3.bit()); __ PrepareCallCFunction(0, 2, scratch0()); __ SetCallCDoubleArguments(left, right); __ CallCFunction( ExternalReference::double_fp_operation(Token::MOD, isolate()), 0, 2); // Move the result in the double result register. __ GetCFunctionDoubleResult(result); // Restore r0-r3. __ ldm(ia_w, sp, r0.bit() | r1.bit() | r2.bit() | r3.bit()); break; } default: UNREACHABLE(); break; } } void LCodeGen::DoArithmeticT(LArithmeticT* instr) { ASSERT(ToRegister(instr->left()).is(r1)); ASSERT(ToRegister(instr->right()).is(r0)); ASSERT(ToRegister(instr->result()).is(r0)); BinaryOpStub stub(instr->op(), NO_OVERWRITE); // Block literal pool emission to ensure nop indicating no inlined smi code // is in the correct position. Assembler::BlockConstPoolScope block_const_pool(masm()); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); __ nop(); // Signals no inlined code. } int LCodeGen::GetNextEmittedBlock() const { for (int i = current_block_ + 1; i < graph()->blocks()->length(); ++i) { if (!chunk_->GetLabel(i)->HasReplacement()) return i; } return -1; } void LCodeGen::EmitBranch(int left_block, int right_block, Condition cc) { int next_block = GetNextEmittedBlock(); right_block = chunk_->LookupDestination(right_block); left_block = chunk_->LookupDestination(left_block); if (right_block == left_block) { EmitGoto(left_block); } else if (left_block == next_block) { __ b(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block)); } else if (right_block == next_block) { __ b(cc, chunk_->GetAssemblyLabel(left_block)); } else { __ b(cc, chunk_->GetAssemblyLabel(left_block)); __ b(chunk_->GetAssemblyLabel(right_block)); } } void LCodeGen::DoBranch(LBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Representation r = instr->hydrogen()->value()->representation(); if (r.IsInteger32()) { Register reg = ToRegister(instr->value()); __ cmp(reg, Operand::Zero()); EmitBranch(true_block, false_block, ne); } else if (r.IsDouble()) { DwVfpRegister reg = ToDoubleRegister(instr->value()); // Test the double value. Zero and NaN are false. __ VFPCompareAndSetFlags(reg, 0.0); __ cmp(r0, r0, vs); // If NaN, set the Z flag. EmitBranch(true_block, false_block, ne); } else { ASSERT(r.IsTagged()); Register reg = ToRegister(instr->value()); HType type = instr->hydrogen()->value()->type(); if (type.IsBoolean()) { __ CompareRoot(reg, Heap::kTrueValueRootIndex); EmitBranch(true_block, false_block, eq); } else if (type.IsSmi()) { __ cmp(reg, Operand::Zero()); EmitBranch(true_block, false_block, ne); } else { Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types(); // Avoid deopts in the case where we've never executed this path before. if (expected.IsEmpty()) expected = ToBooleanStub::all_types(); if (expected.Contains(ToBooleanStub::UNDEFINED)) { // undefined -> false. __ CompareRoot(reg, Heap::kUndefinedValueRootIndex); __ b(eq, false_label); } if (expected.Contains(ToBooleanStub::BOOLEAN)) { // Boolean -> its value. __ CompareRoot(reg, Heap::kTrueValueRootIndex); __ b(eq, true_label); __ CompareRoot(reg, Heap::kFalseValueRootIndex); __ b(eq, false_label); } if (expected.Contains(ToBooleanStub::NULL_TYPE)) { // 'null' -> false. __ CompareRoot(reg, Heap::kNullValueRootIndex); __ b(eq, false_label); } if (expected.Contains(ToBooleanStub::SMI)) { // Smis: 0 -> false, all other -> true. __ cmp(reg, Operand::Zero()); __ b(eq, false_label); __ JumpIfSmi(reg, true_label); } else if (expected.NeedsMap()) { // If we need a map later and have a Smi -> deopt. __ tst(reg, Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); } const Register map = scratch0(); if (expected.NeedsMap()) { __ ldr(map, FieldMemOperand(reg, HeapObject::kMapOffset)); if (expected.CanBeUndetectable()) { // Undetectable -> false. __ ldrb(ip, FieldMemOperand(map, Map::kBitFieldOffset)); __ tst(ip, Operand(1 << Map::kIsUndetectable)); __ b(ne, false_label); } } if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) { // spec object -> true. __ CompareInstanceType(map, ip, FIRST_SPEC_OBJECT_TYPE); __ b(ge, true_label); } if (expected.Contains(ToBooleanStub::STRING)) { // String value -> false iff empty. Label not_string; __ CompareInstanceType(map, ip, FIRST_NONSTRING_TYPE); __ b(ge, &not_string); __ ldr(ip, FieldMemOperand(reg, String::kLengthOffset)); __ cmp(ip, Operand::Zero()); __ b(ne, true_label); __ b(false_label); __ bind(&not_string); } if (expected.Contains(ToBooleanStub::SYMBOL)) { // Symbol value -> true. __ CompareInstanceType(map, ip, SYMBOL_TYPE); __ b(eq, true_label); } if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) { // heap number -> false iff +0, -0, or NaN. DwVfpRegister dbl_scratch = double_scratch0(); Label not_heap_number; __ CompareRoot(map, Heap::kHeapNumberMapRootIndex); __ b(ne, &not_heap_number); __ vldr(dbl_scratch, FieldMemOperand(reg, HeapNumber::kValueOffset)); __ VFPCompareAndSetFlags(dbl_scratch, 0.0); __ cmp(r0, r0, vs); // NaN -> false. __ b(eq, false_label); // +0, -0 -> false. __ b(true_label); __ bind(&not_heap_number); } // We've seen something for the first time -> deopt. DeoptimizeIf(al, instr->environment()); } } } void LCodeGen::EmitGoto(int block) { if (!IsNextEmittedBlock(block)) { __ jmp(chunk_->GetAssemblyLabel(chunk_->LookupDestination(block))); } } void LCodeGen::DoGoto(LGoto* instr) { EmitGoto(instr->block_id()); } Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) { Condition cond = kNoCondition; switch (op) { case Token::EQ: case Token::EQ_STRICT: cond = eq; break; case Token::LT: cond = is_unsigned ? lo : lt; break; case Token::GT: cond = is_unsigned ? hi : gt; break; case Token::LTE: cond = is_unsigned ? ls : le; break; case Token::GTE: cond = is_unsigned ? hs : ge; break; case Token::IN: case Token::INSTANCEOF: default: UNREACHABLE(); } return cond; } void LCodeGen::DoCmpIDAndBranch(LCmpIDAndBranch* instr) { LOperand* left = instr->left(); LOperand* right = instr->right(); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); Condition cond = TokenToCondition(instr->op(), false); if (left->IsConstantOperand() && right->IsConstantOperand()) { // We can statically evaluate the comparison. double left_val = ToDouble(LConstantOperand::cast(left)); double right_val = ToDouble(LConstantOperand::cast(right)); int next_block = EvalComparison(instr->op(), left_val, right_val) ? true_block : false_block; EmitGoto(next_block); } else { if (instr->is_double()) { // Compare left and right operands as doubles and load the // resulting flags into the normal status register. __ VFPCompareAndSetFlags(ToDoubleRegister(left), ToDoubleRegister(right)); // If a NaN is involved, i.e. the result is unordered (V set), // jump to false block label. __ b(vs, chunk_->GetAssemblyLabel(false_block)); } else { if (right->IsConstantOperand()) { __ cmp(ToRegister(left), Operand(ToInteger32(LConstantOperand::cast(right)))); } else if (left->IsConstantOperand()) { __ cmp(ToRegister(right), Operand(ToInteger32(LConstantOperand::cast(left)))); // We transposed the operands. Reverse the condition. cond = ReverseCondition(cond); } else { __ cmp(ToRegister(left), ToRegister(right)); } } EmitBranch(true_block, false_block, cond); } } void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) { Register left = ToRegister(instr->left()); Register right = ToRegister(instr->right()); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); __ cmp(left, Operand(right)); EmitBranch(true_block, false_block, eq); } void LCodeGen::DoCmpConstantEqAndBranch(LCmpConstantEqAndBranch* instr) { Register left = ToRegister(instr->left()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ cmp(left, Operand(instr->hydrogen()->right())); EmitBranch(true_block, false_block, eq); } void LCodeGen::DoIsNilAndBranch(LIsNilAndBranch* instr) { Register scratch = scratch0(); Register reg = ToRegister(instr->value()); int false_block = chunk_->LookupDestination(instr->false_block_id()); // If the expression is known to be untagged or a smi, then it's definitely // not null, and it can't be a an undetectable object. if (instr->hydrogen()->representation().IsSpecialization() || instr->hydrogen()->type().IsSmi()) { EmitGoto(false_block); return; } int true_block = chunk_->LookupDestination(instr->true_block_id()); Heap::RootListIndex nil_value = instr->nil() == kNullValue ? Heap::kNullValueRootIndex : Heap::kUndefinedValueRootIndex; __ LoadRoot(ip, nil_value); __ cmp(reg, ip); if (instr->kind() == kStrictEquality) { EmitBranch(true_block, false_block, eq); } else { Heap::RootListIndex other_nil_value = instr->nil() == kNullValue ? Heap::kUndefinedValueRootIndex : Heap::kNullValueRootIndex; Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ b(eq, true_label); __ LoadRoot(ip, other_nil_value); __ cmp(reg, ip); __ b(eq, true_label); __ JumpIfSmi(reg, false_label); // Check for undetectable objects by looking in the bit field in // the map. The object has already been smi checked. __ ldr(scratch, FieldMemOperand(reg, HeapObject::kMapOffset)); __ ldrb(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset)); __ tst(scratch, Operand(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, ne); } } Condition LCodeGen::EmitIsObject(Register input, Register temp1, Label* is_not_object, Label* is_object) { Register temp2 = scratch0(); __ JumpIfSmi(input, is_not_object); __ LoadRoot(temp2, Heap::kNullValueRootIndex); __ cmp(input, temp2); __ b(eq, is_object); // Load map. __ ldr(temp1, FieldMemOperand(input, HeapObject::kMapOffset)); // Undetectable objects behave like undefined. __ ldrb(temp2, FieldMemOperand(temp1, Map::kBitFieldOffset)); __ tst(temp2, Operand(1 << Map::kIsUndetectable)); __ b(ne, is_not_object); // Load instance type and check that it is in object type range. __ ldrb(temp2, FieldMemOperand(temp1, Map::kInstanceTypeOffset)); __ cmp(temp2, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ b(lt, is_not_object); __ cmp(temp2, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE)); return le; } void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) { Register reg = ToRegister(instr->value()); Register temp1 = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsObject(reg, temp1, false_label, true_label); EmitBranch(true_block, false_block, true_cond); } Condition LCodeGen::EmitIsString(Register input, Register temp1, Label* is_not_string) { __ JumpIfSmi(input, is_not_string); __ CompareObjectType(input, temp1, temp1, FIRST_NONSTRING_TYPE); return lt; } void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) { Register reg = ToRegister(instr->value()); Register temp1 = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsString(reg, temp1, false_label); EmitBranch(true_block, false_block, true_cond); } void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Register input_reg = EmitLoadRegister(instr->value(), ip); __ tst(input_reg, Operand(kSmiTagMask)); EmitBranch(true_block, false_block, eq); } void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) { Register input = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ JumpIfSmi(input, chunk_->GetAssemblyLabel(false_block)); __ ldr(temp, FieldMemOperand(input, HeapObject::kMapOffset)); __ ldrb(temp, FieldMemOperand(temp, Map::kBitFieldOffset)); __ tst(temp, Operand(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, ne); } static Condition ComputeCompareCondition(Token::Value op) { switch (op) { case Token::EQ_STRICT: case Token::EQ: return eq; case Token::LT: return lt; case Token::GT: return gt; case Token::LTE: return le; case Token::GTE: return ge; default: UNREACHABLE(); return kNoCondition; } } void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) { Token::Value op = instr->op(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op); CallCode(ic, RelocInfo::CODE_TARGET, instr); // This instruction also signals no smi code inlined. __ cmp(r0, Operand::Zero()); Condition condition = ComputeCompareCondition(op); EmitBranch(true_block, false_block, condition); } static InstanceType TestType(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == FIRST_TYPE) return to; ASSERT(from == to || to == LAST_TYPE); return from; } static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == to) return eq; if (to == LAST_TYPE) return hs; if (from == FIRST_TYPE) return ls; UNREACHABLE(); return eq; } void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) { Register scratch = scratch0(); Register input = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ JumpIfSmi(input, false_label); __ CompareObjectType(input, scratch, scratch, TestType(instr->hydrogen())); EmitBranch(true_block, false_block, BranchCondition(instr->hydrogen())); } void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); __ AssertString(input); __ ldr(result, FieldMemOperand(input, String::kHashFieldOffset)); __ IndexFromHash(result, result); } void LCodeGen::DoHasCachedArrayIndexAndBranch( LHasCachedArrayIndexAndBranch* instr) { Register input = ToRegister(instr->value()); Register scratch = scratch0(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ ldr(scratch, FieldMemOperand(input, String::kHashFieldOffset)); __ tst(scratch, Operand(String::kContainsCachedArrayIndexMask)); EmitBranch(true_block, false_block, eq); } // Branches to a label or falls through with the answer in flags. Trashes // the temp registers, but not the input. void LCodeGen::EmitClassOfTest(Label* is_true, Label* is_false, Handle<String>class_name, Register input, Register temp, Register temp2) { ASSERT(!input.is(temp)); ASSERT(!input.is(temp2)); ASSERT(!temp.is(temp2)); __ JumpIfSmi(input, is_false); if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Function"))) { // Assuming the following assertions, we can use the same compares to test // for both being a function type and being in the object type range. STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE == FIRST_SPEC_OBJECT_TYPE + 1); STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_SPEC_OBJECT_TYPE - 1); STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ CompareObjectType(input, temp, temp2, FIRST_SPEC_OBJECT_TYPE); __ b(lt, is_false); __ b(eq, is_true); __ cmp(temp2, Operand(LAST_SPEC_OBJECT_TYPE)); __ b(eq, is_true); } else { // Faster code path to avoid two compares: subtract lower bound from the // actual type and do a signed compare with the width of the type range. __ ldr(temp, FieldMemOperand(input, HeapObject::kMapOffset)); __ ldrb(temp2, FieldMemOperand(temp, Map::kInstanceTypeOffset)); __ sub(temp2, temp2, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ cmp(temp2, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE - FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ b(gt, is_false); } // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range. // Check if the constructor in the map is a function. __ ldr(temp, FieldMemOperand(temp, Map::kConstructorOffset)); // Objects with a non-function constructor have class 'Object'. __ CompareObjectType(temp, temp2, temp2, JS_FUNCTION_TYPE); if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Object"))) { __ b(ne, is_true); } else { __ b(ne, is_false); } // temp now contains the constructor function. Grab the // instance class name from there. __ ldr(temp, FieldMemOperand(temp, JSFunction::kSharedFunctionInfoOffset)); __ ldr(temp, FieldMemOperand(temp, SharedFunctionInfo::kInstanceClassNameOffset)); // The class name we are testing against is internalized since it's a literal. // The name in the constructor is internalized because of the way the context // is booted. This routine isn't expected to work for random API-created // classes and it doesn't have to because you can't access it with natives // syntax. Since both sides are internalized it is sufficient to use an // identity comparison. __ cmp(temp, Operand(class_name)); // End with the answer in flags. } void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) { Register input = ToRegister(instr->value()); Register temp = scratch0(); Register temp2 = ToRegister(instr->temp()); Handle<String> class_name = instr->hydrogen()->class_name(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); EmitClassOfTest(true_label, false_label, class_name, input, temp, temp2); EmitBranch(true_block, false_block, eq); } void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) { Register reg = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); int true_block = instr->true_block_id(); int false_block = instr->false_block_id(); __ ldr(temp, FieldMemOperand(reg, HeapObject::kMapOffset)); __ cmp(temp, Operand(instr->map())); EmitBranch(true_block, false_block, eq); } void LCodeGen::DoInstanceOf(LInstanceOf* instr) { ASSERT(ToRegister(instr->left()).is(r0)); // Object is in r0. ASSERT(ToRegister(instr->right()).is(r1)); // Function is in r1. InstanceofStub stub(InstanceofStub::kArgsInRegisters); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); __ cmp(r0, Operand::Zero()); __ mov(r0, Operand(factory()->false_value()), LeaveCC, ne); __ mov(r0, Operand(factory()->true_value()), LeaveCC, eq); } void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) { class DeferredInstanceOfKnownGlobal: public LDeferredCode { public: DeferredInstanceOfKnownGlobal(LCodeGen* codegen, LInstanceOfKnownGlobal* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_); } virtual LInstruction* instr() { return instr_; } Label* map_check() { return &map_check_; } private: LInstanceOfKnownGlobal* instr_; Label map_check_; }; DeferredInstanceOfKnownGlobal* deferred; deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr); Label done, false_result; Register object = ToRegister(instr->value()); Register temp = ToRegister(instr->temp()); Register result = ToRegister(instr->result()); ASSERT(object.is(r0)); ASSERT(result.is(r0)); // A Smi is not instance of anything. __ JumpIfSmi(object, &false_result); // This is the inlined call site instanceof cache. The two occurences of the // hole value will be patched to the last map/result pair generated by the // instanceof stub. Label cache_miss; Register map = temp; __ ldr(map, FieldMemOperand(object, HeapObject::kMapOffset)); { // Block constant pool emission to ensure the positions of instructions are // as expected by the patcher. See InstanceofStub::Generate(). Assembler::BlockConstPoolScope block_const_pool(masm()); __ bind(deferred->map_check()); // Label for calculating code patching. // We use Factory::the_hole_value() on purpose instead of loading from the // root array to force relocation to be able to later patch with // the cached map. PredictableCodeSizeScope predictable(masm_, 5 * Assembler::kInstrSize); Handle<JSGlobalPropertyCell> cell = factory()->NewJSGlobalPropertyCell(factory()->the_hole_value()); __ mov(ip, Operand(Handle<Object>(cell))); __ ldr(ip, FieldMemOperand(ip, JSGlobalPropertyCell::kValueOffset)); __ cmp(map, Operand(ip)); __ b(ne, &cache_miss); // We use Factory::the_hole_value() on purpose instead of loading from the // root array to force relocation to be able to later patch // with true or false. __ mov(result, Operand(factory()->the_hole_value())); } __ b(&done); // The inlined call site cache did not match. Check null and string before // calling the deferred code. __ bind(&cache_miss); // Null is not instance of anything. __ LoadRoot(ip, Heap::kNullValueRootIndex); __ cmp(object, Operand(ip)); __ b(eq, &false_result); // String values is not instance of anything. Condition is_string = masm_->IsObjectStringType(object, temp); __ b(is_string, &false_result); // Go to the deferred code. __ b(deferred->entry()); __ bind(&false_result); __ LoadRoot(result, Heap::kFalseValueRootIndex); // Here result has either true or false. Deferred code also produces true or // false object. __ bind(deferred->exit()); __ bind(&done); } void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr, Label* map_check) { Register result = ToRegister(instr->result()); ASSERT(result.is(r0)); InstanceofStub::Flags flags = InstanceofStub::kNoFlags; flags = static_cast<InstanceofStub::Flags>( flags | InstanceofStub::kArgsInRegisters); flags = static_cast<InstanceofStub::Flags>( flags | InstanceofStub::kCallSiteInlineCheck); flags = static_cast<InstanceofStub::Flags>( flags | InstanceofStub::kReturnTrueFalseObject); InstanceofStub stub(flags); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); // Get the temp register reserved by the instruction. This needs to be r4 as // its slot of the pushing of safepoint registers is used to communicate the // offset to the location of the map check. Register temp = ToRegister(instr->temp()); ASSERT(temp.is(r4)); __ LoadHeapObject(InstanceofStub::right(), instr->function()); static const int kAdditionalDelta = 5; // Make sure that code size is predicable, since we use specific constants // offsets in the code to find embedded values.. PredictableCodeSizeScope predictable(masm_, 6 * Assembler::kInstrSize); int delta = masm_->InstructionsGeneratedSince(map_check) + kAdditionalDelta; Label before_push_delta; __ bind(&before_push_delta); __ BlockConstPoolFor(kAdditionalDelta); __ mov(temp, Operand(delta * kPointerSize)); // The mov above can generate one or two instructions. The delta was computed // for two instructions, so we need to pad here in case of one instruction. if (masm_->InstructionsGeneratedSince(&before_push_delta) != 2) { ASSERT_EQ(1, masm_->InstructionsGeneratedSince(&before_push_delta)); __ nop(); } __ StoreToSafepointRegisterSlot(temp, temp); CallCodeGeneric(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS); LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); // Put the result value into the result register slot and // restore all registers. __ StoreToSafepointRegisterSlot(result, result); } void LCodeGen::DoInstanceSize(LInstanceSize* instr) { Register object = ToRegister(instr->object()); Register result = ToRegister(instr->result()); __ ldr(result, FieldMemOperand(object, HeapObject::kMapOffset)); __ ldrb(result, FieldMemOperand(result, Map::kInstanceSizeOffset)); } void LCodeGen::DoCmpT(LCmpT* instr) { Token::Value op = instr->op(); Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op); CallCode(ic, RelocInfo::CODE_TARGET, instr); // This instruction also signals no smi code inlined. __ cmp(r0, Operand::Zero()); Condition condition = ComputeCompareCondition(op); __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex, condition); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex, NegateCondition(condition)); } void LCodeGen::DoReturn(LReturn* instr) { if (FLAG_trace && info()->IsOptimizing()) { // Push the return value on the stack as the parameter. // Runtime::TraceExit returns its parameter in r0. __ push(r0); __ CallRuntime(Runtime::kTraceExit, 1); } if (info()->saves_caller_doubles()) { ASSERT(NeedsEagerFrame()); BitVector* doubles = chunk()->allocated_double_registers(); BitVector::Iterator save_iterator(doubles); int count = 0; while (!save_iterator.Done()) { __ vldr(DwVfpRegister::FromAllocationIndex(save_iterator.Current()), MemOperand(sp, count * kDoubleSize)); save_iterator.Advance(); count++; } } if (NeedsEagerFrame()) { __ mov(sp, fp); __ ldm(ia_w, sp, fp.bit() | lr.bit()); } if (instr->has_constant_parameter_count()) { int parameter_count = ToInteger32(instr->constant_parameter_count()); int32_t sp_delta = (parameter_count + 1) * kPointerSize; if (sp_delta != 0) { __ add(sp, sp, Operand(sp_delta)); } } else { Register reg = ToRegister(instr->parameter_count()); // The argument count parameter is a smi __ SmiUntag(reg); __ add(sp, sp, Operand(reg, LSL, kPointerSizeLog2)); } __ Jump(lr); } void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) { Register result = ToRegister(instr->result()); __ mov(ip, Operand(Handle<Object>(instr->hydrogen()->cell()))); __ ldr(result, FieldMemOperand(ip, JSGlobalPropertyCell::kValueOffset)); if (instr->hydrogen()->RequiresHoleCheck()) { __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(result, ip); DeoptimizeIf(eq, instr->environment()); } } void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(r0)); ASSERT(ToRegister(instr->result()).is(r0)); __ mov(r2, Operand(instr->name())); RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET : RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, mode, instr); } void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) { Register value = ToRegister(instr->value()); Register cell = scratch0(); // Load the cell. __ mov(cell, Operand(instr->hydrogen()->cell())); // If the cell we are storing to contains the hole it could have // been deleted from the property dictionary. In that case, we need // to update the property details in the property dictionary to mark // it as no longer deleted. if (instr->hydrogen()->RequiresHoleCheck()) { // We use a temp to check the payload (CompareRoot might clobber ip). Register payload = ToRegister(instr->temp()); __ ldr(payload, FieldMemOperand(cell, JSGlobalPropertyCell::kValueOffset)); __ CompareRoot(payload, Heap::kTheHoleValueRootIndex); DeoptimizeIf(eq, instr->environment()); } // Store the value. __ str(value, FieldMemOperand(cell, JSGlobalPropertyCell::kValueOffset)); // Cells are always rescanned, so no write barrier here. } void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(r1)); ASSERT(ToRegister(instr->value()).is(r0)); __ mov(r2, Operand(instr->name())); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr); } void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ ldr(result, ContextOperand(context, instr->slot_index())); if (instr->hydrogen()->RequiresHoleCheck()) { __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(result, ip); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(eq, instr->environment()); } else { __ mov(result, Operand(factory()->undefined_value()), LeaveCC, eq); } } } void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) { Register context = ToRegister(instr->context()); Register value = ToRegister(instr->value()); Register scratch = scratch0(); MemOperand target = ContextOperand(context, instr->slot_index()); Label skip_assignment; if (instr->hydrogen()->RequiresHoleCheck()) { __ ldr(scratch, target); __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(scratch, ip); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(eq, instr->environment()); } else { __ b(ne, &skip_assignment); } } __ str(value, target); if (instr->hydrogen()->NeedsWriteBarrier()) { HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; __ RecordWriteContextSlot(context, target.offset(), value, scratch, GetLinkRegisterState(), kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } __ bind(&skip_assignment); } void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) { int offset = instr->hydrogen()->offset(); Register object = ToRegister(instr->object()); if (instr->hydrogen()->representation().IsDouble()) { DwVfpRegister result = ToDoubleRegister(instr->result()); __ vldr(result, FieldMemOperand(object, offset)); return; } Register result = ToRegister(instr->result()); if (instr->hydrogen()->is_in_object()) { __ ldr(result, FieldMemOperand(object, offset)); } else { __ ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset)); __ ldr(result, FieldMemOperand(result, offset)); } } void LCodeGen::EmitLoadFieldOrConstantFunction(Register result, Register object, Handle<Map> type, Handle<String> name, LEnvironment* env) { LookupResult lookup(isolate()); type->LookupDescriptor(NULL, *name, &lookup); ASSERT(lookup.IsFound() || lookup.IsCacheable()); if (lookup.IsField()) { int index = lookup.GetLocalFieldIndexFromMap(*type); int offset = index * kPointerSize; if (index < 0) { // Negative property indices are in-object properties, indexed // from the end of the fixed part of the object. __ ldr(result, FieldMemOperand(object, offset + type->instance_size())); } else { // Non-negative property indices are in the properties array. __ ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset)); __ ldr(result, FieldMemOperand(result, offset + FixedArray::kHeaderSize)); } } else if (lookup.IsConstantFunction()) { Handle<JSFunction> function(lookup.GetConstantFunctionFromMap(*type)); __ LoadHeapObject(result, function); } else { // Negative lookup. // Check prototypes. Handle<HeapObject> current(HeapObject::cast((*type)->prototype())); Heap* heap = type->GetHeap(); while (*current != heap->null_value()) { __ LoadHeapObject(result, current); __ ldr(result, FieldMemOperand(result, HeapObject::kMapOffset)); __ cmp(result, Operand(Handle<Map>(current->map()))); DeoptimizeIf(ne, env); current = Handle<HeapObject>(HeapObject::cast(current->map()->prototype())); } __ LoadRoot(result, Heap::kUndefinedValueRootIndex); } } void LCodeGen::DoLoadNamedFieldPolymorphic(LLoadNamedFieldPolymorphic* instr) { Register object = ToRegister(instr->object()); Register result = ToRegister(instr->result()); Register object_map = scratch0(); int map_count = instr->hydrogen()->types()->length(); bool need_generic = instr->hydrogen()->need_generic(); if (map_count == 0 && !need_generic) { DeoptimizeIf(al, instr->environment()); return; } Handle<String> name = instr->hydrogen()->name(); Label done; __ ldr(object_map, FieldMemOperand(object, HeapObject::kMapOffset)); for (int i = 0; i < map_count; ++i) { bool last = (i == map_count - 1); Handle<Map> map = instr->hydrogen()->types()->at(i); Label check_passed; __ CompareMap( object_map, map, &check_passed, ALLOW_ELEMENT_TRANSITION_MAPS); if (last && !need_generic) { DeoptimizeIf(ne, instr->environment()); __ bind(&check_passed); EmitLoadFieldOrConstantFunction( result, object, map, name, instr->environment()); } else { Label next; __ b(ne, &next); __ bind(&check_passed); EmitLoadFieldOrConstantFunction( result, object, map, name, instr->environment()); __ b(&done); __ bind(&next); } } if (need_generic) { __ mov(r2, Operand(name)); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); } __ bind(&done); } void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(r0)); ASSERT(ToRegister(instr->result()).is(r0)); // Name is always in r2. __ mov(r2, Operand(instr->name())); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); } void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) { Register scratch = scratch0(); Register function = ToRegister(instr->function()); Register result = ToRegister(instr->result()); // Check that the function really is a function. Load map into the // result register. __ CompareObjectType(function, result, scratch, JS_FUNCTION_TYPE); DeoptimizeIf(ne, instr->environment()); // Make sure that the function has an instance prototype. Label non_instance; __ ldrb(scratch, FieldMemOperand(result, Map::kBitFieldOffset)); __ tst(scratch, Operand(1 << Map::kHasNonInstancePrototype)); __ b(ne, &non_instance); // Get the prototype or initial map from the function. __ ldr(result, FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset)); // Check that the function has a prototype or an initial map. __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(result, ip); DeoptimizeIf(eq, instr->environment()); // If the function does not have an initial map, we're done. Label done; __ CompareObjectType(result, scratch, scratch, MAP_TYPE); __ b(ne, &done); // Get the prototype from the initial map. __ ldr(result, FieldMemOperand(result, Map::kPrototypeOffset)); __ jmp(&done); // Non-instance prototype: Fetch prototype from constructor field // in initial map. __ bind(&non_instance); __ ldr(result, FieldMemOperand(result, Map::kConstructorOffset)); // All done. __ bind(&done); } void LCodeGen::DoLoadExternalArrayPointer( LLoadExternalArrayPointer* instr) { Register to_reg = ToRegister(instr->result()); Register from_reg = ToRegister(instr->object()); __ ldr(to_reg, FieldMemOperand(from_reg, ExternalArray::kExternalPointerOffset)); } void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) { Register arguments = ToRegister(instr->arguments()); Register result = ToRegister(instr->result()); if (instr->length()->IsConstantOperand() && instr->index()->IsConstantOperand()) { int const_index = ToInteger32(LConstantOperand::cast(instr->index())); int const_length = ToInteger32(LConstantOperand::cast(instr->length())); int index = (const_length - const_index) + 1; __ ldr(result, MemOperand(arguments, index * kPointerSize)); } else { Register length = ToRegister(instr->length()); Register index = ToRegister(instr->index()); // There are two words between the frame pointer and the last argument. // Subtracting from length accounts for one of them add one more. __ sub(length, length, index); __ add(length, length, Operand(1)); __ ldr(result, MemOperand(arguments, length, LSL, kPointerSizeLog2)); } } void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) { Register external_pointer = ToRegister(instr->elements()); Register key = no_reg; ElementsKind elements_kind = instr->elements_kind(); bool key_is_constant = instr->key()->IsConstantOperand(); int constant_key = 0; if (key_is_constant) { constant_key = ToInteger32(LConstantOperand::cast(instr->key())); if (constant_key & 0xF0000000) { Abort("array index constant value too big."); } } else { key = ToRegister(instr->key()); } int element_size_shift = ElementsKindToShiftSize(elements_kind); int shift_size = (instr->hydrogen()->key()->representation().IsTagged()) ? (element_size_shift - kSmiTagSize) : element_size_shift; int additional_offset = instr->additional_index() << element_size_shift; if (elements_kind == EXTERNAL_FLOAT_ELEMENTS || elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { DwVfpRegister result = ToDoubleRegister(instr->result()); Operand operand = key_is_constant ? Operand(constant_key << element_size_shift) : Operand(key, LSL, shift_size); __ add(scratch0(), external_pointer, operand); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { __ vldr(kScratchDoubleReg.low(), scratch0(), additional_offset); __ vcvt_f64_f32(result, kScratchDoubleReg.low()); } else { // i.e. elements_kind == EXTERNAL_DOUBLE_ELEMENTS __ vldr(result, scratch0(), additional_offset); } } else { Register result = ToRegister(instr->result()); MemOperand mem_operand = PrepareKeyedOperand( key, external_pointer, key_is_constant, constant_key, element_size_shift, shift_size, instr->additional_index(), additional_offset); switch (elements_kind) { case EXTERNAL_BYTE_ELEMENTS: __ ldrsb(result, mem_operand); break; case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: __ ldrb(result, mem_operand); break; case EXTERNAL_SHORT_ELEMENTS: __ ldrsh(result, mem_operand); break; case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ ldrh(result, mem_operand); break; case EXTERNAL_INT_ELEMENTS: __ ldr(result, mem_operand); break; case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ ldr(result, mem_operand); if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) { __ cmp(result, Operand(0x80000000)); DeoptimizeIf(cs, instr->environment()); } break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) { Register elements = ToRegister(instr->elements()); bool key_is_constant = instr->key()->IsConstantOperand(); Register key = no_reg; DwVfpRegister result = ToDoubleRegister(instr->result()); Register scratch = scratch0(); int element_size_shift = ElementsKindToShiftSize(FAST_DOUBLE_ELEMENTS); int shift_size = (instr->hydrogen()->key()->representation().IsTagged()) ? (element_size_shift - kSmiTagSize) : element_size_shift; int constant_key = 0; if (key_is_constant) { constant_key = ToInteger32(LConstantOperand::cast(instr->key())); if (constant_key & 0xF0000000) { Abort("array index constant value too big."); } } else { key = ToRegister(instr->key()); } int base_offset = (FixedDoubleArray::kHeaderSize - kHeapObjectTag) + ((constant_key + instr->additional_index()) << element_size_shift); if (!key_is_constant) { __ add(elements, elements, Operand(key, LSL, shift_size)); } __ add(elements, elements, Operand(base_offset)); __ vldr(result, elements, 0); if (instr->hydrogen()->RequiresHoleCheck()) { __ ldr(scratch, MemOperand(elements, sizeof(kHoleNanLower32))); __ cmp(scratch, Operand(kHoleNanUpper32)); DeoptimizeIf(eq, instr->environment()); } } void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) { Register elements = ToRegister(instr->elements()); Register result = ToRegister(instr->result()); Register scratch = scratch0(); Register store_base = scratch; int offset = 0; if (instr->key()->IsConstantOperand()) { LConstantOperand* const_operand = LConstantOperand::cast(instr->key()); offset = FixedArray::OffsetOfElementAt(ToInteger32(const_operand) + instr->additional_index()); store_base = elements; } else { Register key = EmitLoadRegister(instr->key(), scratch0()); // Even though the HLoadKeyed instruction forces the input // representation for the key to be an integer, the input gets replaced // during bound check elimination with the index argument to the bounds // check, which can be tagged, so that case must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ add(scratch, elements, Operand(key, LSL, kPointerSizeLog2 - kSmiTagSize)); } else { __ add(scratch, elements, Operand(key, LSL, kPointerSizeLog2)); } offset = FixedArray::OffsetOfElementAt(instr->additional_index()); } __ ldr(result, FieldMemOperand(store_base, offset)); // Check for the hole value. if (instr->hydrogen()->RequiresHoleCheck()) { if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) { __ tst(result, Operand(kSmiTagMask)); DeoptimizeIf(ne, instr->environment()); } else { __ LoadRoot(scratch, Heap::kTheHoleValueRootIndex); __ cmp(result, scratch); DeoptimizeIf(eq, instr->environment()); } } } void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) { if (instr->is_external()) { DoLoadKeyedExternalArray(instr); } else if (instr->hydrogen()->representation().IsDouble()) { DoLoadKeyedFixedDoubleArray(instr); } else { DoLoadKeyedFixedArray(instr); } } MemOperand LCodeGen::PrepareKeyedOperand(Register key, Register base, bool key_is_constant, int constant_key, int element_size, int shift_size, int additional_index, int additional_offset) { if (additional_index != 0 && !key_is_constant) { additional_index *= 1 << (element_size - shift_size); __ add(scratch0(), key, Operand(additional_index)); } if (key_is_constant) { return MemOperand(base, (constant_key << element_size) + additional_offset); } if (additional_index == 0) { if (shift_size >= 0) { return MemOperand(base, key, LSL, shift_size); } else { ASSERT_EQ(-1, shift_size); return MemOperand(base, key, LSR, 1); } } if (shift_size >= 0) { return MemOperand(base, scratch0(), LSL, shift_size); } else { ASSERT_EQ(-1, shift_size); return MemOperand(base, scratch0(), LSR, 1); } } void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(r1)); ASSERT(ToRegister(instr->key()).is(r0)); Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); } void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) { Register scratch = scratch0(); Register result = ToRegister(instr->result()); if (instr->hydrogen()->from_inlined()) { __ sub(result, sp, Operand(2 * kPointerSize)); } else { // Check if the calling frame is an arguments adaptor frame. Label done, adapted; __ ldr(scratch, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); __ ldr(result, MemOperand(scratch, StandardFrameConstants::kContextOffset)); __ cmp(result, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); // Result is the frame pointer for the frame if not adapted and for the real // frame below the adaptor frame if adapted. __ mov(result, fp, LeaveCC, ne); __ mov(result, scratch, LeaveCC, eq); } } void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) { Register elem = ToRegister(instr->elements()); Register result = ToRegister(instr->result()); Label done; // If no arguments adaptor frame the number of arguments is fixed. __ cmp(fp, elem); __ mov(result, Operand(scope()->num_parameters())); __ b(eq, &done); // Arguments adaptor frame present. Get argument length from there. __ ldr(result, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); __ ldr(result, MemOperand(result, ArgumentsAdaptorFrameConstants::kLengthOffset)); __ SmiUntag(result); // Argument length is in result register. __ bind(&done); } void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) { Register receiver = ToRegister(instr->receiver()); Register function = ToRegister(instr->function()); Register scratch = scratch0(); // If the receiver is null or undefined, we have to pass the global // object as a receiver to normal functions. Values have to be // passed unchanged to builtins and strict-mode functions. Label global_object, receiver_ok; // Do not transform the receiver to object for strict mode // functions. __ ldr(scratch, FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset)); __ ldr(scratch, FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset)); __ tst(scratch, Operand(1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize))); __ b(ne, &receiver_ok); // Do not transform the receiver to object for builtins. __ tst(scratch, Operand(1 << (SharedFunctionInfo::kNative + kSmiTagSize))); __ b(ne, &receiver_ok); // Normal function. Replace undefined or null with global receiver. __ LoadRoot(scratch, Heap::kNullValueRootIndex); __ cmp(receiver, scratch); __ b(eq, &global_object); __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); __ cmp(receiver, scratch); __ b(eq, &global_object); // Deoptimize if the receiver is not a JS object. __ tst(receiver, Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); __ CompareObjectType(receiver, scratch, scratch, FIRST_SPEC_OBJECT_TYPE); DeoptimizeIf(lt, instr->environment()); __ jmp(&receiver_ok); __ bind(&global_object); __ ldr(receiver, GlobalObjectOperand()); __ ldr(receiver, FieldMemOperand(receiver, JSGlobalObject::kGlobalReceiverOffset)); __ bind(&receiver_ok); } void LCodeGen::DoApplyArguments(LApplyArguments* instr) { Register receiver = ToRegister(instr->receiver()); Register function = ToRegister(instr->function()); Register length = ToRegister(instr->length()); Register elements = ToRegister(instr->elements()); Register scratch = scratch0(); ASSERT(receiver.is(r0)); // Used for parameter count. ASSERT(function.is(r1)); // Required by InvokeFunction. ASSERT(ToRegister(instr->result()).is(r0)); // Copy the arguments to this function possibly from the // adaptor frame below it. const uint32_t kArgumentsLimit = 1 * KB; __ cmp(length, Operand(kArgumentsLimit)); DeoptimizeIf(hi, instr->environment()); // Push the receiver and use the register to keep the original // number of arguments. __ push(receiver); __ mov(receiver, length); // The arguments are at a one pointer size offset from elements. __ add(elements, elements, Operand(1 * kPointerSize)); // Loop through the arguments pushing them onto the execution // stack. Label invoke, loop; // length is a small non-negative integer, due to the test above. __ cmp(length, Operand::Zero()); __ b(eq, &invoke); __ bind(&loop); __ ldr(scratch, MemOperand(elements, length, LSL, 2)); __ push(scratch); __ sub(length, length, Operand(1), SetCC); __ b(ne, &loop); __ bind(&invoke); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); // The number of arguments is stored in receiver which is r0, as expected // by InvokeFunction. ParameterCount actual(receiver); __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator, CALL_AS_METHOD); __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoPushArgument(LPushArgument* instr) { LOperand* argument = instr->value(); if (argument->IsDoubleRegister() || argument->IsDoubleStackSlot()) { Abort("DoPushArgument not implemented for double type."); } else { Register argument_reg = EmitLoadRegister(argument, ip); __ push(argument_reg); } } void LCodeGen::DoDrop(LDrop* instr) { __ Drop(instr->count()); } void LCodeGen::DoThisFunction(LThisFunction* instr) { Register result = ToRegister(instr->result()); __ ldr(result, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset)); } void LCodeGen::DoContext(LContext* instr) { // If there is a non-return use, the context must be moved to a register. Register result = ToRegister(instr->result()); for (HUseIterator it(instr->hydrogen()->uses()); !it.Done(); it.Advance()) { if (!it.value()->IsReturn()) { __ mov(result, cp); return; } } } void LCodeGen::DoOuterContext(LOuterContext* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ ldr(result, MemOperand(context, Context::SlotOffset(Context::PREVIOUS_INDEX))); } void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) { __ push(cp); // The context is the first argument. __ LoadHeapObject(scratch0(), instr->hydrogen()->pairs()); __ push(scratch0()); __ mov(scratch0(), Operand(Smi::FromInt(instr->hydrogen()->flags()))); __ push(scratch0()); CallRuntime(Runtime::kDeclareGlobals, 3, instr); } void LCodeGen::DoGlobalObject(LGlobalObject* instr) { Register result = ToRegister(instr->result()); __ ldr(result, ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX)); } void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) { Register global = ToRegister(instr->global_object()); Register result = ToRegister(instr->result()); __ ldr(result, FieldMemOperand(global, GlobalObject::kGlobalReceiverOffset)); } void LCodeGen::CallKnownFunction(Handle<JSFunction> function, int formal_parameter_count, int arity, LInstruction* instr, CallKind call_kind, R1State r1_state) { bool dont_adapt_arguments = formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel; bool can_invoke_directly = dont_adapt_arguments || formal_parameter_count == arity; LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); if (can_invoke_directly) { if (r1_state == R1_UNINITIALIZED) { __ LoadHeapObject(r1, function); } // Change context. __ ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset)); // Set r0 to arguments count if adaption is not needed. Assumes that r0 // is available to write to at this point. if (dont_adapt_arguments) { __ mov(r0, Operand(arity)); } // Invoke function. __ SetCallKind(r5, call_kind); __ ldr(ip, FieldMemOperand(r1, JSFunction::kCodeEntryOffset)); __ Call(ip); // Set up deoptimization. RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT); } else { SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt); ParameterCount count(arity); ParameterCount expected(formal_parameter_count); __ InvokeFunction( function, expected, count, CALL_FUNCTION, generator, call_kind); } // Restore context. __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) { ASSERT(ToRegister(instr->result()).is(r0)); CallKnownFunction(instr->hydrogen()->function(), instr->hydrogen()->formal_parameter_count(), instr->arity(), instr, CALL_AS_METHOD, R1_UNINITIALIZED); } void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); Register scratch = scratch0(); // Deoptimize if not a heap number. __ ldr(scratch, FieldMemOperand(input, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex); __ cmp(scratch, Operand(ip)); DeoptimizeIf(ne, instr->environment()); Label done; Register exponent = scratch0(); scratch = no_reg; __ ldr(exponent, FieldMemOperand(input, HeapNumber::kExponentOffset)); // Check the sign of the argument. If the argument is positive, just // return it. __ tst(exponent, Operand(HeapNumber::kSignMask)); // Move the input to the result if necessary. __ Move(result, input); __ b(eq, &done); // Input is negative. Reverse its sign. // Preserve the value of all registers. { PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); // Registers were saved at the safepoint, so we can use // many scratch registers. Register tmp1 = input.is(r1) ? r0 : r1; Register tmp2 = input.is(r2) ? r0 : r2; Register tmp3 = input.is(r3) ? r0 : r3; Register tmp4 = input.is(r4) ? r0 : r4; // exponent: floating point exponent value. Label allocated, slow; __ LoadRoot(tmp4, Heap::kHeapNumberMapRootIndex); __ AllocateHeapNumber(tmp1, tmp2, tmp3, tmp4, &slow); __ b(&allocated); // Slow case: Call the runtime system to do the number allocation. __ bind(&slow); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); // Set the pointer to the new heap number in tmp. if (!tmp1.is(r0)) __ mov(tmp1, Operand(r0)); // Restore input_reg after call to runtime. __ LoadFromSafepointRegisterSlot(input, input); __ ldr(exponent, FieldMemOperand(input, HeapNumber::kExponentOffset)); __ bind(&allocated); // exponent: floating point exponent value. // tmp1: allocated heap number. __ bic(exponent, exponent, Operand(HeapNumber::kSignMask)); __ str(exponent, FieldMemOperand(tmp1, HeapNumber::kExponentOffset)); __ ldr(tmp2, FieldMemOperand(input, HeapNumber::kMantissaOffset)); __ str(tmp2, FieldMemOperand(tmp1, HeapNumber::kMantissaOffset)); __ StoreToSafepointRegisterSlot(tmp1, result); } __ bind(&done); } void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); __ cmp(input, Operand::Zero()); __ Move(result, input, pl); // We can make rsb conditional because the previous cmp instruction // will clear the V (overflow) flag and rsb won't set this flag // if input is positive. __ rsb(result, input, Operand::Zero(), SetCC, mi); // Deoptimize on overflow. DeoptimizeIf(vs, instr->environment()); } void LCodeGen::DoMathAbs(LMathAbs* instr) { // Class for deferred case. class DeferredMathAbsTaggedHeapNumber: public LDeferredCode { public: DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LMathAbs* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_); } virtual LInstruction* instr() { return instr_; } private: LMathAbs* instr_; }; Representation r = instr->hydrogen()->value()->representation(); if (r.IsDouble()) { DwVfpRegister input = ToDoubleRegister(instr->value()); DwVfpRegister result = ToDoubleRegister(instr->result()); __ vabs(result, input); } else if (r.IsInteger32()) { EmitIntegerMathAbs(instr); } else { // Representation is tagged. DeferredMathAbsTaggedHeapNumber* deferred = new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr); Register input = ToRegister(instr->value()); // Smi check. __ JumpIfNotSmi(input, deferred->entry()); // If smi, handle it directly. EmitIntegerMathAbs(instr); __ bind(deferred->exit()); } } void LCodeGen::DoMathFloor(LMathFloor* instr) { DwVfpRegister input = ToDoubleRegister(instr->value()); Register result = ToRegister(instr->result()); Register input_high = scratch0(); Label done, exact; __ vmov(input_high, input.high()); __ TryInt32Floor(result, input, input_high, double_scratch0(), &done, &exact); DeoptimizeIf(al, instr->environment()); __ bind(&exact); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Test for -0. __ cmp(result, Operand::Zero()); __ b(ne, &done); __ cmp(input_high, Operand::Zero()); DeoptimizeIf(mi, instr->environment()); } __ bind(&done); } void LCodeGen::DoMathRound(LMathRound* instr) { DwVfpRegister input = ToDoubleRegister(instr->value()); Register result = ToRegister(instr->result()); DwVfpRegister double_scratch1 = ToDoubleRegister(instr->temp()); DwVfpRegister input_plus_dot_five = double_scratch1; Register input_high = scratch0(); DwVfpRegister dot_five = double_scratch0(); Label convert, done; __ Vmov(dot_five, 0.5, scratch0()); __ vabs(double_scratch1, input); __ VFPCompareAndSetFlags(double_scratch1, dot_five); // If input is in [-0.5, -0], the result is -0. // If input is in [+0, +0.5[, the result is +0. // If the input is +0.5, the result is 1. __ b(hi, &convert); // Out of [-0.5, +0.5]. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ vmov(input_high, input.high()); __ cmp(input_high, Operand::Zero()); DeoptimizeIf(mi, instr->environment()); // [-0.5, -0]. } __ VFPCompareAndSetFlags(input, dot_five); __ mov(result, Operand(1), LeaveCC, eq); // +0.5. // Remaining cases: [+0, +0.5[ or [-0.5, +0.5[, depending on // flag kBailoutOnMinusZero. __ mov(result, Operand::Zero(), LeaveCC, ne); __ b(&done); __ bind(&convert); __ vadd(input_plus_dot_five, input, dot_five); __ vmov(input_high, input_plus_dot_five.high()); // Reuse dot_five (double_scratch0) as we no longer need this value. __ TryInt32Floor(result, input_plus_dot_five, input_high, double_scratch0(), &done, &done); DeoptimizeIf(al, instr->environment()); __ bind(&done); } void LCodeGen::DoMathSqrt(LMathSqrt* instr) { DwVfpRegister input = ToDoubleRegister(instr->value()); DwVfpRegister result = ToDoubleRegister(instr->result()); __ vsqrt(result, input); } void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) { DwVfpRegister input = ToDoubleRegister(instr->value()); DwVfpRegister result = ToDoubleRegister(instr->result()); DwVfpRegister temp = ToDoubleRegister(instr->temp()); // Note that according to ECMA-262 15.8.2.13: // Math.pow(-Infinity, 0.5) == Infinity // Math.sqrt(-Infinity) == NaN Label done; __ vmov(temp, -V8_INFINITY, scratch0()); __ VFPCompareAndSetFlags(input, temp); __ vneg(result, temp, eq); __ b(&done, eq); // Add +0 to convert -0 to +0. __ vadd(result, input, kDoubleRegZero); __ vsqrt(result, result); __ bind(&done); } void LCodeGen::DoPower(LPower* instr) { Representation exponent_type = instr->hydrogen()->right()->representation(); // Having marked this as a call, we can use any registers. // Just make sure that the input/output registers are the expected ones. ASSERT(!instr->right()->IsDoubleRegister() || ToDoubleRegister(instr->right()).is(d2)); ASSERT(!instr->right()->IsRegister() || ToRegister(instr->right()).is(r2)); ASSERT(ToDoubleRegister(instr->left()).is(d1)); ASSERT(ToDoubleRegister(instr->result()).is(d3)); if (exponent_type.IsTagged()) { Label no_deopt; __ JumpIfSmi(r2, &no_deopt); __ ldr(r7, FieldMemOperand(r2, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex); __ cmp(r7, Operand(ip)); DeoptimizeIf(ne, instr->environment()); __ bind(&no_deopt); MathPowStub stub(MathPowStub::TAGGED); __ CallStub(&stub); } else if (exponent_type.IsInteger32()) { MathPowStub stub(MathPowStub::INTEGER); __ CallStub(&stub); } else { ASSERT(exponent_type.IsDouble()); MathPowStub stub(MathPowStub::DOUBLE); __ CallStub(&stub); } } void LCodeGen::DoRandom(LRandom* instr) { class DeferredDoRandom: public LDeferredCode { public: DeferredDoRandom(LCodeGen* codegen, LRandom* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredRandom(instr_); } virtual LInstruction* instr() { return instr_; } private: LRandom* instr_; }; DeferredDoRandom* deferred = new(zone()) DeferredDoRandom(this, instr); // Having marked this instruction as a call we can use any // registers. ASSERT(ToDoubleRegister(instr->result()).is(d7)); ASSERT(ToRegister(instr->global_object()).is(r0)); static const int kSeedSize = sizeof(uint32_t); STATIC_ASSERT(kPointerSize == kSeedSize); __ ldr(r0, FieldMemOperand(r0, GlobalObject::kNativeContextOffset)); static const int kRandomSeedOffset = FixedArray::kHeaderSize + Context::RANDOM_SEED_INDEX * kPointerSize; __ ldr(r2, FieldMemOperand(r0, kRandomSeedOffset)); // r2: FixedArray of the native context's random seeds // Load state[0]. __ ldr(r1, FieldMemOperand(r2, ByteArray::kHeaderSize)); __ cmp(r1, Operand::Zero()); __ b(eq, deferred->entry()); // Load state[1]. __ ldr(r0, FieldMemOperand(r2, ByteArray::kHeaderSize + kSeedSize)); // r1: state[0]. // r0: state[1]. // state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16) __ and_(r3, r1, Operand(0xFFFF)); __ mov(r4, Operand(18273)); __ mul(r3, r3, r4); __ add(r1, r3, Operand(r1, LSR, 16)); // Save state[0]. __ str(r1, FieldMemOperand(r2, ByteArray::kHeaderSize)); // state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16) __ and_(r3, r0, Operand(0xFFFF)); __ mov(r4, Operand(36969)); __ mul(r3, r3, r4); __ add(r0, r3, Operand(r0, LSR, 16)); // Save state[1]. __ str(r0, FieldMemOperand(r2, ByteArray::kHeaderSize + kSeedSize)); // Random bit pattern = (state[0] << 14) + (state[1] & 0x3FFFF) __ and_(r0, r0, Operand(0x3FFFF)); __ add(r0, r0, Operand(r1, LSL, 14)); __ bind(deferred->exit()); // 0x41300000 is the top half of 1.0 x 2^20 as a double. // Create this constant using mov/orr to avoid PC relative load. __ mov(r1, Operand(0x41000000)); __ orr(r1, r1, Operand(0x300000)); // Move 0x41300000xxxxxxxx (x = random bits) to VFP. __ vmov(d7, r0, r1); // Move 0x4130000000000000 to VFP. __ mov(r0, Operand::Zero()); __ vmov(d8, r0, r1); // Subtract and store the result in the heap number. __ vsub(d7, d7, d8); } void LCodeGen::DoDeferredRandom(LRandom* instr) { __ PrepareCallCFunction(1, scratch0()); __ CallCFunction(ExternalReference::random_uint32_function(isolate()), 1); // Return value is in r0. } void LCodeGen::DoMathExp(LMathExp* instr) { DwVfpRegister input = ToDoubleRegister(instr->value()); DwVfpRegister result = ToDoubleRegister(instr->result()); DwVfpRegister double_scratch1 = ToDoubleRegister(instr->double_temp()); DwVfpRegister double_scratch2 = double_scratch0(); Register temp1 = ToRegister(instr->temp1()); Register temp2 = ToRegister(instr->temp2()); MathExpGenerator::EmitMathExp( masm(), input, result, double_scratch1, double_scratch2, temp1, temp2, scratch0()); } void LCodeGen::DoMathLog(LMathLog* instr) { ASSERT(ToDoubleRegister(instr->result()).is(d2)); TranscendentalCacheStub stub(TranscendentalCache::LOG, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathTan(LMathTan* instr) { ASSERT(ToDoubleRegister(instr->result()).is(d2)); TranscendentalCacheStub stub(TranscendentalCache::TAN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathCos(LMathCos* instr) { ASSERT(ToDoubleRegister(instr->result()).is(d2)); TranscendentalCacheStub stub(TranscendentalCache::COS, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathSin(LMathSin* instr) { ASSERT(ToDoubleRegister(instr->result()).is(d2)); TranscendentalCacheStub stub(TranscendentalCache::SIN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) { ASSERT(ToRegister(instr->function()).is(r1)); ASSERT(instr->HasPointerMap()); Handle<JSFunction> known_function = instr->hydrogen()->known_function(); if (known_function.is_null()) { LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt); ParameterCount count(instr->arity()); __ InvokeFunction(r1, count, CALL_FUNCTION, generator, CALL_AS_METHOD); __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } else { CallKnownFunction(known_function, instr->hydrogen()->formal_parameter_count(), instr->arity(), instr, CALL_AS_METHOD, R1_CONTAINS_TARGET); } } void LCodeGen::DoCallKeyed(LCallKeyed* instr) { ASSERT(ToRegister(instr->result()).is(r0)); int arity = instr->arity(); Handle<Code> ic = isolate()->stub_cache()->ComputeKeyedCallInitialize(arity); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallNamed(LCallNamed* instr) { ASSERT(ToRegister(instr->result()).is(r0)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ mov(r2, Operand(instr->name())); CallCode(ic, mode, instr, NEVER_INLINE_TARGET_ADDRESS); // Restore context register. __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallFunction(LCallFunction* instr) { ASSERT(ToRegister(instr->function()).is(r1)); ASSERT(ToRegister(instr->result()).is(r0)); int arity = instr->arity(); CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallGlobal(LCallGlobal* instr) { ASSERT(ToRegister(instr->result()).is(r0)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ mov(r2, Operand(instr->name())); CallCode(ic, mode, instr, NEVER_INLINE_TARGET_ADDRESS); __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) { ASSERT(ToRegister(instr->result()).is(r0)); CallKnownFunction(instr->hydrogen()->target(), instr->hydrogen()->formal_parameter_count(), instr->arity(), instr, CALL_AS_FUNCTION, R1_UNINITIALIZED); } void LCodeGen::DoCallNew(LCallNew* instr) { ASSERT(ToRegister(instr->constructor()).is(r1)); ASSERT(ToRegister(instr->result()).is(r0)); __ mov(r0, Operand(instr->arity())); if (FLAG_optimize_constructed_arrays) { // No cell in r2 for construct type feedback in optimized code Handle<Object> undefined_value(isolate()->heap()->undefined_value(), isolate()); __ mov(r2, Operand(undefined_value)); } CallConstructStub stub(NO_CALL_FUNCTION_FLAGS); CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr); } void LCodeGen::DoCallNewArray(LCallNewArray* instr) { ASSERT(ToRegister(instr->constructor()).is(r1)); ASSERT(ToRegister(instr->result()).is(r0)); ASSERT(FLAG_optimize_constructed_arrays); __ mov(r0, Operand(instr->arity())); __ mov(r2, Operand(instr->hydrogen()->property_cell())); ElementsKind kind = instr->hydrogen()->elements_kind(); if (instr->arity() == 0) { ArrayNoArgumentConstructorStub stub(kind); CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr); } else if (instr->arity() == 1) { ArraySingleArgumentConstructorStub stub(kind); CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr); } else { ArrayNArgumentsConstructorStub stub(kind); CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr); } } void LCodeGen::DoCallRuntime(LCallRuntime* instr) { CallRuntime(instr->function(), instr->arity(), instr); } void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) { Register result = ToRegister(instr->result()); Register base = ToRegister(instr->base_object()); __ add(result, base, Operand(instr->offset())); } void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) { Representation representation = instr->representation(); Register object = ToRegister(instr->object()); Register scratch = scratch0(); int offset = instr->offset(); Handle<Map> transition = instr->transition(); if (FLAG_track_fields && representation.IsSmi()) { Register value = ToRegister(instr->value()); __ SmiTag(value, value, SetCC); if (!instr->hydrogen()->value()->range()->IsInSmiRange()) { DeoptimizeIf(vs, instr->environment()); } } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) { Register value = ToRegister(instr->value()); if (!instr->hydrogen()->value()->type().IsHeapObject()) { __ tst(value, Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); } } else if (FLAG_track_double_fields && representation.IsDouble()) { ASSERT(transition.is_null()); ASSERT(instr->is_in_object()); ASSERT(!instr->hydrogen()->NeedsWriteBarrier()); DwVfpRegister value = ToDoubleRegister(instr->value()); __ vstr(value, FieldMemOperand(object, offset)); return; } if (!transition.is_null()) { if (transition->CanBeDeprecated()) { transition_maps_.Add(transition, info()->zone()); } __ mov(scratch, Operand(transition)); __ str(scratch, FieldMemOperand(object, HeapObject::kMapOffset)); if (instr->hydrogen()->NeedsWriteBarrierForMap()) { Register temp = ToRegister(instr->temp()); // Update the write barrier for the map field. __ RecordWriteField(object, HeapObject::kMapOffset, scratch, temp, GetLinkRegisterState(), kSaveFPRegs, OMIT_REMEMBERED_SET, OMIT_SMI_CHECK); } } // Do the store. Register value = ToRegister(instr->value()); ASSERT(!object.is(value)); HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; if (instr->is_in_object()) { __ str(value, FieldMemOperand(object, offset)); if (instr->hydrogen()->NeedsWriteBarrier()) { // Update the write barrier for the object for in-object properties. __ RecordWriteField(object, offset, value, scratch, GetLinkRegisterState(), kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } else { __ ldr(scratch, FieldMemOperand(object, JSObject::kPropertiesOffset)); __ str(value, FieldMemOperand(scratch, offset)); if (instr->hydrogen()->NeedsWriteBarrier()) { // Update the write barrier for the properties array. // object is used as a scratch register. __ RecordWriteField(scratch, offset, value, object, GetLinkRegisterState(), kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } } void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(r1)); ASSERT(ToRegister(instr->value()).is(r0)); // Name is always in r2. __ mov(r2, Operand(instr->name())); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); } void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) { if (instr->hydrogen()->skip_check()) return; if (instr->index()->IsConstantOperand()) { int constant_index = ToInteger32(LConstantOperand::cast(instr->index())); if (instr->hydrogen()->length()->representation().IsTagged()) { __ mov(ip, Operand(Smi::FromInt(constant_index))); } else { __ mov(ip, Operand(constant_index)); } __ cmp(ip, ToRegister(instr->length())); } else { __ cmp(ToRegister(instr->index()), ToRegister(instr->length())); } DeoptimizeIf(hs, instr->environment()); } void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) { Register external_pointer = ToRegister(instr->elements()); Register key = no_reg; ElementsKind elements_kind = instr->elements_kind(); bool key_is_constant = instr->key()->IsConstantOperand(); int constant_key = 0; if (key_is_constant) { constant_key = ToInteger32(LConstantOperand::cast(instr->key())); if (constant_key & 0xF0000000) { Abort("array index constant value too big."); } } else { key = ToRegister(instr->key()); } int element_size_shift = ElementsKindToShiftSize(elements_kind); int shift_size = (instr->hydrogen()->key()->representation().IsTagged()) ? (element_size_shift - kSmiTagSize) : element_size_shift; int additional_offset = instr->additional_index() << element_size_shift; if (elements_kind == EXTERNAL_FLOAT_ELEMENTS || elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { DwVfpRegister value(ToDoubleRegister(instr->value())); Operand operand(key_is_constant ? Operand(constant_key << element_size_shift) : Operand(key, LSL, shift_size)); __ add(scratch0(), external_pointer, operand); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { __ vcvt_f32_f64(double_scratch0().low(), value); __ vstr(double_scratch0().low(), scratch0(), additional_offset); } else { // i.e. elements_kind == EXTERNAL_DOUBLE_ELEMENTS __ vstr(value, scratch0(), additional_offset); } } else { Register value(ToRegister(instr->value())); MemOperand mem_operand = PrepareKeyedOperand( key, external_pointer, key_is_constant, constant_key, element_size_shift, shift_size, instr->additional_index(), additional_offset); switch (elements_kind) { case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_BYTE_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: __ strb(value, mem_operand); break; case EXTERNAL_SHORT_ELEMENTS: case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ strh(value, mem_operand); break; case EXTERNAL_INT_ELEMENTS: case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ str(value, mem_operand); break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) { DwVfpRegister value = ToDoubleRegister(instr->value()); Register elements = ToRegister(instr->elements()); Register key = no_reg; Register scratch = scratch0(); bool key_is_constant = instr->key()->IsConstantOperand(); int constant_key = 0; // Calculate the effective address of the slot in the array to store the // double value. if (key_is_constant) { constant_key = ToInteger32(LConstantOperand::cast(instr->key())); if (constant_key & 0xF0000000) { Abort("array index constant value too big."); } } else { key = ToRegister(instr->key()); } int element_size_shift = ElementsKindToShiftSize(FAST_DOUBLE_ELEMENTS); int shift_size = (instr->hydrogen()->key()->representation().IsTagged()) ? (element_size_shift - kSmiTagSize) : element_size_shift; Operand operand = key_is_constant ? Operand((constant_key << element_size_shift) + FixedDoubleArray::kHeaderSize - kHeapObjectTag) : Operand(key, LSL, shift_size); __ add(scratch, elements, operand); if (!key_is_constant) { __ add(scratch, scratch, Operand(FixedDoubleArray::kHeaderSize - kHeapObjectTag)); } if (instr->NeedsCanonicalization()) { // Force a canonical NaN. if (masm()->emit_debug_code()) { __ vmrs(ip); __ tst(ip, Operand(kVFPDefaultNaNModeControlBit)); __ Assert(ne, "Default NaN mode not set"); } __ VFPCanonicalizeNaN(value); } __ vstr(value, scratch, instr->additional_index() << element_size_shift); } void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) { Register value = ToRegister(instr->value()); Register elements = ToRegister(instr->elements()); Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg; Register scratch = scratch0(); Register store_base = scratch; int offset = 0; // Do the store. if (instr->key()->IsConstantOperand()) { ASSERT(!instr->hydrogen()->NeedsWriteBarrier()); LConstantOperand* const_operand = LConstantOperand::cast(instr->key()); offset = FixedArray::OffsetOfElementAt(ToInteger32(const_operand) + instr->additional_index()); store_base = elements; } else { // Even though the HLoadKeyed instruction forces the input // representation for the key to be an integer, the input gets replaced // during bound check elimination with the index argument to the bounds // check, which can be tagged, so that case must be handled here, too. if (instr->hydrogen()->key()->representation().IsTagged()) { __ add(scratch, elements, Operand(key, LSL, kPointerSizeLog2 - kSmiTagSize)); } else { __ add(scratch, elements, Operand(key, LSL, kPointerSizeLog2)); } offset = FixedArray::OffsetOfElementAt(instr->additional_index()); } __ str(value, FieldMemOperand(store_base, offset)); if (instr->hydrogen()->NeedsWriteBarrier()) { HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; // Compute address of modified element and store it into key register. __ add(key, store_base, Operand(offset - kHeapObjectTag)); __ RecordWrite(elements, key, value, GetLinkRegisterState(), kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) { // By cases: external, fast double if (instr->is_external()) { DoStoreKeyedExternalArray(instr); } else if (instr->hydrogen()->value()->representation().IsDouble()) { DoStoreKeyedFixedDoubleArray(instr); } else { DoStoreKeyedFixedArray(instr); } } void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(r2)); ASSERT(ToRegister(instr->key()).is(r1)); ASSERT(ToRegister(instr->value()).is(r0)); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->KeyedStoreIC_Initialize_Strict() : isolate()->builtins()->KeyedStoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr, NEVER_INLINE_TARGET_ADDRESS); } void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) { Register object_reg = ToRegister(instr->object()); Register scratch = scratch0(); Handle<Map> from_map = instr->original_map(); Handle<Map> to_map = instr->transitioned_map(); ElementsKind from_kind = instr->from_kind(); ElementsKind to_kind = instr->to_kind(); Label not_applicable; __ ldr(scratch, FieldMemOperand(object_reg, HeapObject::kMapOffset)); __ cmp(scratch, Operand(from_map)); __ b(ne, &not_applicable); if (IsSimpleMapChangeTransition(from_kind, to_kind)) { Register new_map_reg = ToRegister(instr->new_map_temp()); __ mov(new_map_reg, Operand(to_map)); __ str(new_map_reg, FieldMemOperand(object_reg, HeapObject::kMapOffset)); // Write barrier. __ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg, scratch, GetLinkRegisterState(), kDontSaveFPRegs); } else if (FLAG_compiled_transitions) { PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); __ Move(r0, object_reg); __ Move(r1, to_map); TransitionElementsKindStub stub(from_kind, to_kind); __ CallStub(&stub); RecordSafepointWithRegisters( instr->pointer_map(), 0, Safepoint::kNoLazyDeopt); } else if (IsFastSmiElementsKind(from_kind) && IsFastDoubleElementsKind(to_kind)) { Register fixed_object_reg = ToRegister(instr->temp()); ASSERT(fixed_object_reg.is(r2)); Register new_map_reg = ToRegister(instr->new_map_temp()); ASSERT(new_map_reg.is(r3)); __ mov(new_map_reg, Operand(to_map)); __ mov(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsSmiToDouble(), RelocInfo::CODE_TARGET, instr); } else if (IsFastDoubleElementsKind(from_kind) && IsFastObjectElementsKind(to_kind)) { Register fixed_object_reg = ToRegister(instr->temp()); ASSERT(fixed_object_reg.is(r2)); Register new_map_reg = ToRegister(instr->new_map_temp()); ASSERT(new_map_reg.is(r3)); __ mov(new_map_reg, Operand(to_map)); __ mov(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsDoubleToObject(), RelocInfo::CODE_TARGET, instr); } else { UNREACHABLE(); } __ bind(&not_applicable); } void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) { Register object = ToRegister(instr->object()); Register temp = ToRegister(instr->temp()); __ TestJSArrayForAllocationSiteInfo(object, temp); DeoptimizeIf(eq, instr->environment()); } void LCodeGen::DoStringAdd(LStringAdd* instr) { __ push(ToRegister(instr->left())); __ push(ToRegister(instr->right())); StringAddStub stub(NO_STRING_CHECK_IN_STUB); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) { class DeferredStringCharCodeAt: public LDeferredCode { public: DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharCodeAt* instr_; }; DeferredStringCharCodeAt* deferred = new(zone()) DeferredStringCharCodeAt(this, instr); StringCharLoadGenerator::Generate(masm(), ToRegister(instr->string()), ToRegister(instr->index()), ToRegister(instr->result()), deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); Register scratch = scratch0(); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ mov(result, Operand::Zero()); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); __ push(string); // Push the index as a smi. This is safe because of the checks in // DoStringCharCodeAt above. if (instr->index()->IsConstantOperand()) { int const_index = ToInteger32(LConstantOperand::cast(instr->index())); __ mov(scratch, Operand(Smi::FromInt(const_index))); __ push(scratch); } else { Register index = ToRegister(instr->index()); __ SmiTag(index); __ push(index); } CallRuntimeFromDeferred(Runtime::kStringCharCodeAt, 2, instr); __ AssertSmi(r0); __ SmiUntag(r0); __ StoreToSafepointRegisterSlot(r0, result); } void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) { class DeferredStringCharFromCode: public LDeferredCode { public: DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharFromCode* instr_; }; DeferredStringCharFromCode* deferred = new(zone()) DeferredStringCharFromCode(this, instr); ASSERT(instr->hydrogen()->value()->representation().IsInteger32()); Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); ASSERT(!char_code.is(result)); __ cmp(char_code, Operand(String::kMaxOneByteCharCode)); __ b(hi, deferred->entry()); __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex); __ add(result, result, Operand(char_code, LSL, kPointerSizeLog2)); __ ldr(result, FieldMemOperand(result, FixedArray::kHeaderSize)); __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); __ cmp(result, ip); __ b(eq, deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) { Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ mov(result, Operand::Zero()); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); __ SmiTag(char_code); __ push(char_code); CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr); __ StoreToSafepointRegisterSlot(r0, result); } void LCodeGen::DoStringLength(LStringLength* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); __ ldr(result, FieldMemOperand(string, String::kLengthOffset)); } void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister() || input->IsStackSlot()); LOperand* output = instr->result(); ASSERT(output->IsDoubleRegister()); SwVfpRegister single_scratch = double_scratch0().low(); if (input->IsStackSlot()) { Register scratch = scratch0(); __ ldr(scratch, ToMemOperand(input)); __ vmov(single_scratch, scratch); } else { __ vmov(single_scratch, ToRegister(input)); } __ vcvt_f64_s32(ToDoubleRegister(output), single_scratch); } void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) { LOperand* input = instr->value(); LOperand* output = instr->result(); SwVfpRegister flt_scratch = double_scratch0().low(); __ vmov(flt_scratch, ToRegister(input)); __ vcvt_f64_u32(ToDoubleRegister(output), flt_scratch); } void LCodeGen::DoNumberTagI(LNumberTagI* instr) { class DeferredNumberTagI: public LDeferredCode { public: DeferredNumberTagI(LCodeGen* codegen, LNumberTagI* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagI(instr_, instr_->value(), SIGNED_INT32); } virtual LInstruction* instr() { return instr_; } private: LNumberTagI* instr_; }; Register src = ToRegister(instr->value()); Register dst = ToRegister(instr->result()); DeferredNumberTagI* deferred = new(zone()) DeferredNumberTagI(this, instr); __ SmiTag(dst, src, SetCC); __ b(vs, deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoNumberTagU(LNumberTagU* instr) { class DeferredNumberTagU: public LDeferredCode { public: DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagI(instr_, instr_->value(), UNSIGNED_INT32); } virtual LInstruction* instr() { return instr_; } private: LNumberTagU* instr_; }; LOperand* input = instr->value(); ASSERT(input->IsRegister() && input->Equals(instr->result())); Register reg = ToRegister(input); DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr); __ cmp(reg, Operand(Smi::kMaxValue)); __ b(hi, deferred->entry()); __ SmiTag(reg, reg); __ bind(deferred->exit()); } void LCodeGen::DoDeferredNumberTagI(LInstruction* instr, LOperand* value, IntegerSignedness signedness) { Label slow; Register src = ToRegister(value); Register dst = ToRegister(instr->result()); DwVfpRegister dbl_scratch = double_scratch0(); SwVfpRegister flt_scratch = dbl_scratch.low(); // Preserve the value of all registers. PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); Label done; if (signedness == SIGNED_INT32) { // There was overflow, so bits 30 and 31 of the original integer // disagree. Try to allocate a heap number in new space and store // the value in there. If that fails, call the runtime system. if (dst.is(src)) { __ SmiUntag(src, dst); __ eor(src, src, Operand(0x80000000)); } __ vmov(flt_scratch, src); __ vcvt_f64_s32(dbl_scratch, flt_scratch); } else { __ vmov(flt_scratch, src); __ vcvt_f64_u32(dbl_scratch, flt_scratch); } if (FLAG_inline_new) { __ LoadRoot(scratch0(), Heap::kHeapNumberMapRootIndex); __ AllocateHeapNumber(r5, r3, r4, scratch0(), &slow, DONT_TAG_RESULT); __ Move(dst, r5); __ b(&done); } // Slow case: Call the runtime system to do the number allocation. __ bind(&slow); // TODO(3095996): Put a valid pointer value in the stack slot where the result // register is stored, as this register is in the pointer map, but contains an // integer value. __ mov(ip, Operand::Zero()); __ StoreToSafepointRegisterSlot(ip, dst); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); __ Move(dst, r0); __ sub(dst, dst, Operand(kHeapObjectTag)); // Done. Put the value in dbl_scratch into the value of the allocated heap // number. __ bind(&done); __ vstr(dbl_scratch, dst, HeapNumber::kValueOffset); __ add(dst, dst, Operand(kHeapObjectTag)); __ StoreToSafepointRegisterSlot(dst, dst); } void LCodeGen::DoNumberTagD(LNumberTagD* instr) { class DeferredNumberTagD: public LDeferredCode { public: DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); } virtual LInstruction* instr() { return instr_; } private: LNumberTagD* instr_; }; DwVfpRegister input_reg = ToDoubleRegister(instr->value()); Register scratch = scratch0(); Register reg = ToRegister(instr->result()); Register temp1 = ToRegister(instr->temp()); Register temp2 = ToRegister(instr->temp2()); bool convert_hole = false; HValue* change_input = instr->hydrogen()->value(); if (change_input->IsLoadKeyed()) { HLoadKeyed* load = HLoadKeyed::cast(change_input); convert_hole = load->UsesMustHandleHole(); } Label no_special_nan_handling; Label done; if (convert_hole) { DwVfpRegister input_reg = ToDoubleRegister(instr->value()); __ VFPCompareAndSetFlags(input_reg, input_reg); __ b(vc, &no_special_nan_handling); __ vmov(scratch, input_reg.high()); __ cmp(scratch, Operand(kHoleNanUpper32)); // If not the hole NaN, force the NaN to be canonical. __ VFPCanonicalizeNaN(input_reg, ne); __ b(ne, &no_special_nan_handling); __ Move(reg, factory()->the_hole_value()); __ b(&done); } __ bind(&no_special_nan_handling); DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr); if (FLAG_inline_new) { __ LoadRoot(scratch, Heap::kHeapNumberMapRootIndex); // We want the untagged address first for performance __ AllocateHeapNumber(reg, temp1, temp2, scratch, deferred->entry(), DONT_TAG_RESULT); } else { __ jmp(deferred->entry()); } __ bind(deferred->exit()); __ vstr(input_reg, reg, HeapNumber::kValueOffset); // Now that we have finished with the object's real address tag it __ add(reg, reg, Operand(kHeapObjectTag)); __ bind(&done); } void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) { // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. Register reg = ToRegister(instr->result()); __ mov(reg, Operand::Zero()); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); __ sub(r0, r0, Operand(kHeapObjectTag)); __ StoreToSafepointRegisterSlot(r0, reg); } void LCodeGen::DoSmiTag(LSmiTag* instr) { ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)); __ SmiTag(ToRegister(instr->result()), ToRegister(instr->value())); } void LCodeGen::DoSmiUntag(LSmiUntag* instr) { Register input = ToRegister(instr->value()); Register result = ToRegister(instr->result()); if (instr->needs_check()) { STATIC_ASSERT(kHeapObjectTag == 1); // If the input is a HeapObject, SmiUntag will set the carry flag. __ SmiUntag(result, input, SetCC); DeoptimizeIf(cs, instr->environment()); } else { __ SmiUntag(result, input); } } void LCodeGen::EmitNumberUntagD(Register input_reg, DwVfpRegister result_reg, bool deoptimize_on_undefined, bool deoptimize_on_minus_zero, LEnvironment* env, NumberUntagDMode mode) { Register scratch = scratch0(); SwVfpRegister flt_scratch = double_scratch0().low(); ASSERT(!result_reg.is(double_scratch0())); Label load_smi, heap_number, done; if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) { // Smi check. __ UntagAndJumpIfSmi(scratch, input_reg, &load_smi); // Heap number map check. __ ldr(scratch, FieldMemOperand(input_reg, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex); __ cmp(scratch, Operand(ip)); if (deoptimize_on_undefined) { DeoptimizeIf(ne, env); } else { Label heap_number; __ b(eq, &heap_number); __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); __ cmp(input_reg, Operand(ip)); DeoptimizeIf(ne, env); // Convert undefined to NaN. __ LoadRoot(ip, Heap::kNanValueRootIndex); __ sub(ip, ip, Operand(kHeapObjectTag)); __ vldr(result_reg, ip, HeapNumber::kValueOffset); __ jmp(&done); __ bind(&heap_number); } // Heap number to double register conversion. __ sub(ip, input_reg, Operand(kHeapObjectTag)); __ vldr(result_reg, ip, HeapNumber::kValueOffset); if (deoptimize_on_minus_zero) { __ vmov(ip, result_reg.low()); __ cmp(ip, Operand::Zero()); __ b(ne, &done); __ vmov(ip, result_reg.high()); __ cmp(ip, Operand(HeapNumber::kSignMask)); DeoptimizeIf(eq, env); } __ jmp(&done); } else if (mode == NUMBER_CANDIDATE_IS_SMI_OR_HOLE) { __ SmiUntag(scratch, input_reg, SetCC); DeoptimizeIf(cs, env); } else if (mode == NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE) { __ UntagAndJumpIfSmi(scratch, input_reg, &load_smi); __ Vmov(result_reg, FixedDoubleArray::hole_nan_as_double(), no_reg); __ b(&done); } else { __ SmiUntag(scratch, input_reg); ASSERT(mode == NUMBER_CANDIDATE_IS_SMI); } // Smi to double register conversion __ bind(&load_smi); // scratch: untagged value of input_reg __ vmov(flt_scratch, scratch); __ vcvt_f64_s32(result_reg, flt_scratch); __ bind(&done); } void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) { Register input_reg = ToRegister(instr->value()); Register scratch1 = scratch0(); Register scratch2 = ToRegister(instr->temp()); DwVfpRegister double_scratch = double_scratch0(); DwVfpRegister double_scratch2 = ToDoubleRegister(instr->temp3()); ASSERT(!scratch1.is(input_reg) && !scratch1.is(scratch2)); ASSERT(!scratch2.is(input_reg) && !scratch2.is(scratch1)); Label done; // The input was optimistically untagged; revert it. // The carry flag is set when we reach this deferred code as we just executed // SmiUntag(heap_object, SetCC) STATIC_ASSERT(kHeapObjectTag == 1); __ adc(input_reg, input_reg, Operand(input_reg)); // Heap number map check. __ ldr(scratch1, FieldMemOperand(input_reg, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex); __ cmp(scratch1, Operand(ip)); if (instr->truncating()) { Register scratch3 = ToRegister(instr->temp2()); ASSERT(!scratch3.is(input_reg) && !scratch3.is(scratch1) && !scratch3.is(scratch2)); // Performs a truncating conversion of a floating point number as used by // the JS bitwise operations. Label heap_number; __ b(eq, &heap_number); // Check for undefined. Undefined is converted to zero for truncating // conversions. __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); __ cmp(input_reg, Operand(ip)); DeoptimizeIf(ne, instr->environment()); __ mov(input_reg, Operand::Zero()); __ b(&done); __ bind(&heap_number); __ sub(scratch1, input_reg, Operand(kHeapObjectTag)); __ vldr(double_scratch2, scratch1, HeapNumber::kValueOffset); __ ECMAToInt32(input_reg, double_scratch2, scratch1, scratch2, scratch3, double_scratch); } else { // Deoptimize if we don't have a heap number. DeoptimizeIf(ne, instr->environment()); __ sub(ip, input_reg, Operand(kHeapObjectTag)); __ vldr(double_scratch, ip, HeapNumber::kValueOffset); __ TryDoubleToInt32Exact(input_reg, double_scratch, double_scratch2); DeoptimizeIf(ne, instr->environment()); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ cmp(input_reg, Operand::Zero()); __ b(ne, &done); __ vmov(scratch1, double_scratch.high()); __ tst(scratch1, Operand(HeapNumber::kSignMask)); DeoptimizeIf(ne, instr->environment()); } } __ bind(&done); } void LCodeGen::DoTaggedToI(LTaggedToI* instr) { class DeferredTaggedToI: public LDeferredCode { public: DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredTaggedToI(instr_); } virtual LInstruction* instr() { return instr_; } private: LTaggedToI* instr_; }; LOperand* input = instr->value(); ASSERT(input->IsRegister()); ASSERT(input->Equals(instr->result())); Register input_reg = ToRegister(input); DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr); // Optimistically untag the input. // If the input is a HeapObject, SmiUntag will set the carry flag. __ SmiUntag(input_reg, SetCC); // Branch to deferred code if the input was tagged. // The deferred code will take care of restoring the tag. __ b(cs, deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) { LOperand* input = instr->value(); ASSERT(input->IsRegister()); LOperand* result = instr->result(); ASSERT(result->IsDoubleRegister()); Register input_reg = ToRegister(input); DwVfpRegister result_reg = ToDoubleRegister(result); NumberUntagDMode mode = NUMBER_CANDIDATE_IS_ANY_TAGGED; HValue* value = instr->hydrogen()->value(); if (value->type().IsSmi()) { if (value->IsLoadKeyed()) { HLoadKeyed* load = HLoadKeyed::cast(value); if (load->UsesMustHandleHole()) { if (load->hole_mode() == ALLOW_RETURN_HOLE) { mode = NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE; } else { mode = NUMBER_CANDIDATE_IS_SMI_OR_HOLE; } } else { mode = NUMBER_CANDIDATE_IS_SMI; } } else { mode = NUMBER_CANDIDATE_IS_SMI; } } EmitNumberUntagD(input_reg, result_reg, instr->hydrogen()->deoptimize_on_undefined(), instr->hydrogen()->deoptimize_on_minus_zero(), instr->environment(), mode); } void LCodeGen::DoDoubleToI(LDoubleToI* instr) { Register result_reg = ToRegister(instr->result()); Register scratch1 = scratch0(); Register scratch2 = ToRegister(instr->temp()); DwVfpRegister double_input = ToDoubleRegister(instr->value()); DwVfpRegister double_scratch = double_scratch0(); Label done; if (instr->truncating()) { Register scratch3 = ToRegister(instr->temp2()); __ ECMAToInt32(result_reg, double_input, scratch1, scratch2, scratch3, double_scratch); } else { __ TryDoubleToInt32Exact(result_reg, double_input, double_scratch); // Deoptimize if the input wasn't a int32 (inside a double). DeoptimizeIf(ne, instr->environment()); } __ bind(&done); } void LCodeGen::DoCheckSmi(LCheckSmi* instr) { LOperand* input = instr->value(); __ tst(ToRegister(input), Operand(kSmiTagMask)); DeoptimizeIf(ne, instr->environment()); } void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) { LOperand* input = instr->value(); __ tst(ToRegister(input), Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); } void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) { Register input = ToRegister(instr->value()); Register scratch = scratch0(); __ ldr(scratch, FieldMemOperand(input, HeapObject::kMapOffset)); __ ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset)); if (instr->hydrogen()->is_interval_check()) { InstanceType first; InstanceType last; instr->hydrogen()->GetCheckInterval(&first, &last); __ cmp(scratch, Operand(first)); // If there is only one type in the interval check for equality. if (first == last) { DeoptimizeIf(ne, instr->environment()); } else { DeoptimizeIf(lo, instr->environment()); // Omit check for the last type. if (last != LAST_TYPE) { __ cmp(scratch, Operand(last)); DeoptimizeIf(hi, instr->environment()); } } } else { uint8_t mask; uint8_t tag; instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag); if (IsPowerOf2(mask)) { ASSERT(tag == 0 || IsPowerOf2(tag)); __ tst(scratch, Operand(mask)); DeoptimizeIf(tag == 0 ? ne : eq, instr->environment()); } else { __ and_(scratch, scratch, Operand(mask)); __ cmp(scratch, Operand(tag)); DeoptimizeIf(ne, instr->environment()); } } } void LCodeGen::DoCheckFunction(LCheckFunction* instr) { Register reg = ToRegister(instr->value()); Handle<JSFunction> target = instr->hydrogen()->target(); ALLOW_HANDLE_DEREF(isolate(), "smi check"); if (isolate()->heap()->InNewSpace(*target)) { Register reg = ToRegister(instr->value()); Handle<JSGlobalPropertyCell> cell = isolate()->factory()->NewJSGlobalPropertyCell(target); __ mov(ip, Operand(Handle<Object>(cell))); __ ldr(ip, FieldMemOperand(ip, JSGlobalPropertyCell::kValueOffset)); __ cmp(reg, ip); } else { __ cmp(reg, Operand(target)); } DeoptimizeIf(ne, instr->environment()); } void LCodeGen::DoCheckMapCommon(Register map_reg, Handle<Map> map, CompareMapMode mode, LEnvironment* env) { Label success; __ CompareMap(map_reg, map, &success, mode); DeoptimizeIf(ne, env); __ bind(&success); } void LCodeGen::DoCheckMaps(LCheckMaps* instr) { Register map_reg = scratch0(); LOperand* input = instr->value(); ASSERT(input->IsRegister()); Register reg = ToRegister(input); Label success; SmallMapList* map_set = instr->hydrogen()->map_set(); __ ldr(map_reg, FieldMemOperand(reg, HeapObject::kMapOffset)); for (int i = 0; i < map_set->length() - 1; i++) { Handle<Map> map = map_set->at(i); __ CompareMap(map_reg, map, &success, REQUIRE_EXACT_MAP); __ b(eq, &success); } Handle<Map> map = map_set->last(); DoCheckMapCommon(map_reg, map, REQUIRE_EXACT_MAP, instr->environment()); __ bind(&success); } void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) { DwVfpRegister value_reg = ToDoubleRegister(instr->unclamped()); Register result_reg = ToRegister(instr->result()); DwVfpRegister temp_reg = ToDoubleRegister(instr->temp()); __ ClampDoubleToUint8(result_reg, value_reg, temp_reg); } void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) { Register unclamped_reg = ToRegister(instr->unclamped()); Register result_reg = ToRegister(instr->result()); __ ClampUint8(result_reg, unclamped_reg); } void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) { Register scratch = scratch0(); Register input_reg = ToRegister(instr->unclamped()); Register result_reg = ToRegister(instr->result()); DwVfpRegister temp_reg = ToDoubleRegister(instr->temp()); Label is_smi, done, heap_number; // Both smi and heap number cases are handled. __ UntagAndJumpIfSmi(result_reg, input_reg, &is_smi); // Check for heap number __ ldr(scratch, FieldMemOperand(input_reg, HeapObject::kMapOffset)); __ cmp(scratch, Operand(factory()->heap_number_map())); __ b(eq, &heap_number); // Check for undefined. Undefined is converted to zero for clamping // conversions. __ cmp(input_reg, Operand(factory()->undefined_value())); DeoptimizeIf(ne, instr->environment()); __ mov(result_reg, Operand::Zero()); __ jmp(&done); // Heap number __ bind(&heap_number); __ vldr(double_scratch0(), FieldMemOperand(input_reg, HeapNumber::kValueOffset)); __ ClampDoubleToUint8(result_reg, double_scratch0(), temp_reg); __ jmp(&done); // smi __ bind(&is_smi); __ ClampUint8(result_reg, result_reg); __ bind(&done); } void LCodeGen::DoCheckPrototypeMaps(LCheckPrototypeMaps* instr) { Register prototype_reg = ToRegister(instr->temp()); Register map_reg = ToRegister(instr->temp2()); ZoneList<Handle<JSObject> >* prototypes = instr->prototypes(); ZoneList<Handle<Map> >* maps = instr->maps(); ASSERT(prototypes->length() == maps->length()); if (instr->hydrogen()->CanOmitPrototypeChecks()) { for (int i = 0; i < maps->length(); i++) { prototype_maps_.Add(maps->at(i), info()->zone()); } } else { for (int i = 0; i < prototypes->length(); i++) { __ LoadHeapObject(prototype_reg, prototypes->at(i)); __ ldr(map_reg, FieldMemOperand(prototype_reg, HeapObject::kMapOffset)); DoCheckMapCommon(map_reg, maps->at(i), ALLOW_ELEMENT_TRANSITION_MAPS, instr->environment()); } } } void LCodeGen::DoAllocateObject(LAllocateObject* instr) { class DeferredAllocateObject: public LDeferredCode { public: DeferredAllocateObject(LCodeGen* codegen, LAllocateObject* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredAllocateObject(instr_); } virtual LInstruction* instr() { return instr_; } private: LAllocateObject* instr_; }; DeferredAllocateObject* deferred = new(zone()) DeferredAllocateObject(this, instr); Register result = ToRegister(instr->result()); Register scratch = ToRegister(instr->temp()); Register scratch2 = ToRegister(instr->temp2()); Handle<JSFunction> constructor = instr->hydrogen()->constructor(); Handle<Map> initial_map = instr->hydrogen()->constructor_initial_map(); int instance_size = initial_map->instance_size(); ASSERT(initial_map->pre_allocated_property_fields() + initial_map->unused_property_fields() - initial_map->inobject_properties() == 0); __ Allocate(instance_size, result, scratch, scratch2, deferred->entry(), TAG_OBJECT); __ bind(deferred->exit()); if (FLAG_debug_code) { Label is_in_new_space; __ JumpIfInNewSpace(result, scratch, &is_in_new_space); __ Abort("Allocated object is not in new-space"); __ bind(&is_in_new_space); } // Load the initial map. Register map = scratch; __ LoadHeapObject(map, constructor); __ ldr(map, FieldMemOperand(map, JSFunction::kPrototypeOrInitialMapOffset)); // Initialize map and fields of the newly allocated object. ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE); __ str(map, FieldMemOperand(result, JSObject::kMapOffset)); __ LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex); __ str(scratch, FieldMemOperand(result, JSObject::kElementsOffset)); __ str(scratch, FieldMemOperand(result, JSObject::kPropertiesOffset)); if (initial_map->inobject_properties() != 0) { __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); for (int i = 0; i < initial_map->inobject_properties(); i++) { int property_offset = JSObject::kHeaderSize + i * kPointerSize; __ str(scratch, FieldMemOperand(result, property_offset)); } } } void LCodeGen::DoDeferredAllocateObject(LAllocateObject* instr) { Register result = ToRegister(instr->result()); Handle<Map> initial_map = instr->hydrogen()->constructor_initial_map(); int instance_size = initial_map->instance_size(); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ mov(result, Operand::Zero()); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); __ mov(r0, Operand(Smi::FromInt(instance_size))); __ push(r0); CallRuntimeFromDeferred(Runtime::kAllocateInNewSpace, 1, instr); __ StoreToSafepointRegisterSlot(r0, result); } void LCodeGen::DoAllocate(LAllocate* instr) { class DeferredAllocate: public LDeferredCode { public: DeferredAllocate(LCodeGen* codegen, LAllocate* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredAllocate(instr_); } virtual LInstruction* instr() { return instr_; } private: LAllocate* instr_; }; DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr); Register result = ToRegister(instr->result()); Register scratch = ToRegister(instr->temp1()); Register scratch2 = ToRegister(instr->temp2()); // Allocate memory for the object. AllocationFlags flags = TAG_OBJECT; if (instr->hydrogen()->MustAllocateDoubleAligned()) { flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT); } if (instr->hydrogen()->CanAllocateInOldPointerSpace()) { flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE); } if (instr->size()->IsConstantOperand()) { int32_t size = ToInteger32(LConstantOperand::cast(instr->size())); __ Allocate(size, result, scratch, scratch2, deferred->entry(), flags); } else { Register size = ToRegister(instr->size()); __ Allocate(size, result, scratch, scratch2, deferred->entry(), flags); } __ bind(deferred->exit()); } void LCodeGen::DoDeferredAllocate(LAllocate* instr) { Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ mov(result, Operand(Smi::FromInt(0))); PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); if (instr->size()->IsRegister()) { Register size = ToRegister(instr->size()); ASSERT(!size.is(result)); __ SmiTag(size); __ push(size); } else { int32_t size = ToInteger32(LConstantOperand::cast(instr->size())); __ Push(Smi::FromInt(size)); } if (instr->hydrogen()->CanAllocateInOldPointerSpace()) { CallRuntimeFromDeferred( Runtime::kAllocateInOldPointerSpace, 1, instr); } else { CallRuntimeFromDeferred( Runtime::kAllocateInNewSpace, 1, instr); } __ StoreToSafepointRegisterSlot(r0, result); } void LCodeGen::DoToFastProperties(LToFastProperties* instr) { ASSERT(ToRegister(instr->value()).is(r0)); __ push(r0); CallRuntime(Runtime::kToFastProperties, 1, instr); } void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) { Label materialized; // Registers will be used as follows: // r7 = literals array. // r1 = regexp literal. // r0 = regexp literal clone. // r2 and r4-r6 are used as temporaries. int literal_offset = FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index()); __ LoadHeapObject(r7, instr->hydrogen()->literals()); __ ldr(r1, FieldMemOperand(r7, literal_offset)); __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); __ cmp(r1, ip); __ b(ne, &materialized); // Create regexp literal using runtime function // Result will be in r0. __ mov(r6, Operand(Smi::FromInt(instr->hydrogen()->literal_index()))); __ mov(r5, Operand(instr->hydrogen()->pattern())); __ mov(r4, Operand(instr->hydrogen()->flags())); __ Push(r7, r6, r5, r4); CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr); __ mov(r1, r0); __ bind(&materialized); int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize; Label allocated, runtime_allocate; __ Allocate(size, r0, r2, r3, &runtime_allocate, TAG_OBJECT); __ jmp(&allocated); __ bind(&runtime_allocate); __ mov(r0, Operand(Smi::FromInt(size))); __ Push(r1, r0); CallRuntime(Runtime::kAllocateInNewSpace, 1, instr); __ pop(r1); __ bind(&allocated); // Copy the content into the newly allocated memory. __ CopyFields(r0, r1, double_scratch0(), double_scratch0().low(), size / kPointerSize); } void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) { // Use the fast case closure allocation code that allocates in new // space for nested functions that don't need literals cloning. bool pretenure = instr->hydrogen()->pretenure(); if (!pretenure && instr->hydrogen()->has_no_literals()) { FastNewClosureStub stub(instr->hydrogen()->language_mode(), instr->hydrogen()->is_generator()); __ mov(r1, Operand(instr->hydrogen()->shared_info())); __ push(r1); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); } else { __ mov(r2, Operand(instr->hydrogen()->shared_info())); __ mov(r1, Operand(pretenure ? factory()->true_value() : factory()->false_value())); __ Push(cp, r2, r1); CallRuntime(Runtime::kNewClosure, 3, instr); } } void LCodeGen::DoTypeof(LTypeof* instr) { Register input = ToRegister(instr->value()); __ push(input); CallRuntime(Runtime::kTypeof, 1, instr); } void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) { Register input = ToRegister(instr->value()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition final_branch_condition = EmitTypeofIs(true_label, false_label, input, instr->type_literal()); if (final_branch_condition != kNoCondition) { EmitBranch(true_block, false_block, final_branch_condition); } } Condition LCodeGen::EmitTypeofIs(Label* true_label, Label* false_label, Register input, Handle<String> type_name) { Condition final_branch_condition = kNoCondition; Register scratch = scratch0(); if (type_name->Equals(heap()->number_string())) { __ JumpIfSmi(input, true_label); __ ldr(input, FieldMemOperand(input, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex); __ cmp(input, Operand(ip)); final_branch_condition = eq; } else if (type_name->Equals(heap()->string_string())) { __ JumpIfSmi(input, false_label); __ CompareObjectType(input, input, scratch, FIRST_NONSTRING_TYPE); __ b(ge, false_label); __ ldrb(ip, FieldMemOperand(input, Map::kBitFieldOffset)); __ tst(ip, Operand(1 << Map::kIsUndetectable)); final_branch_condition = eq; } else if (type_name->Equals(heap()->symbol_string())) { __ JumpIfSmi(input, false_label); __ CompareObjectType(input, input, scratch, SYMBOL_TYPE); final_branch_condition = eq; } else if (type_name->Equals(heap()->boolean_string())) { __ CompareRoot(input, Heap::kTrueValueRootIndex); __ b(eq, true_label); __ CompareRoot(input, Heap::kFalseValueRootIndex); final_branch_condition = eq; } else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_string())) { __ CompareRoot(input, Heap::kNullValueRootIndex); final_branch_condition = eq; } else if (type_name->Equals(heap()->undefined_string())) { __ CompareRoot(input, Heap::kUndefinedValueRootIndex); __ b(eq, true_label); __ JumpIfSmi(input, false_label); // Check for undetectable objects => true. __ ldr(input, FieldMemOperand(input, HeapObject::kMapOffset)); __ ldrb(ip, FieldMemOperand(input, Map::kBitFieldOffset)); __ tst(ip, Operand(1 << Map::kIsUndetectable)); final_branch_condition = ne; } else if (type_name->Equals(heap()->function_string())) { STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); __ JumpIfSmi(input, false_label); __ CompareObjectType(input, scratch, input, JS_FUNCTION_TYPE); __ b(eq, true_label); __ cmp(input, Operand(JS_FUNCTION_PROXY_TYPE)); final_branch_condition = eq; } else if (type_name->Equals(heap()->object_string())) { __ JumpIfSmi(input, false_label); if (!FLAG_harmony_typeof) { __ CompareRoot(input, Heap::kNullValueRootIndex); __ b(eq, true_label); } __ CompareObjectType(input, input, scratch, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE); __ b(lt, false_label); __ CompareInstanceType(input, scratch, LAST_NONCALLABLE_SPEC_OBJECT_TYPE); __ b(gt, false_label); // Check for undetectable objects => false. __ ldrb(ip, FieldMemOperand(input, Map::kBitFieldOffset)); __ tst(ip, Operand(1 << Map::kIsUndetectable)); final_branch_condition = eq; } else { __ b(false_label); } return final_branch_condition; } void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) { Register temp1 = ToRegister(instr->temp()); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); EmitIsConstructCall(temp1, scratch0()); EmitBranch(true_block, false_block, eq); } void LCodeGen::EmitIsConstructCall(Register temp1, Register temp2) { ASSERT(!temp1.is(temp2)); // Get the frame pointer for the calling frame. __ ldr(temp1, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); // Skip the arguments adaptor frame if it exists. Label check_frame_marker; __ ldr(temp2, MemOperand(temp1, StandardFrameConstants::kContextOffset)); __ cmp(temp2, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); __ b(ne, &check_frame_marker); __ ldr(temp1, MemOperand(temp1, StandardFrameConstants::kCallerFPOffset)); // Check the marker in the calling frame. __ bind(&check_frame_marker); __ ldr(temp1, MemOperand(temp1, StandardFrameConstants::kMarkerOffset)); __ cmp(temp1, Operand(Smi::FromInt(StackFrame::CONSTRUCT))); } void LCodeGen::EnsureSpaceForLazyDeopt() { if (info()->IsStub()) return; // Ensure that we have enough space after the previous lazy-bailout // instruction for patching the code here. int current_pc = masm()->pc_offset(); int patch_size = Deoptimizer::patch_size(); if (current_pc < last_lazy_deopt_pc_ + patch_size) { // Block literal pool emission for duration of padding. Assembler::BlockConstPoolScope block_const_pool(masm()); int padding_size = last_lazy_deopt_pc_ + patch_size - current_pc; ASSERT_EQ(0, padding_size % Assembler::kInstrSize); while (padding_size > 0) { __ nop(); padding_size -= Assembler::kInstrSize; } } last_lazy_deopt_pc_ = masm()->pc_offset(); } void LCodeGen::DoLazyBailout(LLazyBailout* instr) { EnsureSpaceForLazyDeopt(); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoDeoptimize(LDeoptimize* instr) { DeoptimizeIf(al, instr->environment()); } void LCodeGen::DoDummyUse(LDummyUse* instr) { // Nothing to see here, move on! } void LCodeGen::DoDeleteProperty(LDeleteProperty* instr) { Register object = ToRegister(instr->object()); Register key = ToRegister(instr->key()); Register strict = scratch0(); __ mov(strict, Operand(Smi::FromInt(strict_mode_flag()))); __ Push(object, key, strict); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoIn(LIn* instr) { Register obj = ToRegister(instr->object()); Register key = ToRegister(instr->key()); __ Push(key, obj); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator(this, pointers, Safepoint::kLazyDeopt); __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) { PushSafepointRegistersScope scope(this, Safepoint::kWithRegisters); __ CallRuntimeSaveDoubles(Runtime::kStackGuard); RecordSafepointWithLazyDeopt( instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoStackCheck(LStackCheck* instr) { class DeferredStackCheck: public LDeferredCode { public: DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); } virtual LInstruction* instr() { return instr_; } private: LStackCheck* instr_; }; ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); // There is no LLazyBailout instruction for stack-checks. We have to // prepare for lazy deoptimization explicitly here. if (instr->hydrogen()->is_function_entry()) { // Perform stack overflow check. Label done; __ LoadRoot(ip, Heap::kStackLimitRootIndex); __ cmp(sp, Operand(ip)); __ b(hs, &done); StackCheckStub stub; PredictableCodeSizeScope predictable(masm_, 2 * Assembler::kInstrSize); CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr); EnsureSpaceForLazyDeopt(); __ bind(&done); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } else { ASSERT(instr->hydrogen()->is_backwards_branch()); // Perform stack overflow check if this goto needs it before jumping. DeferredStackCheck* deferred_stack_check = new(zone()) DeferredStackCheck(this, instr); __ LoadRoot(ip, Heap::kStackLimitRootIndex); __ cmp(sp, Operand(ip)); __ b(lo, deferred_stack_check->entry()); EnsureSpaceForLazyDeopt(); __ bind(instr->done_label()); deferred_stack_check->SetExit(instr->done_label()); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); // Don't record a deoptimization index for the safepoint here. // This will be done explicitly when emitting call and the safepoint in // the deferred code. } } void LCodeGen::DoOsrEntry(LOsrEntry* instr) { // This is a pseudo-instruction that ensures that the environment here is // properly registered for deoptimization and records the assembler's PC // offset. LEnvironment* environment = instr->environment(); environment->SetSpilledRegisters(instr->SpilledRegisterArray(), instr->SpilledDoubleRegisterArray()); // If the environment were already registered, we would have no way of // backpatching it with the spill slot operands. ASSERT(!environment->HasBeenRegistered()); RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(osr_pc_offset_ == -1); osr_pc_offset_ = masm()->pc_offset(); } void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) { __ LoadRoot(ip, Heap::kUndefinedValueRootIndex); __ cmp(r0, ip); DeoptimizeIf(eq, instr->environment()); Register null_value = r5; __ LoadRoot(null_value, Heap::kNullValueRootIndex); __ cmp(r0, null_value); DeoptimizeIf(eq, instr->environment()); __ tst(r0, Operand(kSmiTagMask)); DeoptimizeIf(eq, instr->environment()); STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE); __ CompareObjectType(r0, r1, r1, LAST_JS_PROXY_TYPE); DeoptimizeIf(le, instr->environment()); Label use_cache, call_runtime; __ CheckEnumCache(null_value, &call_runtime); __ ldr(r0, FieldMemOperand(r0, HeapObject::kMapOffset)); __ b(&use_cache); // Get the set of properties to enumerate. __ bind(&call_runtime); __ push(r0); CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr); __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset)); __ LoadRoot(ip, Heap::kMetaMapRootIndex); __ cmp(r1, ip); DeoptimizeIf(ne, instr->environment()); __ bind(&use_cache); } void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) { Register map = ToRegister(instr->map()); Register result = ToRegister(instr->result()); Label load_cache, done; __ EnumLength(result, map); __ cmp(result, Operand(Smi::FromInt(0))); __ b(ne, &load_cache); __ mov(result, Operand(isolate()->factory()->empty_fixed_array())); __ jmp(&done); __ bind(&load_cache); __ LoadInstanceDescriptors(map, result); __ ldr(result, FieldMemOperand(result, DescriptorArray::kEnumCacheOffset)); __ ldr(result, FieldMemOperand(result, FixedArray::SizeFor(instr->idx()))); __ cmp(result, Operand::Zero()); DeoptimizeIf(eq, instr->environment()); __ bind(&done); } void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) { Register object = ToRegister(instr->value()); Register map = ToRegister(instr->map()); __ ldr(scratch0(), FieldMemOperand(object, HeapObject::kMapOffset)); __ cmp(map, scratch0()); DeoptimizeIf(ne, instr->environment()); } void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) { Register object = ToRegister(instr->object()); Register index = ToRegister(instr->index()); Register result = ToRegister(instr->result()); Register scratch = scratch0(); Label out_of_object, done; __ cmp(index, Operand::Zero()); __ b(lt, &out_of_object); STATIC_ASSERT(kPointerSizeLog2 > kSmiTagSize); __ add(scratch, object, Operand(index, LSL, kPointerSizeLog2 - kSmiTagSize)); __ ldr(result, FieldMemOperand(scratch, JSObject::kHeaderSize)); __ b(&done); __ bind(&out_of_object); __ ldr(result, FieldMemOperand(object, JSObject::kPropertiesOffset)); // Index is equal to negated out of object property index plus 1. __ sub(scratch, result, Operand(index, LSL, kPointerSizeLog2 - kSmiTagSize)); __ ldr(result, FieldMemOperand(scratch, FixedArray::kHeaderSize - kPointerSize)); __ bind(&done); } #undef __ } } // namespace v8::internal
[ "george.bungarzescu@gmail.com" ]
george.bungarzescu@gmail.com
05996d0b86c8e06d201a029a2ec9d8157f84d30e
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/media/base/video_decoder.h
5a474b56e21ebdc8177edc6cb351e98c7790f108
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
5,402
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_VIDEO_DECODER_H_ #define MEDIA_BASE_VIDEO_DECODER_H_ #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "media/base/decode_status.h" #include "media/base/media_export.h" #include "media/base/pipeline_status.h" #include "ui/gfx/geometry/size.h" namespace media { class CdmContext; class DecoderBuffer; class VideoDecoderConfig; class VideoFrame; class MEDIA_EXPORT VideoDecoder { public: // Callback for VideoDecoder initialization. typedef base::Callback<void(bool success)> InitCB; // Callback for VideoDecoder to return a decoded frame whenever it becomes // available. Only non-EOS frames should be returned via this callback. typedef base::Callback<void(const scoped_refptr<VideoFrame>&)> OutputCB; // Callback type for Decode(). Called after the decoder has completed decoding // corresponding DecoderBuffer, indicating that it's ready to accept another // buffer to decode. typedef base::Callback<void(DecodeStatus)> DecodeCB; VideoDecoder(); // Fires any pending callbacks, stops and destroys the decoder. // Note: Since this is a destructor, |this| will be destroyed after this call. // Make sure the callbacks fired from this call doesn't post any task that // depends on |this|. virtual ~VideoDecoder(); // Returns the name of the decoder for logging purpose. virtual std::string GetDisplayName() const = 0; // Initializes a VideoDecoder with the given |config|, executing the // |init_cb| upon completion. |output_cb| is called for each output frame // decoded by Decode(). // // If |low_delay| is true then the decoder is not allowed to queue frames, // except for out-of-order frames, i.e. if the next frame can be returned it // must be returned without waiting for Decode() to be called again. // Initialization should fail if |low_delay| is true and the decoder cannot // satisfy the requirements above. // // |cdm_context| can be used to handle encrypted buffers. May be null if the // stream is not encrypted. // // Note: // 1) The VideoDecoder will be reinitialized if it was initialized before. // Upon reinitialization, all internal buffered frames will be dropped. // 2) This method should not be called during pending decode or reset. // 3) No VideoDecoder calls should be made before |init_cb| is executed. // 4) VideoDecoders should take care to run |output_cb| as soon as the frame // is ready (i.e. w/o thread trampolining) since it can strongly affect frame // delivery times with high-frame-rate material. See Decode() for additional // notes. virtual void Initialize(const VideoDecoderConfig& config, bool low_delay, CdmContext* cdm_context, const InitCB& init_cb, const OutputCB& output_cb) = 0; // Requests a |buffer| to be decoded. The status of the decoder and decoded // frame are returned via the provided callback. Some decoders may allow // decoding multiple buffers in parallel. Callers should call // GetMaxDecodeRequests() to get number of buffers that may be decoded in // parallel. Decoder must call |decode_cb| in the same order in which Decode() // is called. // // Implementations guarantee that the callback will not be called from within // this method and that |decode_cb| will not be blocked on the following // Decode() calls (i.e. |decode_cb| will be called even if Decode() is never // called again). // // After decoding is finished the decoder calls |output_cb| specified in // Initialize() for each decoded frame. |output_cb| is always called before // |decode_cb|. However, |output_cb| may be called before Decode() returns, if // other behavior is desired callers should ensure that |output_cb| will // trampoline as necessary. // // If |buffer| is an EOS buffer then the decoder must be flushed, i.e. // |output_cb| must be called for each frame pending in the queue and // |decode_cb| must be called after that. Callers will not call Decode() // again until after the flush completes. virtual void Decode(const scoped_refptr<DecoderBuffer>& buffer, const DecodeCB& decode_cb) = 0; // Resets decoder state. All pending Decode() requests will be finished or // aborted before |closure| is called. // Note: No VideoDecoder calls should be made before |closure| is executed. virtual void Reset(const base::Closure& closure) = 0; // Returns true if the decoder needs bitstream conversion before decoding. virtual bool NeedsBitstreamConversion() const; // Returns true if the decoder currently has the ability to decode and return // a VideoFrame. Most implementations can allocate a new VideoFrame and hence // this will always return true. Override and return false for decoders that // use a fixed set of VideoFrames for decoding. virtual bool CanReadWithoutStalling() const; // Returns maximum number of parallel decode requests. virtual int GetMaxDecodeRequests() const; private: DISALLOW_COPY_AND_ASSIGN(VideoDecoder); }; } // namespace media #endif // MEDIA_BASE_VIDEO_DECODER_H_
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
239c9c1c1ed64e8b1ebcac64053be306df4e4c5a
e567f7cdc6cf2ddd7e8a21c3b76a70be3907c292
/uva-350.cpp
a3a0bc693dcc6fd9cd0e53fac595d8c60f1e1ab6
[]
no_license
Ripon440/uva-solutions
3a1a154e45019086fed727744b28fb09ef2ce230
f37f10b7266fc216aa2bac90c01d8fed04a4116d
refs/heads/master
2022-05-24T19:58:28.133855
2020-05-02T07:03:29
2020-05-02T07:03:29
260,631,248
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include<iostream> using namespace std; int main() { int Z, I, M, L; int caseNumber = 0; //insert input while(cin >> Z >> I >> M >> L) { caseNumber++;//increment case number if( Z == 0 && I == 0 && M == 0 && L == 0) break; int maps[M] = {0};//assign all element of the array is 0 int cycleLength = 0;//assign cycle length 0 int seed = L;// assign first one is seed while(1) { L = (Z * L + I) % M;//determine new seed by equation if(seed == L)// if seed == L , the cycle is found { break; } else if(maps[L]) // if maps[L] == 1, then the cycle already began { break; } maps[L] = 1;// mark the maps[L] to true, that means the seed already determined seed = L;//assign new L to seed cycleLength++;//increment cycle length } cout << "Case "<< caseNumber << ": " << cycleLength << endl; } return 0; }
[ "torikulislam697@gmail.com" ]
torikulislam697@gmail.com
5df1be82fbc2f3db85fe0c42b311e4223ce3e294
120cf10a541b4462cacbfb81b1263b3675f99e97
/src/qtjson_exception.cpp
cf43fde1e8ef1470c2f299b268adb00c011876a6
[ "MIT" ]
permissive
xishuai416/qt-json-1
65b7173b4d4f351dd6f56a1e6116c08016ea6ba7
aab888bc3d0878d7c13411e4445616e69ca81842
refs/heads/master
2023-03-16T00:42:13.275190
2020-05-20T15:36:32
2020-05-20T15:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,504
cpp
#include "qtjson_exception.h" using namespace QtJson; const char *Exception::what() const noexcept { return _what.constData(); } void Exception::raise() const { throw *this; } ExceptionBase *Exception::clone() const { return new Exception{*this}; } Exception::Exception(QByteArray what) : _what{std::move(what)} {} InvalidValueTypeException::InvalidValueTypeException(QJsonValue::Type actual, const QList<QJsonValue::Type> &expected) : Exception{ "Unabled to deserialize JSON value of type " + typeName(actual) + (expected.isEmpty() ? QByteArray{} : " - expected type to be one of: " + join(expected)) } {} InvalidValueTypeException::InvalidValueTypeException(QCborValue::Type actual, const QList<QCborValue::Type> &expected) : Exception{ "Unabled to deserialize CBOR value of type " + typeName(actual) + (expected.isEmpty() ? QByteArray{} : " - expected type to be one of: " + join(expected)) } {} void InvalidValueTypeException::raise() const { throw *this; } ExceptionBase *InvalidValueTypeException::clone() const { return new InvalidValueTypeException{*this}; } QByteArray InvalidValueTypeException::typeName(QJsonValue::Type type) { switch (type) { case QJsonValue::Null: return "null"; case QJsonValue::Bool: return "bool"; case QJsonValue::Double: return "double"; case QJsonValue::String: return "string"; case QJsonValue::Array: return "array"; case QJsonValue::Object: return "object"; case QJsonValue::Undefined: return "undefined"; default: Q_UNREACHABLE(); } } QByteArray InvalidValueTypeException::typeName(QCborValue::Type type) { switch (type) { case QCborValue::Integer: return "integer"; case QCborValue::ByteArray: return "bytearray"; case QCborValue::String: return "string"; case QCborValue::Array: return "array"; case QCborValue::Map: return "map"; case QCborValue::Tag: return "tag"; case QCborValue::SimpleType: return "simple"; case QCborValue::False: return "false"; case QCborValue::True: return "true"; case QCborValue::Null: return "null"; case QCborValue::Undefined: return "undefined"; case QCborValue::Double: return "double"; case QCborValue::DateTime: return "datetime"; case QCborValue::Url: return "url"; case QCborValue::RegularExpression: return "regexp"; case QCborValue::Uuid: return "uuid"; case QCborValue::Invalid: return "invalid"; default: Q_UNREACHABLE(); } } InvalidValueTagException::InvalidValueTagException(QCborTag actual, const QList<QCborTag> &expected) : Exception{ "Unexpected CBOR-Tag " + QByteArray::number(static_cast<std::underlying_type_t<QCborTag>>(actual)) + (expected.isEmpty() ? QByteArray{} : " - expected tag to be one of: " + join(expected)) } {} void InvalidValueTagException::raise() const { throw *this; } ExceptionBase *InvalidValueTagException::clone() const { return new InvalidValueTagException{*this}; } InvalidPropertyValueException::InvalidPropertyValueException(const QMetaProperty &property, const QVariant &value) : Exception{ QByteArrayLiteral("Unabled to set property ") + property.name() + " off " + property.enclosingMetaObject()->className() + ": Variant of type \"" + value.typeName() + "\" cannot be convert to \"" + property.typeName() + "\"" } {} InvalidPropertyValueException::InvalidPropertyValueException(const QMetaProperty &property, const QJsonValue &value) : Exception{ QByteArrayLiteral("Unabled to set property ") + property.name() + " off " + property.enclosingMetaObject()->className() + ": Variant of type " + QByteArray::number(value.type()) + " cannot be convert to \"" + property.typeName() + "\"" } {} InvalidPropertyValueException::InvalidPropertyValueException(const QMetaProperty &property, const QCborValue &value) : Exception{ QByteArrayLiteral("Unabled to set property ") + property.name() + " of " + property.enclosingMetaObject()->className() + ": Variant of type " + QByteArray::number(value.type()) + (value.isTag() ? " (Tag: " + QByteArray::number(static_cast<quint64>(value.tag())) + ")" : QByteArray{}) + " cannot be convert to \"" + property.typeName() + "\"" } {} void InvalidPropertyValueException::raise() const { throw *this; } ExceptionBase *InvalidPropertyValueException::clone() const { return new InvalidPropertyValueException{*this}; } InvalidPropertyMethodCallException::InvalidPropertyMethodCallException(const QMetaProperty &property, const QMetaMethod &method) : Exception{ QByteArrayLiteral("Failed to invoke meta method \"") + method.methodSignature() + "\" for property " + property.name() + " on gadget of type " + property.enclosingMetaObject()->className() } {} void InvalidPropertyMethodCallException::raise() const { throw *this; } ExceptionBase *InvalidPropertyMethodCallException::clone() const { return new InvalidPropertyMethodCallException{*this}; } ValidationFailureException::ValidationFailureException(const QMetaProperty &property) : Exception{ QByteArrayLiteral("Property ") + property.name() + " of " + property.enclosingMetaObject()->className() + " is missing in given JSON/CBOR map" } {} ValidationFailureException::ValidationFailureException(const QMetaObject *metaObject, const QStringList &extra) : Exception { QByteArrayLiteral("Found ") + QByteArray::number(extra.size()) + " additional values in given JSON/CBOR, but they are not declared for " + metaObject->className() + " - the keys of these values are: " + extra.join(QStringLiteral(", ")).toUtf8() } {} void ValidationFailureException::raise() const { throw *this; } ExceptionBase *ValidationFailureException::clone() const { return new ValidationFailureException{*this}; } InvalidDataException::InvalidDataException() : Exception{"Got unexpected invalid CBOR/JSON data! Unable to continue serialization"} {} void InvalidDataException::raise() const { throw *this; } ExceptionBase *InvalidDataException::clone() const { return new InvalidDataException{*this}; } JsonParseException::JsonParseException(const QJsonParseError &error) : Exception{ "Failed to parse JSON data at position " + QByteArray::number(error.offset) + " with error: " + error.errorString().toUtf8() } {} void JsonParseException::raise() const { throw *this; } ExceptionBase *JsonParseException::clone() const { return new JsonParseException{*this}; } CborParseException::CborParseException(const QByteArray &signature) : Exception{ "Unable to parse CBOR data - expected signature to be 0xd9d9f7, but was 0x" + signature.toHex().toLower() } {} CborParseException::CborParseException(const QCborParserError &error) : Exception{ "Failed to parse CBOR data at position " + QByteArray::number(error.offset) + " with error: " + error.errorString().toUtf8() } {} void CborParseException::raise() const { throw *this; } ExceptionBase *CborParseException::clone() const { return new CborParseException{*this}; }
[ "Skycoder42@users.noreply.github.com" ]
Skycoder42@users.noreply.github.com
fd440dc3600e00a348c8a5e43317aadc95dd5a11
9b922c0d2f69cb23b9abc4b5852e697d82ffdcbb
/VirtualReality/Lab1/main.cpp
a269e52cfb93e05933c7556d811a3f82e73fb060
[]
no_license
dannoane/Faculty
12399d7c67926c23ccd4997600cb6553f5425d8f
9716168967e7d05b6e68d15ba769282b4cf03c4c
refs/heads/master
2021-09-27T13:03:31.813345
2018-11-08T18:24:23
2018-11-08T18:24:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,554
cpp
#include <cmath> #include <iostream> #include <string> #include "Vector.hpp" #include "Line.hpp" #include "Geometry.hpp" #include "Sphere.hpp" #include "Image.hpp" #include "Color.hpp" #include "Intersection.hpp" #include "Material.hpp" #include "stdio.h" #include "Scene.hpp" using namespace std; using namespace rt; double imageToViewPlane(int n, int imgSize, double viewPlaneSize) { double u = (double) n * viewPlaneSize / (double) imgSize; u -= viewPlaneSize / 2; return u; } const Intersection findFirstIntersection(const Line& ray, double minDist, double maxDist) { Intersection intersection; for (int i = 0; i < geometryCount; ++i) { Intersection in = scene[i]->getIntersection(ray, minDist, maxDist); if (in.valid()) { if (!intersection.valid()) { intersection = in; } else if (in.t() < intersection.t()) { intersection = in; } } } return intersection; } int main() { Vector viewPoint(0, 0, 0); Vector viewDirection(0, 0, 1); Vector viewUp(0, -1, 0); Vector x0, x1; double viewPlaneDist = 512; double viewPlaneWidth = 1024; double viewPlaneHeight = 768; int imageWidth = 1024; int imageHeight = 768; int i, j, k; Vector viewParallel = viewUp ^ viewDirection; viewDirection.normalize(); viewUp.normalize(); viewParallel.normalize(); Image image(imageWidth, imageHeight); Color *c = new Color(0, 0, 0); Vector n, t, e, r; for (i = 0; i < imageWidth; ++i) { for (j = 0; j < imageHeight; ++j) { // background color image.setPixel(i, j, Color(0.3, 0.3, 0.3)); // camera x0 = viewPoint; // point in space x1 = viewPoint + viewDirection * viewPlaneDist + viewUp * imageToViewPlane(j, imageHeight, viewPlaneHeight) + viewParallel * imageToViewPlane(i, imageWidth, viewPlaneWidth); // line from viewpoint to point in space Line *line = new Line(x0, x1, true); Intersection intersection = findFirstIntersection(*line, 0.25 , 0.25); if (intersection.valid()) { *c = intersection.geometry()->material().ambient(); for (k = 0; k < 2; ++k) { *c *= lights[k]->ambient(); // normal to the surface n = intersection.vec() - ((Sphere *)intersection.geometry())->center(); n.normalize(); // vector from intersection to light t = lights[k]->position() - intersection.vec(); t.normalize(); if (n * t > 0) { *c += intersection.geometry()->material().diffuse()*lights[k]->diffuse()*(n * t); } // vector from intersection point to camera e = viewPoint - intersection.vec(); e.normalize(); // reflection vector r = n * 2 * (n * t) - t; r.normalize(); if(e * r > 0) { *c += intersection.geometry()->material().specular() * lights[k]->specular() * pow(e * r, intersection.geometry()->material().shininess()); } *c *= lights[k]->intensity(); } image.setPixel(i, j, *c); } } } image.store("scene.png"); for (int i = 0; i < geometryCount; i++) { delete scene[i]; } return 0; }
[ "Noane.Dan@outlook.com" ]
Noane.Dan@outlook.com
384a0c2b6cbe8b9206855a0dc064863343d4c64a
cb76dcee2f0530d461bb4231d8ad308039b79fd8
/cpp/test_atomic/order_acquire_release.cpp
706a3c3ac156368059ee6efbe60e538bf8ea27e5
[]
no_license
lvHiei/LearnAndTest
b9c3e5ef23bba46f4f7024d13a8b53931176bb3f
c1bd16bd94cdc2ebfc9a79b545e6ce1952acbd3b
refs/heads/master
2021-06-24T02:21:03.261729
2020-10-27T12:47:49
2020-10-27T12:47:49
130,451,933
0
0
null
null
null
null
UTF-8
C++
false
false
1,665
cpp
#include "inc.h" std::atomic<std::string*> ptr; int data; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2; while (!(p2 = ptr.load(std::memory_order_acquire))) ; assert(*p2 == "Hello"); // 绝无问题 assert(data == 42); // 绝无问题 } std::atomic<int> state; enum{ IDLE, INIT, PROCESSING, }; void thread1() { while(true){ int expect = IDLE; while(!state.compare_exchange_strong(expect, INIT,std::memory_order_acq_rel, std::memory_order_relaxed)){ LOGI("thread1 is waiting\n"); expect = IDLE; } int i = random(100, 500); std::this_thread::sleep_for(std::chrono::microseconds(i)); assert(state.load() == INIT); state.store(IDLE, std::memory_order_release); } } void thread2() { while(true){ int expect = IDLE; while(!state.compare_exchange_strong(expect, PROCESSING, std::memory_order_acq_rel, std::memory_order_relaxed)){ LOGI("thread2 is waiting\n"); expect = IDLE; } int i = random(100, 800); std::this_thread::sleep_for(std::chrono::microseconds(i)); assert(state.load() == PROCESSING); state.store(IDLE, std::memory_order_release); } } void test_memory_order_acquire_release() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); } void test_memory_order_acq_rel() { state.store(IDLE); std::thread t1(thread1); std::thread t2(thread2); t1.join(); t2.join(); }
[ "majun@mail.51vv.com" ]
majun@mail.51vv.com
39a03edbc9b85db59346de4d1d95a3f45f49d732
3a870ff0b88e62685bfb4c6e70b591da7602d7a3
/SFML/Dialogue.cpp
3b86b46ecaecdb91223b5c20548f4a4bdf2c222f
[]
no_license
denyaalpha/kursach
95bdd77e70faac2fb450cfea8c96cf1485a76d88
2a3b750d9b119e0909c3160f2e8b61fd2e81a0bb
refs/heads/master
2022-11-02T07:34:42.154135
2020-06-23T11:08:43
2020-06-23T11:08:43
274,374,666
0
0
null
null
null
null
UTF-8
C++
false
false
2,464
cpp
#include "Dialogue.h" Dialogue::Dialogue(sf::Vector2f scale) { this->scale = scale; mainBox.setFillColor(sf::Color(100, 100, 100)); mainBox.setSize(sf::Vector2f(700*scale.x, 100*scale.y)); TEXT.setFont("DisposableDroidBB"); TEXT.setColor(sf::Color::White); TEXT.setPosition(sf::Vector2f(scale.x * (207 + 10), scale.y * (460 + 10))); mainBox.setPosition(sf::Vector2f(50*scale.x, 450*scale.y)); hero.setPosition(sf::Vector2f(60*scale.x, 460*scale.y)); toSwitch = true; if (!buffer.loadFromFile("SoundEffects/DialogueRunning.wav")) std::cout << "No sound:c" << std::endl; sound.setBuffer(buffer); sound.setVolume(20); loaded = false; } bool Dialogue::loadDialogue(std::string filename) { std::ifstream textDialogue("Dialogs/" + filename + ".txt"); if (!textDialogue.is_open()) { std::cout << "dialogs error\n"; return false; } std::string replica; std::string numHero; allReplicas.push("-"); while (!textDialogue.eof()) { getline(textDialogue,replica); getline(textDialogue, numHero); allReplicas.push(replica); allHeroes.push(numHero); } loaded = true; return true; } void Dialogue::updateScale(sf::Vector2f scale) { this->scale = scale; mainBox.setSize(sf::Vector2f(700 * scale.x, 100 * scale.y)); mainBox.setPosition(sf::Vector2f(50 * scale.x, 450 * scale.y)); hero.setPosition(sf::Vector2f(60 * scale.x, 460 * scale.y)); TEXT.setPosition(sf::Vector2f(scale.x * (207 + 10), scale.y * (460 + 10))); } void Dialogue::updateDialogue() { if (!toSwitch) return; if (!loaded) return; texture.loadFromFile("Dialogs/" + allHeroes.front() +".png"); hero.setTexture(texture); hero.setScale(scale); initialPositionString = 0; allReplicas.pop(); allHeroes.pop(); TEXT.clearText(); toSwitch = false; timerMS = 0; delayMS = 0; } bool Dialogue::getToSwitch() { return toSwitch; } void Dialogue::draw(sf::RenderWindow& window) { if (!loaded) return; window.draw(mainBox); window.draw(hero); if (delayMS < 0) { delayMS++; window.draw(TEXT.getText()); return; } if (allReplicas.front()[initialPositionString] == '.') delayMS = -2000; else timerMS++; if (initialPositionString < allReplicas.front().length()) { if (!(timerMS%100)) { TEXT.addLetter(allReplicas.front()[initialPositionString++]); sound.play(); } } window.draw(TEXT.getText()); } bool Dialogue::isReplicaEmpty() { return (allReplicas.size() == 1); } void Dialogue::changeToSwitch() { toSwitch = !toSwitch; }
[ "mvch15.1.denya.lobanov1@gmail.com" ]
mvch15.1.denya.lobanov1@gmail.com
03ad89fcc55a98351d0512bc66ccd628fedad5bb
d9fe6d8dce013b01cd49406429b00e6bd94302f9
/HashMap.h
98845d17f82a396e58877e3435b625b72e6feebc
[]
no_license
jianbinghuang/sortStudy
15596167ba0147a7cb02fe439a460405df14c9f8
6a87d1eb8a53e8fe3dd42805193543c9016ff100
refs/heads/master
2020-03-20T16:21:52.540356
2019-06-06T13:03:04
2019-06-06T13:03:04
137,537,269
0
0
null
null
null
null
UTF-8
C++
false
false
2,592
h
#ifndef HASHMAP_H #define HASHMAP_H #include "System.h" #define HASHSIZE 379 template<typename KT, typename VT> struct HashNode { HashNode() : next(nullptr) {} HashNode<KT, VT>(const KT& inKey, const VT& inVal) : key(inKey), val(inVal), next(nullptr) {} KT key; KT val; HashNode<KT, VT>* next; }; inline int32_t straightHash(int32_t key) { return key; } template<typename KT, typename VT> class Bucket { public: Bucket() : _pHead(nullptr) {} typedef HashNode<KT, VT> HashNodeT; HashNodeT* find(const KT& k) { HashNodeT* pCurr = _pHead; while(pCurr && pCurr->key != k) pCurr = pCurr->next; return pCurr; } HashNodeT* insert(const KT& k, const VT& v) { HashNodeT *pPrev = nullptr, * pCurr = _pHead; while(pCurr && pCurr->key != k){ pPrev = pCurr; pCurr = pCurr->next; } if(pCurr) return pCurr; // already exists else if(pPrev){ // _pHead != nullptr HashNodeT* pNew = new HashNodeT(k, v); pPrev->next = pNew; return pNew; } else{ // _pHead == nullptr _pHead = new HashNodeT(k, v); return _pHead; } } // return true if k is found and removed, false if k is not found bool remove(const KT& k) { HashNodeT *pPrev = nullptr, * pCurr = _pHead; while(pCurr && pCurr->key != k){ pPrev = pCurr; pCurr = pCurr->next; } if(pCurr){ if(pPrev){ pPrev->next = pCurr->next; delete pCurr; } else{ _pHead = pCurr->next; delete pCurr; } return true; } else return false; } private: HashNodeT* _pHead; }; template<typename KT, typename VT> class HashMap { Bucket<KT, VT> _b[HASHSIZE]; public: typedef HashNode<KT, VT> HashNodeT; class Iterator { HashNodeT* _n; public: Iterator(HashNodeT* n) : _n(n) {} bool isValid() const { return _n != nullptr; } const KT& key() { assert(isValid()); return _n->key; } const VT& value() { assert(isValid()); return _n->value; } }; // return valid iterator if n is found, return invalid otherwise Iterator find(const KT& k) { int32_t b_idx = straightHash(k) % HASHSIZE; return Iterator(_b[b_idx].find(k)); } // If n already exists, return Iterator to the existing node Iterator insert(const KT& k, const VT& v) { int32_t b_idx = straightHash(k) % HASHSIZE; return Iterator( _b[b_idx].insert(k, v)); } bool remove(const KT& k) { int32_t b_idx = straightHash(k) % HASHSIZE; return _b[b_idx].remove(k); } }; typedef HashMap<int32_t, int32_t> MapInt32Int32; typedef HashMap<int32_t, int32_t>::Iterator IteratorInt32Int32; #endif
[ "jianbing.huang@siemens.com" ]
jianbing.huang@siemens.com
e60a643bd07ac6d4c76f00b186cc5a04ab54b84f
630e5fa4fec4cee4b6936eec74a726550406c11f
/src/qt/pengolincoin/walletpassworddialog.h
96599c8e5fd4e9956e1ae7a36c45da3f4ed38546
[ "MIT" ]
permissive
crypTuron/PengolinCoin-Core
4d815d25de927d42dc890379d15738ee728c525e
3d6c66dd930110075ff44ee6f5a4364c533becd7
refs/heads/master
2022-11-24T21:17:56.271853
2020-07-23T13:49:52
2020-07-23T13:49:52
282,408,670
0
0
MIT
2020-07-25T09:04:22
2020-07-25T09:04:21
null
UTF-8
C++
false
false
664
h
// Copyright (c) 2019 The PENGOLINCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef WALLETPASSWORDDIALOG_H #define WALLETPASSWORDDIALOG_H #include <QDialog> #include <QCheckBox> namespace Ui { class WalletPasswordDialog; class QCheckBox; } class WalletPasswordDialog : public QDialog { Q_OBJECT public: explicit WalletPasswordDialog(QWidget *parent = nullptr); ~WalletPasswordDialog(); private slots: void onWatchClicked(); private: Ui::WalletPasswordDialog *ui; QCheckBox *btnWatch; }; #endif // WALLETPASSWORDDIALOG_H
[ "alonewolf2ksk@gmail.com" ]
alonewolf2ksk@gmail.com
de02fede784096a8206cfc14153825811ee8e8ee
722b60f449ca80a653bde8d59bbc7fe1c930c289
/face_detector/ImageIterator.cpp
e0ca74bd993f07ed452338226c1e5000f6d0c02e
[]
no_license
yukaiwang/face_detector
a9a09aee6180519783ae1ccf6cd70b3e3343882d
e786fce6c6f3c34af0d6e81efff518067a41dfdd
refs/heads/master
2021-01-10T01:10:36.248507
2015-12-04T11:57:39
2015-12-04T11:57:39
47,401,139
0
0
null
null
null
null
UTF-8
C++
false
false
5,268
cpp
// // ImageIterator.cpp // face_detector // // Created by Yukai Wang on 01/12/15. // Copyright © 2015 Yukai Wang. All rights reserved. // #include "ImageIterator.hpp" void write_csv_file(int A[], int length, string file_name) { std::ofstream output(file_name); for(int i = 0; i < length; i++) { output << A[i] << std::endl; } } ImageIterator::ImageIterator(const string& model_file, const string& trained_file, const Mat& img) { classifier = new Classifier(model_file, trained_file); originalImg = img; nbIterator = 0; } ImageIterator::~ImageIterator(){ delete classifier; } void ImageIterator::FrameIterator(Mat actualImg ) { int actualWidth = actualImg.size().width; int actualHeight = actualImg.size().height; std::cout << "actual width 3: " << actualWidth << std::endl; std::cout << "actual height 3: " << actualHeight << std::endl; for (int i = 0; i <= actualHeight-TAILLE_IMG; i += 1) { for (int j = 0; j <= actualWidth-TAILLE_IMG; j += 1) { Mat smallFrame = actualImg(Rect(j, i, TAILLE_IMG, TAILLE_IMG)); std::vector<float> predictions = classifier->Classify(smallFrame); if (predictions[0] < 0.4) { Tag tag; tag.realX = pow(REDUCTION_RATE, nbIterator) * i; tag.realY = pow(REDUCTION_RATE, nbIterator) * j; tag.realWidth = pow(REDUCTION_RATE, nbIterator) * TAILLE_IMG; tag.realHeight = pow(REDUCTION_RATE, nbIterator) * TAILLE_IMG; tags.push_back(tag); } } } } void ImageIterator::Draw() { if (results.size() == 0) { std::cout << "No result" << std::endl; } for (size_t i = 0; i < results.size(); ++i) { Tag tag = results[i]; std::cout << "realX: " << tag.realX << std::endl; std::cout << "realY: " << tag.realY << std::endl; std::cout << "realWidth: " << tag.realWidth << std::endl; std::cout << "realHeight: " << tag.realHeight << std::endl; rectangle(originalImg, Point(tag.realX, tag.realY), Point(tag.realX+tag.realWidth, tag.realY+tag.realHeight), Scalar(255, 0, 0)); } } void ImageIterator::Detect() { Mat actualImg = originalImg.clone(); int actualWidth = actualImg.size().width; int actualHeight = actualImg.size().height; std::cout << "actual width 1: " << actualWidth << std::endl; std::cout << "actual height 1: " << actualHeight << std::endl; while (actualWidth >= TAILLE_IMG && actualHeight >= TAILLE_IMG) { FrameIterator(actualImg); Size size(actualWidth/REDUCTION_RATE,actualHeight/REDUCTION_RATE); resize(actualImg,actualImg,size); actualWidth = actualImg.size().width; actualHeight = actualImg.size().height; nbIterator++; std::cout << "actual width 2: " << actualWidth << std::endl; std::cout << "actual height 2: " << actualHeight << std::endl; } } void ImageIterator::WriteCSV() { std::ofstream output("MeanshiftInput.csv"); for (int i = 0; i < tags.size(); i++) { int centerX = tags[i].realX + tags[i].realWidth/2; int centerY = tags[i].realY + tags[i].realHeight/2; output << centerX << ";" << centerY << std::endl; } } void ImageIterator::ReadCSV() { std::ifstream input("MeanshiftOutput.csv"); if(!input.is_open()){ std::cerr << "failed to open file."; return; } const int MAXSIZE = 20; char oneLine[MAXSIZE]; int i = 0; while(input.getline(oneLine,MAXSIZE)) { string str(oneLine); string str_cluster = str.substr(0, str.find_first_not_of(';')); int nbCluster = stoi(str); clusters[nbCluster].push_back(i++); } std::map<int, std::vector<int> >::iterator it; for (it = clusters.begin(); it != clusters.end(); ++it) { std::cout << "key : " << it->first << std::endl; for (int n = 0; n < it->second.size(); n++) { std::cout << it->second[n] << " "; } } } void ImageIterator::Transform() { std::map<int, std::vector<int> >::iterator it; for (it = clusters.begin(); it != clusters.end(); ++it) { int sumX = 0; int sumY = 0; int sumWidth = 0; int sumHeight = 0; int size = (int)it->second.size(); vector<int> numbers = it->second; for (int n = 0; n < size; n++) { Tag tag = tags[numbers[n] ]; sumX += tag.realX; sumY += tag.realY; sumWidth += tag.realWidth; sumHeight += tag.realHeight; } Tag averageTag = {sumX/size, sumY/size, sumWidth/size, sumHeight/size}; std::cout << "x : " << averageTag.realX << std::endl; std::cout << "y : " << averageTag.realY << std::endl; std::cout << "w : " << averageTag.realWidth << std::endl; std::cout << "h : " << averageTag.realHeight << std::endl; results.push_back(averageTag); } } void ImageIterator::Clustering() { string cmd = "python mean_shift.py"; if (tags.size() == 0) { return; } WriteCSV(); system(cmd.c_str()); ReadCSV(); Transform(); }
[ "yukai.wang1991@gmail.com" ]
yukai.wang1991@gmail.com
76bbcd116363b5e98b39fab3e89989830ac16456
c22c1aed75252533bb5de8ce9ff3c0f5ac9814bc
/samples/greengrass/basic_discovery/main.cpp
2cde0f2515cdc7739b6a2753e87606df19df2fa6
[ "Apache-2.0" ]
permissive
QPC-database/aws-iot-device-sdk-cpp-v2
d141caef6916646967dff1bb48e661bccc6f45f3
163fdf3bff9cc2a51f5d0aeca3d9356f665583a3
refs/heads/main
2023-06-15T00:33:28.643390
2021-06-22T21:02:05
2021-06-22T21:02:05
384,712,786
1
0
Apache-2.0
2021-07-10T14:07:43
2021-07-10T14:07:43
null
UTF-8
C++
false
false
13,859
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/crt/Api.h> #include <aws/crt/io/HostResolver.h> #include <aws/discovery/DiscoveryClient.h> #include <aws/iot/MqttClient.h> #include <algorithm> #include <condition_variable> #include <iostream> #include <mutex> using namespace Aws::Crt; using namespace Aws::Discovery; static void s_printHelp() { fprintf(stdout, "Usage:\n"); fprintf( stdout, "basic-discovery --region <optional: region> --cert <path to cert>" " --key <path to key> --ca_file <optional: path to custom ca>" " --thing_name <thing name> --topic <optional: topic> " " --mode <optional: both|publish|subscribe> --message <optional: message to publish>" " --proxy-host <optional: proxy host name> --proxy-port <optional: proxy port>\n\n"); fprintf(stdout, "region: the region for your green grass groups, default us-east-1\n"); fprintf(stdout, "cert: path to your client certificate in PEM format\n"); fprintf(stdout, "key: path to your key in PEM format\n"); fprintf(stdout, "ca_file: ca file to use in verifying TLS connections.\n"); fprintf(stdout, "\tIt's the path to a CA file in PEM format\n"); fprintf(stdout, "thing_name: the name of your IOT thing\n"); fprintf(stdout, "topic: targeted topic. Default is test/topic\n"); fprintf(stdout, "mode: default both\n"); fprintf(stdout, "message: message to publish. default 'Hello World'\n"); fprintf(stdout, "proxy-host: proxy host to use for discovery call. Default is to not use a proxy.\n"); fprintf(stdout, "proxy-port: proxy port to use for discovery call.\n"); } bool s_cmdOptionExists(char **begin, char **end, const String &option) { return std::find(begin, end, option) != end; } char *s_getCmdOption(char **begin, char **end, const String &option) { char **itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } int main(int argc, char *argv[]) { /************************ Setup the Lib ****************************/ /* * Do the global initialization for the API. */ ApiHandle apiHandle; String proxyHost; uint16_t proxyPort = 0; String region("us-east-1"); String certificatePath; String keyPath; String caFile; String thingName; String topic("test/topic"); String mode("both"); String message("Hello World"); /*********************** Parse Arguments ***************************/ if (!(s_cmdOptionExists(argv, argv + argc, "--cert") && s_cmdOptionExists(argv, argv + argc, "--key") && s_cmdOptionExists(argv, argv + argc, "--thing_name"))) { s_printHelp(); return 0; } certificatePath = s_getCmdOption(argv, argv + argc, "--cert"); keyPath = s_getCmdOption(argv, argv + argc, "--key"); thingName = s_getCmdOption(argv, argv + argc, "--thing_name"); if (s_cmdOptionExists(argv, argv + argc, "--ca_file")) { caFile = s_getCmdOption(argv, argv + argc, "--ca_file"); } if (s_cmdOptionExists(argv, argv + argc, "--region")) { region = s_getCmdOption(argv, argv + argc, "--region"); } if (s_cmdOptionExists(argv, argv + argc, "--topic")) { topic = s_getCmdOption(argv, argv + argc, "--topic"); } if (s_cmdOptionExists(argv, argv + argc, "--mode")) { mode = s_getCmdOption(argv, argv + argc, "--mode"); } if (s_cmdOptionExists(argv, argv + argc, "--message")) { message = s_getCmdOption(argv, argv + argc, "--message"); } if (s_cmdOptionExists(argv, argv + argc, "--proxy-host")) { proxyHost = s_getCmdOption(argv, argv + argc, "--proxy-host"); } if (s_cmdOptionExists(argv, argv + argc, "--proxy-port")) { String portString = s_getCmdOption(argv, argv + argc, "--proxy-port"); proxyPort = static_cast<uint16_t>(atoi(portString.c_str())); } Io::EventLoopGroup eventLoopGroup(1); if (!eventLoopGroup) { fprintf( stderr, "Event Loop Group Creation failed with error %s\n", ErrorDebugString(eventLoopGroup.LastError())); exit(-1); } /* * We're using Mutual TLS for Mqtt, so we need to load our client certificates */ Io::TlsContextOptions tlsCtxOptions = Io::TlsContextOptions::InitClientWithMtls(certificatePath.c_str(), keyPath.c_str()); if (!tlsCtxOptions) { fprintf(stderr, "TLS Context Options creation failed with error %s\n", ErrorDebugString(Aws::Crt::LastError())); exit(-1); } if (!caFile.empty()) { tlsCtxOptions.OverrideDefaultTrustStore(nullptr, caFile.c_str()); } Io::TlsContext tlsCtx(tlsCtxOptions, Io::TlsMode::CLIENT); if (!tlsCtx) { fprintf(stderr, "Tls Context creation failed with error %s\n", ErrorDebugString(LastErrorOrUnknown())); exit(-1); } /* * Default Socket options to use. IPV4 will be ignored based on what DNS * tells us. */ Io::SocketOptions socketOptions; socketOptions.SetConnectTimeoutMs(3000); Io::DefaultHostResolver hostResolver(eventLoopGroup, 64, 30); Io::ClientBootstrap bootstrap(eventLoopGroup, hostResolver); if (!bootstrap) { fprintf(stderr, "ClientBootstrap failed with error %s\n", ErrorDebugString(bootstrap.LastError())); exit(-1); } DiscoveryClientConfig clientConfig; clientConfig.Bootstrap = &bootstrap; clientConfig.SocketOptions = socketOptions; clientConfig.TlsContext = tlsCtx; clientConfig.Region = region; Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions; if (proxyHost.length() > 0 && proxyPort != 0) { proxyOptions.HostName = proxyHost; proxyOptions.Port = proxyPort; clientConfig.ProxyOptions = proxyOptions; // } auto discoveryClient = DiscoveryClient::CreateClient(clientConfig); Aws::Iot::MqttClient mqttClient(bootstrap); std::shared_ptr<Mqtt::MqttConnection> connection(nullptr); std::promise<void> connectionFinishedPromise; std::promise<void> shutdownCompletedPromise; discoveryClient->Discover(thingName, [&](DiscoverResponse *response, int error, int httpResponseCode) { if (!error && response->GGGroups) { auto groupToUse = std::move(response->GGGroups->at(0)); auto connectivityInfo = groupToUse.Cores->at(0).Connectivity->at(0); fprintf( stdout, "Connecting to group %s with thing arn %s, using endpoint %s:%d\n", groupToUse.GGGroupId->c_str(), groupToUse.Cores->at(0).ThingArn->c_str(), connectivityInfo.HostAddress->c_str(), (int)connectivityInfo.Port.value()); connection = mqttClient.NewConnection( Aws::Iot::MqttClientConnectionConfigBuilder(certificatePath.c_str(), keyPath.c_str()) .WithCertificateAuthority(ByteCursorFromCString(groupToUse.CAs->at(0).c_str())) .WithPortOverride(connectivityInfo.Port.value()) .WithEndpoint(connectivityInfo.HostAddress.value()) .Build()); if (!connection) { fprintf(stderr, "Connection setup failed with error %s", ErrorDebugString(mqttClient.LastError())); exit(-1); } connection->OnConnectionCompleted = [&, connectivityInfo, groupToUse]( Mqtt::MqttConnection &conn, int errorCode, Mqtt::ReturnCode /*returnCode*/, bool /*sessionPresent*/) { if (!errorCode) { fprintf( stdout, "Connected to group %s, using connection to %s:%d\n", groupToUse.GGGroupId->c_str(), connectivityInfo.HostAddress->c_str(), (int)connectivityInfo.Port.value()); if (mode == "both" || mode == "subscribe") { auto onMessage = [&](Mqtt::MqttConnection & /*connection*/, const String &receivedOnTopic, const ByteBuf &payload, bool /*dup*/, Mqtt::QOS /*qos*/, bool /*retain*/) { fprintf(stdout, "Publish received on topic %s\n", receivedOnTopic.c_str()); fprintf(stdout, "Message: \n"); fwrite(payload.buffer, 1, payload.len, stdout); fprintf(stdout, "\n"); }; auto onSubAck = [&](Mqtt::MqttConnection & /*connection*/, uint16_t /*packetId*/, const String &topic, Mqtt::QOS /*qos*/, int errorCode) { if (!errorCode) { fprintf(stdout, "Successfully subscribed to %s\n", topic.c_str()); connectionFinishedPromise.set_value(); } else { fprintf( stderr, "Failed to subscribe to %s with error %s. Exiting\n", topic.c_str(), aws_error_debug_str(errorCode)); exit(-1); } }; conn.Subscribe(topic.c_str(), AWS_MQTT_QOS_AT_MOST_ONCE, onMessage, onSubAck); } else { connectionFinishedPromise.set_value(); } } else { fprintf( stderr, "Error connecting to group %s, using connection to %s:%d\n", groupToUse.GGGroupId->c_str(), connectivityInfo.HostAddress->c_str(), (int)connectivityInfo.Port.value()); fprintf(stderr, "Error: %s\n", aws_error_debug_str(errorCode)); exit(-1); } }; connection->OnConnectionInterrupted = [](Mqtt::MqttConnection &, int errorCode) { fprintf(stderr, "Connection interrupted with error %s\n", aws_error_debug_str(errorCode)); }; connection->OnConnectionResumed = [](Mqtt::MqttConnection & /*connection*/, Mqtt::ReturnCode /*connectCode*/, bool /*sessionPresent*/) { fprintf(stdout, "Connection resumed\n"); }; connection->OnDisconnect = [&](Mqtt::MqttConnection & /*connection*/) { fprintf(stdout, "Connection disconnected. Shutting Down.....\n"); shutdownCompletedPromise.set_value(); }; if (!connection->Connect(thingName.c_str(), false)) { fprintf(stderr, "Connect failed with error %s\n", aws_error_debug_str(aws_last_error())); exit(-1); } } else { fprintf( stderr, "Discover failed with error: %s, and http response code %d\n", aws_error_debug_str(error), httpResponseCode); exit(-1); } }); { connectionFinishedPromise.get_future().wait(); } while (true) { String input; if (mode == "both" || mode == "publish") { fprintf( stdout, "Enter the message you want to publish to topic %s and press enter. Enter 'exit' to exit this " "program.\n", topic.c_str()); } else { fprintf(stdout, "Enter exit or quit to exit the program.\n"); } std::getline(std::cin, input); if (input == "exit" || input == "quit") { fprintf(stdout, "Exiting..."); break; } if (mode == "both" || mode == "publish") { ByteBuf payload = ByteBufNewCopy(DefaultAllocator(), (const uint8_t *)input.data(), input.length()); ByteBuf *payloadPtr = &payload; auto onPublishComplete = [payloadPtr](Mqtt::MqttConnection &, uint16_t packetId, int errorCode) { aws_byte_buf_clean_up(payloadPtr); if (packetId) { fprintf(stdout, "Operation on packetId %d Succeeded\n", packetId); } else { fprintf(stdout, "Operation failed with error %s\n", aws_error_debug_str(errorCode)); } }; connection->Publish(topic.c_str(), AWS_MQTT_QOS_AT_MOST_ONCE, false, payload, onPublishComplete); } } connection->Disconnect(); { shutdownCompletedPromise.get_future().wait(); } return 0; }
[ "noreply@github.com" ]
QPC-database.noreply@github.com
9e5b5d34c359ff932deb80286da67530d1c31fc9
2a4a845584aa202b6e4567397cb464200aaeea16
/src/browser/content_browser_client.h
97842c5283badb065cb8b2f61e513d3f016f088b
[ "MIT" ]
permissive
CharlesHoskinson/exo_browser
32453b220c96fbce88dede61492820fd7b801eea
414286dde5a8a71f9b8b2482e635ecb0f04a117f
refs/heads/master
2020-12-11T06:01:21.212884
2013-12-31T11:06:01
2013-12-31T11:06:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,350
h
// Copyright (c) 2013 Stanislas Polu. // Copyright (c) 2012 The Chromium Authors. // See the LICENSE file. #ifndef EXO_BROWSER_BROWSER_CONTENT_BROWSER_CLIENT_H_ #define EXO_BROWSER_BROWSER_CONTENT_BROWSER_CLIENT_H_ #include <string> #include <map> #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/web_contents_view.h" namespace exo_browser { class ExoBrowserMainParts; class ExoBrowserContext; class ExoBrowserResourceDispatcherHostDelegate; class RenderProcessHost; class ExoSession; class ExoBrowserContentBrowserClient : public content::ContentBrowserClient { public: // Gets the current instance. static ExoBrowserContentBrowserClient* Get(); ExoBrowserContentBrowserClient(); virtual ~ExoBrowserContentBrowserClient(); /****************************************************************************/ /* CONTENTBROWSERCLIENT IMPLEMENTATION */ /****************************************************************************/ virtual content::BrowserMainParts* CreateBrowserMainParts( const content::MainFunctionParams& parameters) OVERRIDE; virtual void AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) OVERRIDE; virtual void OverrideWebkitPrefs(content::RenderViewHost* render_view_host, const GURL& url, WebPreferences* prefs) OVERRIDE; virtual void ResourceDispatcherHostCreated() OVERRIDE; /* TODO(spolu): Reintroduce AccessTokenStore */ //virtual content::AccessTokenStore* CreateAccessTokenStore() OVERRIDE; virtual std::string GetDefaultDownloadName() OVERRIDE; virtual content::WebContentsViewDelegate* GetWebContentsViewDelegate( content::WebContents* web_contents) OVERRIDE; virtual void BrowserURLHandlerCreated( content::BrowserURLHandler* handler) OVERRIDE; virtual void RenderProcessHostCreated( content::RenderProcessHost* host) OVERRIDE; virtual net::URLRequestContextGetter* CreateRequestContext( content::BrowserContext* browser_context, content::ProtocolHandlerMap* protocol_handlers) OVERRIDE; virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition( content::BrowserContext* browser_context, const base::FilePath& partition_path, bool in_memory, content::ProtocolHandlerMap* protocol_handlers) OVERRIDE; virtual bool IsHandledURL(const GURL& url) OVERRIDE; /****************************************************************************/ /* EXOSESSION I/F */ /****************************************************************************/ // ### RegisterExoSession // ``` // @session {ExoSession} the session to register // ``` // Lets ExoSession register themselves when constructed so that they can be // retrieved from their underlying BrowserContext when needed. // see ExoSessionForBrowserContext void RegisterExoSession(ExoSession* session); // ### UnRegisterExoSession // ``` // @session {ExoSession} the session to unregister // ``` void UnRegisterExoSession(ExoSession* session); // ### ExoSessionFroBrowserContext // ``` // @content_browser_context {BrowserContext} // ``` // Retrieves the ExoSession wrapping the given content::BrowserContext ExoSession* ExoSessionForBrowserContext( content::BrowserContext* browser_context); /****************************************************************************/ /* ACCESSORS */ /****************************************************************************/ ExoBrowserResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() { return resource_dispatcher_host_delegate_.get(); } ExoBrowserMainParts* browser_main_parts() { return browser_main_parts_; } private: scoped_ptr<ExoBrowserResourceDispatcherHostDelegate> resource_dispatcher_host_delegate_; ExoBrowserMainParts* browser_main_parts_; std::vector<ExoSession*> sessions_; }; } // namespace exo_browser #endif // EXO_BROWSER_BROWSER_CONTENT_BROWSER_CLIENT_H_
[ "polu.stanislas@gmail.com" ]
polu.stanislas@gmail.com
32228738aeaa35c47274ab10e556b820ce660f50
cf0fc67feeaf7f1289b4bd3d3026cf9ce271aa87
/djiros-3.3/djiros-3.3/src/bluefox2/camera.cpp
fdb1afd137cf0a05e6293ba3a1f7ee42899c4c05
[]
no_license
hch661100/Manifold
8b4e7f3f5ad006f491a50007b4a4795fca3b6dc9
7017be6c34779b5f4050a22ece7b707890888952
refs/heads/master
2020-03-19T10:34:38.968350
2018-09-24T18:03:59
2018-09-24T18:03:59
136,383,709
0
0
null
null
null
null
UTF-8
C++
false
false
22,768
cpp
#include "camera.h" #include <boost/format.hpp> #include <algorithm> namespace bluefox2 { Camera::Camera(ros::NodeHandle _param_nh) : pnode(_param_nh), m_fast_mode(false), m_hwsync_grab_count(0), m_max_req_number(-1), m_verbose_output(false), m_sync_offset_for_debug(0.0) { int exposure_time_us; bool use_color; bool use_hdr; bool has_hdr; bool use_binning; bool use_auto_exposure; int auto_speed; double fps; double gain; bool is_slave; int aec_desired_gray_value; int aec_control_delay_frame; pnode.param("use_color", use_color, false); pnode.param("use_hdr", use_hdr, true); pnode.param("has_hdr", has_hdr, true); pnode.param("use_binning", use_binning, false); pnode.param("use_auto_exposure", use_auto_exposure, false); pnode.param("aec_desired_gray_value", aec_desired_gray_value, 100); pnode.param("aec_control_delay_frame", aec_control_delay_frame, 0); pnode.param("exposure_time_us", exposure_time_us, 10000); pnode.param("auto_speed", auto_speed, 0); pnode.param("fps", fps, 30.0); pnode.param("gain", gain, 0.0); pnode.param("is_slave", is_slave, false); pnode.param("fast_mode", m_fast_mode, false); pnode.param("verbose_output", m_verbose_output, false); pnode.param("cam_cnt", cam_cnt, 1); m_fps = fps; ROS_ASSERT_MSG(cam_cnt <= MAX_CAM_CNT, "cam_cnt exceeds MAX_CAM_CNT(%d)", MAX_CAM_CNT); for (int i = 0; i < cam_cnt; i++) { std::string prefix = boost::str(boost::format("camera%d/") % i); CameraSetting cs; pnode.param(prefix + "serial", cs.serial, std::string("25001214")); pnode.param(prefix + "topic", cs.topic, boost::str(boost::format("image%d") % i)); // pnode.param(prefix + std::string("fps"), fps, 30.0); pnode.param(prefix + "use_color", cs.use_color, use_color); pnode.param(prefix + "use_hdr", cs.use_hdr, use_hdr); pnode.param(prefix + "has_hdr", cs.has_hdr, has_hdr); pnode.param(prefix + "use_binning", cs.use_binning, use_binning); pnode.param(prefix + "use_auto_exposure", cs.use_auto_exposure, use_auto_exposure); pnode.param( prefix + "aec_desired_gray_value", cs.aec_desired_gray_value, aec_desired_gray_value); pnode.param(prefix + "aec_control_delay_frame", cs.aec_control_delay_frame, aec_control_delay_frame); pnode.param(prefix + "exposure_time_us", cs.exposure_time_us, exposure_time_us); pnode.param(prefix + "auto_speed", cs.auto_speed, auto_speed); pnode.param(prefix + "gain", cs.gain, gain); pnode.param(prefix + "is_slave", cs.is_slave, is_slave); ROS_ASSERT_MSG(cs.auto_speed < 3, "Invalid auto speed"); ROS_ASSERT_MSG(!cs.serial.empty(), "Cannot read camera serial"); camSettings[cs.serial] = cs; } std::pair<int, int> master_slave_cnt = {0, 0}; for (auto& item : camSettings) { const CameraSetting& cs = item.second; img_publisher[cs.serial] = pnode.advertise<sensor_msgs::Image>(cs.topic, 10); img_buffer[cs.serial] = sensor_msgs::Image(); if (cs.is_slave) { master_slave_cnt.second++; } else { master_slave_cnt.first++; } } if (master_slave_cnt.first == cam_cnt) { m_is_slave_mode = false; } else if (master_slave_cnt.second == cam_cnt) { m_is_slave_mode = true; } else { ROS_FATAL("This driver is designed for all master/all slave usage!"); ROS_BREAK(); } // Count cameras devCnt = devMgr.deviceCount(); ROS_INFO("All %d mvBlueFOX devices", devCnt); // Init cameras ok = true; for (auto& item : camSettings) { bool current_camera_inited = false; CameraSetting& cs = item.second; for (unsigned int k = 0; k < devCnt; k++) { if (devMgr[k]->serial.read() == cs.serial) { ids[cs.serial] = k; if (!initSingleMVDevice(k, cs)) { ok = false; ROS_ERROR("Camera %s Init Failed.", cs.serial.c_str()); break; } else { current_camera_inited = true; } } } if (!current_camera_inited) { ROS_ASSERT_MSG(false, "Camera %s not found!!!", cs.serial.c_str()); } } // Subscribe for debug message m_offset_sub = pnode.subscribe<std_msgs::Float64>("sync_offset", 10, boost::bind(&Camera::debug_sync_offset_callback, this, _1), ros::VoidConstPtr(), ros::TransportHints().tcpNoDelay()); } Camera::~Camera() { for (auto& item : camSettings) { const int devIndex = ids.at(item.second.serial); fi[devIndex]->imageRequestReset(0, 0); devMgr[devIndex]->close(); } ok = false; } bool Camera::is_slave_mode() const { return m_is_slave_mode; } bool Camera::is_fast_mode() const { return m_fast_mode; } bool Camera::isOK() { return ok; } bool Camera::initSingleMVDevice(unsigned int id, const CameraSetting& cs) { ROS_INFO("Camera Found: %s(%s)", devMgr[id]->family.read().c_str(), devMgr[id]->serial.read().c_str()); try { devMgr[id]->open(); } catch (const mvIMPACT::acquire::ImpactAcquireException& e) { std::cout << "An error occurred while opening the device " << devMgr[id]->serial.read() << "(error code: " << e.getErrorCode() << "(" << e.getErrorCodeAsString() << "))." << std::endl << "Press [ENTER] to end the application..." << std::endl; return false; } try { fi[id] = new mvIMPACT::acquire::FunctionInterface(devMgr[id]); } catch (const mvIMPACT::acquire::ImpactAcquireException& e) { std::cout << "An error occurred while creating the function interface on device " << devMgr[id]->serial.read() << "(error code: " << e.getErrorCode() << "(" << e.getErrorCodeAsString() << "))." << std::endl << "Press [ENTER] to end the application..." << std::endl; return false; } try { statistics[id] = new mvIMPACT::acquire::Statistics(devMgr[id]); } catch (const mvIMPACT::acquire::ImpactAcquireException& e) { std::cout << "An error occurred while initializing the statistical information on device " << devMgr[id]->serial.read() << "(error code: " << e.getErrorCode() << "(" << e.getErrorCodeAsString() << "))." << std::endl << "Press [ENTER] to end the application..." << std::endl; return false; } // Set Properties mvIMPACT::acquire::SettingsBlueFOX settings(devMgr[id]); // Using the "Base" settings (default) // Binning if (cs.use_binning) { settings.cameraSetting.binningMode.write(cbmBinningHV); ROS_INFO("2X Binning"); } else { ROS_INFO("No Binning"); } // Gain settings.cameraSetting.autoGainControl.write(agcOff); if (cs.gain >= 0.0) { settings.cameraSetting.gain_dB.write(cs.gain); ROS_INFO("Gain: %f", settings.cameraSetting.gain_dB.read()); } else { settings.cameraSetting.autoGainControl.write(agcOn); ROS_INFO("Auto Gain %d", settings.cameraSetting.autoGainControl.read()); } // Auto exposure, modified controller for better results, be careful about the minimum exposure // time if (cs.use_auto_exposure) { // settings.cameraSetting.autoControlParameters.controllerSpeed.write(acsUserDefined); // settings.cameraSetting.autoControlParameters.controllerGain.write(0.5); // settings.cameraSetting.autoControlParameters.controllerIntegralTime_ms.write(100); // settings.cameraSetting.autoControlParameters.controllerDerivativeTime_ms.write(0.0001); std::vector<mvIMPACT::acquire::TAutoControlSpeed> tacSpeedTable = { acsSlow, acsMedium, acsFast, acsUserDefined}; settings.cameraSetting.autoControlParameters.controllerSpeed.write( tacSpeedTable.at(cs.auto_speed)); settings.cameraSetting.autoControlParameters.desiredAverageGreyValue.write( cs.aec_desired_gray_value); settings.cameraSetting.autoControlParameters.controllerDelay_Images.write( cs.aec_control_delay_frame); settings.cameraSetting.autoControlParameters.exposeLowerLimit_us.write(12); settings.cameraSetting.autoControlParameters.exposeUpperLimit_us.write(cs.exposure_time_us); settings.cameraSetting.autoExposeControl.write(aecOn); ROS_INFO("Auto Exposure w/ Max Exposure Time (us) : %d . Desired Grey Value: %d", settings.cameraSetting.autoControlParameters.exposeUpperLimit_us.read(), settings.cameraSetting.autoControlParameters.desiredAverageGreyValue.read()); } else { settings.cameraSetting.autoExposeControl.write(aecOff); settings.cameraSetting.expose_us.write(cs.exposure_time_us); ROS_INFO("Exposure Time (us) : %d", settings.cameraSetting.expose_us.read()); } // HDR if (cs.has_hdr) { if (cs.use_hdr) { settings.cameraSetting.getHDRControl().HDRMode.write(cHDRmFixed0); settings.cameraSetting.getHDRControl().HDREnable.write(bTrue); ROS_INFO("Enable HDR ..."); ROS_INFO("KneePoint 0:"); ROS_INFO(" Voltage (mV): %d", settings.cameraSetting.getHDRControl() .getHDRKneePoint(0) .HDRControlVoltage_mV.read()); ROS_INFO( " Parts per Million: %d", settings.cameraSetting.getHDRControl().getHDRKneePoint(0).HDRExposure_ppm.read()); ROS_INFO("KneePoint 1:"); ROS_INFO(" Voltage (mV): %d", settings.cameraSetting.getHDRControl() .getHDRKneePoint(1) .HDRControlVoltage_mV.read()); ROS_INFO( " Parts per Million: %d", settings.cameraSetting.getHDRControl().getHDRKneePoint(1).HDRExposure_ppm.read()); } else { settings.cameraSetting.getHDRControl().HDREnable.write(bFalse); ROS_INFO("HDR Off"); } } else { ROS_INFO("No HDR"); } // Color if (cs.use_color) { // RGB image settings.imageDestination.pixelFormat.write(idpfBGR888Packed); ROS_INFO("Color Images"); } else { // Raw image settings.imageDestination.pixelFormat.write(idpfRaw); ROS_INFO("Grayscale/Bayer Images"); } // prefill the capture queue. There can be more then 1 queue for some device, but only one for // now mvIMPACT::acquire::SystemSettings ss(devMgr[id]); ss.requestCount.write(1); // Trigger setting if (cs.is_slave) { ROS_INFO("Set Slave Mode\n"); // settings.cameraSetting.triggerMode.write(ctmContinuous); settings.cameraSetting.triggerMode.write(ctmOnHighLevel); settings.cameraSetting.triggerSource.write(ctsDigIn0); settings.cameraSetting.frameDelay_us.write(0); } else { ROS_INFO("Set Master Mode\n"); settings.cameraSetting.triggerMode.write(ctmOnDemand); settings.cameraSetting.flashMode.write(cfmDigout0); settings.cameraSetting.flashType.write(cftStandard); settings.cameraSetting.flashToExposeDelay_us.write(0); } return true; } void Camera::feedImages() { ROS_ASSERT(!is_slave_mode()); ros::Rate r(m_fps); while (pnode.ok()) { send_software_request(); if (grab_image_data()) { for (auto& item : img_publisher) { const std::string& serial = item.first; img_buffer.at(serial).header.stamp = capture_time; item.second.publish(img_buffer.at(serial)); } } ros::spinOnce(); r.sleep(); } } void Camera::send_software_request() { // Request images from both cameras for (auto& item : ids) { const int devIndex = item.second; fi[devIndex]->imageRequestSingle(); } usleep(10000); // necessary short sleep to warm up the camera capture_time = ros::Time::now(); } bool Camera::grab_image_data() { int requestNr[MAX_CAM_CNT] = {INVALID_ID}; // ros::Time s1 = ros::Time::now(); for (auto& item : ids) { const int devIndex = item.second; requestNr[devIndex] = fi[devIndex]->imageRequestWaitFor(300); } // ros::Time s2 = ros::Time::now(); // ROS_INFO("imageRequestWaitFor %7.3f ms", (s2 - s1).toSec() * 1000.0); bool status = true; for (auto& item : ids) { const int devIndex = item.second; if (!(fi[devIndex]->isRequestNrValid(requestNr[devIndex]))) { status = false; ROS_ERROR("[djiros/cam] Camera %s request timeout.", item.first.c_str()); } } if (status) { int ok_cnt = 0; for (auto& item : ids) { const int devIndex = item.second; pRequest[devIndex] = fi[devIndex]->getRequest(requestNr[devIndex]); ok_cnt += pRequest[devIndex]->isOK(); if (!pRequest[devIndex]->isOK()) { ROS_ERROR("[djiros/cam] Camera %s request failed.", item.first.c_str()); } } if (ok_cnt == cam_cnt) { for (auto& item : ids) { const int devIndex = item.second; const std::string& serial = item.first; int Channels = pRequest[devIndex]->imageChannelCount.read(); int Height = pRequest[devIndex]->imageHeight.read(); int Width = pRequest[devIndex]->imageWidth.read(); int Step = Width * Channels; std::string Encoding = Channels == 1 ? sensor_msgs::image_encodings::MONO8 : sensor_msgs::image_encodings::BGR8; img_buffer.at(serial).height = Height; img_buffer.at(serial).width = Width; img_buffer.at(serial).step = Step; img_buffer.at(serial).encoding = Encoding; ROS_ASSERT(static_cast<int>(Step * Height) == pRequest[devIndex]->imageSize.read()); img_buffer.at(serial).data.resize(Step * Height); std::memcpy(&img_buffer.at(serial).data[0], pRequest[devIndex]->imageData.read(), pRequest[devIndex]->imageSize.read()); img_buffer.at(serial).header.frame_id = boost::str( boost::format("expose_us:%d") % pRequest[devIndex]->infoExposeTime_us.read()); } // Release capture request for (auto& item : ids) { const int devIndex = item.second; fi[devIndex]->imageRequestUnlock(requestNr[devIndex]); } status = true; } else { ROS_ERROR("Not all requests are vaild, discard all data."); // Clear all image received and reset capture for (auto& item : ids) { const int devIndex = item.second; fi[devIndex]->imageRequestUnlock(requestNr[devIndex]); } status = false; } } else { ROS_ERROR("[djiros/cam] Timeout request/s."); // Clear all image received and reset capture for (auto& item : ids) { const int devIndex = item.second; if (fi[devIndex]->isRequestNrValid(requestNr[devIndex])) { pRequest[devIndex] = fi[devIndex]->getRequest(requestNr[devIndex]); fi[devIndex]->imageRequestUnlock(requestNr[devIndex]); } } status = false; } return status; } void Camera::send_hardware_request() { m_hwsync->req_queue.push(SyncReqInfo(SyncReqInfo::SingleRequestValue)); } void Camera::send_driver_request() { // Request images from both cameras for (auto& item : ids) { const int devIndex = item.second; fi[devIndex]->imageRequestSingle(); } } void Camera::reset_driver_request() { // Request images from both cameras for (auto& item : ids) { const int devIndex = item.second; fi[devIndex]->imageRequestReset(0, 0); } } bool Camera::wait_for_imu_ack(SyncAckInfo& sync_ack, int& queue_size) { ros::Time wait_start_time = ros::Time::now(); while (1) { if (!pnode.ok()) { return false; } // Check imu response { std::lock_guard<std::mutex> lg(m_hwsync->ack_mutex); queue_size = m_hwsync->ack_queue.size(); if (m_hwsync->ack_queue.size()) { if (m_hwsync->ack_queue.size() == 1) { // ROS_INFO("ack queue size = %zu", m_hwsync->ack_queue.size()); } else { ROS_ERROR("ack queue size = %zu", m_hwsync->ack_queue.size()); ROS_ERROR( "Cannot sync! Image capturing is too slow! Try to decrease fps/exposure or " "turn off aec!"); ros::shutdown(); } // get first and erase it sync_ack = m_hwsync->ack_queue.front(); m_hwsync->ack_queue.pop(); // return the ack break; }; } // sleep for the while loop ros::Duration(5.0 / 1000.0).sleep(); ros::Duration dt = ros::Time::now() - wait_start_time; // Timeout set as two times longer than normal interval if (dt.toSec() > (1.0 / m_fps * 2)) { ROS_WARN_THROTTLE(1.0, "Wait %.3f secs for imu ack", dt.toSec()); return false; } } return true; } void Camera::process_slow_sync() { ROS_ASSERT(is_slave_mode()); ROS_ASSERT(m_hwsync.get()); send_driver_request(); ros::Rate r(m_fps); while (pnode.ok()) { send_hardware_request(); // Wait for imu ack SyncAckInfo sync_ack; int queue_size = 0; if (!wait_for_imu_ack(sync_ack, queue_size)) { reset_driver_request(); ROS_ERROR("reset all driver requests!"); goto END_OF_OUT_LOOP; } // Imu ack received, verify it ROS_ASSERT(sync_ack.seq >= 0); // Get image from driver if (grab_image_data()) { ROS_INFO_COND(m_verbose_output, "Grab data with seq[%d]", sync_ack.seq); ROS_ASSERT_MSG(sync_ack.seq == m_hwsync_grab_count, "sync_ack.seq=%d, hwsync_grab_count=%d", sync_ack.seq, m_hwsync_grab_count); for (auto& item : img_publisher) { const std::string& serial = item.first; capture_time = ros::Time(sync_ack.stamp); img_buffer.at(serial).header.stamp = capture_time; item.second.publish(img_buffer.at(serial)); } } m_hwsync_grab_count++; // inc it whether grab success or failed. send_driver_request(); END_OF_OUT_LOOP: r.sleep(); if (m_max_req_number > 0 && m_hwsync_grab_count >= m_max_req_number) { break; } } } void Camera::process_fast_sync() { ROS_ASSERT(is_slave_mode()); ROS_ASSERT(is_fast_mode()); ROS_ASSERT(m_hwsync.get()); const int TRAIL_CNT = 5; ros::Time tm1, tm2; bool grab_result; ROS_INFO("[djiros/cam] Process several one-shot requests..."); this->m_max_req_number = TRAIL_CNT; this->process_slow_sync(); ROS_INFO("[djiros/cam] Clear buffers... (There may be request timeout)"); for (size_t i = 0; i < 1; ++i) { grab_image_data(); ros::Duration(1.0 / m_fps).sleep(); } ROS_INFO("[djiros/cam] Start continuous requests"); { std::lock_guard<std::mutex> lg(m_hwsync->req_mutex); m_hwsync->req_queue.push(SyncReqInfo(static_cast<int>(m_fps))); } m_hwsync_grab_count = 0; send_driver_request(); ros::Rate r(200.0); while (pnode.ok()) { // Wait for imu ack SyncAckInfo sync_ack; int queue_size = 0; if (!wait_for_imu_ack(sync_ack, queue_size)) { ROS_ERROR("Wait failed."); goto END_OF_OUT_LOOP; } // Imu ack received, verify it ROS_ASSERT(sync_ack.seq >= 0); // Get image from driver tm1 = ros::Time::now(); grab_result = grab_image_data(); tm2 = ros::Time::now(); ROS_INFO_COND(m_verbose_output, "grab time %.3f", (tm2 - tm1).toSec()); ROS_INFO_COND(m_verbose_output, "Try grabing data with imu_seq[%d] grab_seq[%d]", sync_ack.seq, m_hwsync_grab_count); if (grab_result) { for (auto& item : img_publisher) { const std::string& serial = item.first; capture_time = sync_ack.stamp; // After artificial calibrated, we found that actually image is taken one imu later // than triggered img_buffer.at(serial).header.stamp = capture_time + ros::Duration(m_sync_offset_for_debug); item.second.publish(img_buffer.at(serial)); } } m_hwsync_grab_count++; // inc it whether grab success or failed. tm1 = ros::Time::now(); // if (queue_size > 0 && queue_size < 4) { // for(size_t k = 0; k < static_cast<size_t>(queue_size); ++k) { send_driver_request(); // } // } else { // ROS_ERROR("[djiros/cam] queue_size = %d", queue_size); // } tm2 = ros::Time::now(); // ROS_INFO("driver time %.3f", (tm2-tm1).toSec()); END_OF_OUT_LOOP: // tm1 = ros::Time::now(); r.sleep(); // tm2 = ros::Time::now(); // ROS_INFO("sleep time %.3f", (tm2-tm1).toSec()); } } void Camera::debug_sync_offset_callback(const std_msgs::Float64ConstPtr& pMsg) { ROS_INFO("[djifox] Sync offset set to [img] = [imu] + %f", pMsg->data); m_sync_offset_for_debug = pMsg->data; } } // End of namespace bluefox2
[ "chonghuang@umail.ucsb.edu" ]
chonghuang@umail.ucsb.edu
87b9ec7acd66aa33f0dea390266587eb6e0140d0
065514567124ae77a1c18ac3a05cdbd5a479bde1
/MeshTools/FEFileExport.cpp
712cd33721774d5f1a2fd87200bf5a6bcd122aa2
[ "MIT" ]
permissive
davidlni/FEBioStudio
d6b1f61304c104e33e6b1b1e8d522c19c95aa154
324d76b069a60e99328500b9b25eb79cf5a019e8
refs/heads/master
2023-08-17T09:04:30.943726
2021-09-28T21:19:29
2021-09-28T21:19:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
cpp
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ // FEFileExport.cpp: implementation of the FEFileExport class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FEFileExport.h" #include <stdarg.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// FEFileExport::FEFileExport(FEProject& prj) : m_prj(prj) { } FEFileExport::~FEFileExport() { } void FEFileExport::ClearLog() { m_err.clear(); } bool FEFileExport::errf(const char* szerr, ...) { // get a pointer to the argument list va_list args; // copy to string char szmsg[256] = {0}; va_start(args, szerr); vsprintf(szmsg, szerr, args); va_end(args); m_err += szmsg; m_err += "\n"; return false; }
[ "michaelrossherron@gmail.com" ]
michaelrossherron@gmail.com
49365e6a6fcd9b134e8ab48c90d0e391d2cd4296
aebf2b4a7c6182828780d8c3bfc7667256576dc5
/Library System/Book.cpp
fe1e4c99bdd9bcfaa8a5cc1a1430a40c8cc5cd5d
[]
no_license
yoonioncho/OOPG-with-C
39b764209d4105f70f801d247a3c7862383c6415
4388b883abb9e3850c4b68d2ac9b5fda4347151a
refs/heads/main
2023-02-25T23:04:28.021244
2021-02-03T12:50:25
2021-02-03T12:50:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
466
cpp
//Book.cpp //Member and friend function definitions of class Book #include "Book.h" Book::Book(Author ba, Publisher bp, Date bd, string bt) : BookAuthor(ba),BookPublisher(bp),PublishDate(bd) { BookTitle = bt; } Book::~Book() { } void Book::print() const { cout << "\tBook Title : " << BookTitle << endl; BookAuthor.print(); cout << endl; BookPublisher.print(); cout << endl; cout << "\tPublish Date : "; PublishDate.print(); }
[ "noreply@github.com" ]
yoonioncho.noreply@github.com
223a5efb836418531e7b0180d0bb2b983877c6f2
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtbase/src/gui/doc/snippets/textdocument-tables/xmlwriter.cpp
fd860c73eef2a29aa7f3205943d6077865a8efa8
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-commercial-license", "LGPL-2.0-or-later", "LGPL-2.1-only", "GFDL-1.3-only", "LicenseRef-scancode-qt-commercial-1.1", "LGPL-3.0-only", "LicenseRef-scancode-qt-company-exception-lgpl-2.1", "GPL-1.0-or-later", "GPL-3.0-only", "BSD-3-Clause", "LGPL-2.1-or-later", "GPL-2.0-only", "Qt-LGPL-exception-1.1", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-generic-exception" ]
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
5,577
cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include "xmlwriter.h" QDomDocument *XmlWriter::toXml() { QDomImplementation implementation; QDomDocumentType docType = implementation.createDocumentType( "scribe-document", "scribe", "qt.nokia.com/scribe"); document = new QDomDocument(docType); // ### This processing instruction is required to ensure that any kind // of encoding is given when the document is written. QDomProcessingInstruction process = document->createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"utf-8\""); document->appendChild(process); QDomElement documentElement = document->createElement("document"); document->appendChild(documentElement); QTextFrame *root = textDocument->rootFrame(); if (root) processFrame(documentElement, root); return document; } void XmlWriter::processBlock(QDomElement &parent, const QTextBlock &block) { QDomElement blockElement = document->createElement("block"); blockElement.setAttribute("position", block.position()); blockElement.setAttribute("length", block.length()); parent.appendChild(blockElement); QTextBlock::iterator it; for (it = block.begin(); !(it.atEnd()); ++it) { QTextFragment fragment = it.fragment(); if (fragment.isValid()) { QDomElement fragmentElement = document->createElement("fragment"); blockElement.appendChild(fragmentElement); fragmentElement.setAttribute("length", fragment.length()); QDomText fragmentText = document->createTextNode(fragment.text()); fragmentElement.appendChild(fragmentText); } } } void XmlWriter::processFrame(QDomElement &parent, QTextFrame *frame) { QDomElement frameElement = document->createElement("frame"); frameElement.setAttribute("begin", frame->firstPosition()); frameElement.setAttribute("end", frame->lastPosition()); parent.appendChild(frameElement); //! [0] QDomElement frameElement = ... QTextFrame::iterator it; for (it = frame->begin(); !(it.atEnd()); ++it) { QTextFrame *childFrame = it.currentFrame(); QTextBlock childBlock = it.currentBlock(); if (childFrame) { QTextTable *childTable = qobject_cast<QTextTable*>(childFrame); if (childTable) processTable(frameElement, childTable); else processFrame(frameElement, childFrame); } else if (childBlock.isValid()) //! [0] //! [1] processBlock(frameElement, childBlock); } //! [1] } void XmlWriter::processTable(QDomElement &parent, QTextTable *table) { QDomElement element = document->createElement("table"); for (int row = 0; row < table->rows(); ++row) { for (int column = 0; column < table->columns(); ++column) { QTextTableCell cell = table->cellAt(row, column); processTableCell(element, cell); } } parent.appendChild(element); } void XmlWriter::processTableCell(QDomElement &parent, const QTextTableCell &cell) { QDomElement element = document->createElement("cell"); element.setAttribute("row", cell.row()); element.setAttribute("column", cell.column()); QTextFrame::iterator it; for (it = cell.begin(); !(it.atEnd()); ++it) { QTextFrame *childFrame = it.currentFrame(); QTextBlock childBlock = it.currentBlock(); if (childFrame) processFrame(element, childFrame); else if (childBlock.isValid()) processBlock(element, childBlock); } parent.appendChild(element); }
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
d535307fcc5686fef9830bbdd41ef87aca5e42b1
707996ee245f8ca271baa6959823211b248b362e
/src/bitcoinrpc.cpp
c3c442a96187df9639e0266332be5adad9238d21
[]
no_license
OnionCoin/OnionCoin
6eeac1d77a81c4223bf6d431121336fc994224fd
fcb4001a99e59940931031112957d6deb3629d9c
refs/heads/master
2020-04-06T06:44:23.619557
2014-02-08T14:37:55
2014-02-08T14:37:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
116,254
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 The Litecoin Developers // Copyright (c) 2013 Adam M. (Wouldn't want your name to be lower case, would you?) // Copyright (c) 2014 FoxCoin Foxes. // Copyright (c) 2014 OnionCoin. // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "wallet.h" #include "db.h" #include "walletdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; static int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern Value getconnectioncount(const Array& params, bool fHelp); // in rpcnet.cpp extern Value getpeerinfo(const Array& params, bool fHelp); extern Value dumpprivkey(const Array& params, bool fHelp); // in rpcdump.cpp extern Value importprivkey(const Array& params, bool fHelp); extern Value getrawtransaction(const Array& params, bool fHelp); // in rcprawtransaction.cpp extern Value listunspent(const Array& params, bool fHelp); extern Value createrawtransaction(const Array& params, bool fHelp); extern Value decoderawtransaction(const Array& params, bool fHelp); extern Value signrawtransaction(const Array& params, bool fHelp); extern Value sendrawtransaction(const Array& params, bool fHelp); const Object emptyobj; void ThreadRPCServer3(void* parg); Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (v.type() != t) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(-3, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (v.type() == null_type) throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str())); if (v.type() != t.second) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(-3, err); } } } double GetDifficulty(const CBlockIndex* blockindex = NULL) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(-3, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(-3, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires Wallet passphrase to be set with Walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the Wallet passphrase with Walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (confirms) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(-11, "Invalid account name"); return strAccount; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } /// Note: This interface may still be subject to change. string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "stop\n" "Stop OnionCoin server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "OnionCoin server has now stopped running!"; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } // Litecoin: Return average network hashes per second based on last number of blocks. Value GetNetworkHashPS(int lookup) { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnetworkhashps [blocks]\n" "Returns the estimated network paws per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120); } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); CService addrProxy; GetProxy(NET_IPV4, addrProxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new OnionCoin address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current OnionCoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <OnionCoin address> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid OnionCoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <OnionCoin address>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid OnionCoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of address for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <OnionCoin address> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid OnionCoin address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the OnionCoin passphrase with OnionCoinpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <OnionCoin address> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(-4, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(-5, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <OnionCoin address> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(-5, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <OnionCoin address> [minconf=1]\n" "Returns the total amount received by <OnionCoin address> in transactions with at least [minconf] confirmations."); // OnionCoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(-5, "Invalid OnionCoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nGenerated, nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance += nGenerated - nSent - nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' should always return the same number. int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; nBalance += allGeneratedMature; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your Wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(-20, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(-20, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <to OnionCoin address> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid OnionCoin address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(-5, string("Invalid OnionCoin address:")+s.name_); if (setAddress.count(address)) throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(-6, "Insufficient funds"); throw JSONRPCError(-4, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(-4, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the Wallet\"\n" "each key is a OnionCoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: OnionCoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64 nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Generated blocks assigned to account "" if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == "")) { Object entry; entry.push_back(Pair("account", string(""))); if (nGeneratedImmature) { entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature))); } else { entry.push_back(Pair("category", "generate")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature))); } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString())); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString())); entry.push_back(Pair("category", "receive")); entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(-8, "Negative count"); if (nFrom < 0) throw JSONRPCError(-8, "Negative from"); Array ret; CWalletDB walletdb(pwalletMain->strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64, TxPair > TxItems; TxItems txByTime; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } // iterate backwards until we have nCount items to return: for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { mapAccountBalances[""] += nGeneratedMature; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(-8, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-Wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(-5, "Invalid or non-Wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); BackupWallet(*pwalletMain, strDest); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(-4, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); Sleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the Wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unbarricaded Wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(-17, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(-14, "Error: The Wallet passphrase entered was incorrect."); } else throw runtime_error( "Walletpassphrase <passphrase> <timeout>\n" "Stores the Wallet decryption key in memory for <timeout> seconds."); CreateThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); CreateThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the Wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unbarricaded Wallet, but Walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "Walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the Wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(-14, "Error: The Wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the Wallet barricade key from memory, locking the Wallet.\n" "After calling this method, you will need to call Walletpassphrase again\n" "before being able to call any methods which require the Wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unbarricaded Wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptWallet <passphrase>\n" "barricades the Wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an barricaded Wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Barricades the Wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(-16, "Error: Failed to barricade the Wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "Wallet barricaded; OnionCoin server stopping, restart to run with barricaded Wallet"; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <OnionCoin address>\n" "Return information about <OnionCoin address>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "OnionCoin server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "OnionCoin server is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; printf("DEBUG: merkle size %i\n", merkle.size()); BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(-9, "OnionCoin server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "OnionCoin server is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); result.push_back(Pair("algorithm", "scrypt:1024,1,1")); // specify that we should use the scrypt algorithm return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblocktemplate [params]\n" "If [params] does not contain a \"data\" key, returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "If [params] does contain a \"data\" key, tries to solve the block and returns null if it was successful (and \"rejected\" if not)\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); const Object& oparam = params[0].get_obj(); std::string strMode; { const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (find_value(oparam, "data").type() == null_type) strMode = "template"; else strMode = "submit"; } if (strMode == "template") { if (vNodes.empty()) throw JSONRPCError(-9, "OnionCoin server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "OnionCoin server is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block if(pblock) delete pblock; pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } else if (strMode == "submit") { // Parse parameters CDataStream ssBlock(ParseHex(find_value(oparam, "data").get_str()), SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; ssBlock >> pblock; bool fAccepted = ProcessBlock(NULL, &pblock); return fAccepted ? Value::null : "rejected"; } throw JSONRPCError(-8, "Invalid mode"); } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblock <hash>\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(-5, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex); } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safe mode? // ------------------------ ----------------------- ---------- { "help", &help, true }, { "stop", &stop, true }, { "getblockcount", &getblockcount, true }, { "getconnectioncount", &getconnectioncount, true }, { "getpeerinfo", &getpeerinfo, true }, { "getdifficulty", &getdifficulty, true }, { "getnetworkhashps", &getnetworkhashps, true }, { "getgenerate", &getgenerate, true }, { "setgenerate", &setgenerate, true }, { "gethashespersec", &gethashespersec, true }, { "getinfo", &getinfo, true }, { "getmininginfo", &getmininginfo, true }, { "getnewaddress", &getnewaddress, true }, { "getaccountaddress", &getaccountaddress, true }, { "setaccount", &setaccount, true }, { "getaccount", &getaccount, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true }, { "sendtoaddress", &sendtoaddress, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false }, { "backupwallet", &backupwallet, true }, { "keypoolrefill", &keypoolrefill, true }, { "walletpassphrase", &walletpassphrase, true }, { "walletpassphrasechange", &walletpassphrasechange, false }, { "walletlock", &walletlock, true }, { "encryptwallet", &encryptwallet, false }, { "validateaddress", &validateaddress, true }, { "getbalance", &getbalance, false }, { "move", &movecmd, false }, { "sendfrom", &sendfrom, false }, { "sendmany", &sendmany, false }, { "addmultisigaddress", &addmultisigaddress, false }, { "getrawmempool", &getrawmempool, true }, { "getblock", &getblock, false }, { "getblockhash", &getblockhash, false }, { "gettransaction", &gettransaction, false }, { "listtransactions", &listtransactions, false }, { "signmessage", &signmessage, false }, { "verifymessage", &verifymessage, false }, { "getwork", &getwork, true }, { "getworkex", &getworkex, true }, { "listaccounts", &listaccounts, false }, { "settxfee", &settxfee, false }, { "setmininput", &setmininput, false }, { "getblocktemplate", &getblocktemplate, true }, { "listsinceblock", &listsinceblock, false }, { "dumpprivkey", &dumpprivkey, false }, { "importprivkey", &importprivkey, false }, { "listunspent", &listunspent, false }, { "getrawtransaction", &getrawtransaction, false }, { "createrawtransaction", &createrawtransaction, false }, { "decoderawtransaction", &decoderawtransaction, false }, { "signrawtransaction", &signrawtransaction, false }, { "sendrawtransaction", &sendrawtransaction, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: onioncoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == 401) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: onioncoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == 200) cStatus = "OK"; else if (nStatus == 400) cStatus = "Bad Request"; else if (nStatus == 403) cStatus = "Forbidden"; else if (nStatus == 404) cStatus = "Not Found"; else if (nStatus == 500) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %d\r\n" "Content-Type: application/json\r\n" "Server: onioncoin-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return 500; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return 500; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return strUserPass == strRPCUserColonPass; } // // JSON-RPC protocol. OnionCoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = 500; int code = find_value(objError, "code").get_int(); if (code == -32600) nStatus = 400; else if (code == -32601) nStatus = 404; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Chech whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg)); // Make this thread recognisable as the RPC listener RenameThread("bitcoin-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're canceled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(403, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!CreateThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (mapArgs["-rpcpassword"] == "") { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use onioncoin"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=onioncoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "If the file does not exist, create it with owner-readable-only file permissions.\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 9919)); boost::signals2::signal<void ()> StopRequests; try { boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) boost::system::error_code v6_only_error; acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); } } catch(boost::system::system_error &e) { uiInterface.ThreadSafeMessageBox(strprintf(_("An error occured while setting up the RPC port %i for listening: %s"), endpoint.port(), e.what()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(-32600, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(-32600, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(-32600, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(-32600, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(-32700, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer3(parg)); // Make this thread recognisable as the RPC handler RenameThread("bitcoin-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; loop { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) Sleep(250); conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(-32700, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(-32700, "Top-level object parse error"); conn->stream() << HTTPReply(200, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(-32700, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(-32601, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(-2, string("Safe mode: ") + strWarning); try { // Execute Value result; { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } return result; } catch (std::exception& e) { throw JSONRPCError(-1, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "9919"))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == 401) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value) { if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); value = value2.get_value<T>(); } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
[ "onioncoin2014@gmail.com" ]
onioncoin2014@gmail.com
d93417644e900dd26f249c23c695611e4f0d9645
65d3fd04cbe3780600b7113645f6cd8072c2baab
/M.cpp
3363bfa0b5b29e1bb813edef834a21d637958938
[]
no_license
devtot0/task3
6d10ca6f96be55c7850667cf6b2ba147962bef7d
e3776b33c0ad01ebe90379c2d6f76ff944ee2085
refs/heads/master
2020-04-07T08:03:57.183889
2018-11-19T10:13:15
2018-11-19T10:13:15
158,199,463
0
0
null
null
null
null
UTF-8
C++
false
false
2,671
cpp
#include "M.h" CImg<int> dilation(CImg<int>& image, vector<vector<maskItem>> mask) { CImg<int> result = image; for (int x = 1; x < image.width() - 1; x++) { for (int y = 1; y < image.height() - 1; y++) { bool isMax = false; for (int i = 0; i < mask.size(); i++) { for (int j = 0; j < mask[0].size(); j++) { if (mask[i][j] == inactive) { continue; } if (mask[i][j] == one && image(x+i-1,y+j-1,0)==255) { isMax = true; break; } } if (isMax) { break; } } if (isMax) { for (int c = 0; c < image.spectrum(); c++) { result(x, y, 0, c) = 255; } } } } return result; } CImg<int> erosion(CImg<int>& image, vector<vector<maskItem>> mask) { CImg<int> result = image; for (int x = 1; x < image.width() - 1; x++) { for (int y = 1; y < image.height() - 1; y++) { bool isMin = false; for (int i = 0; i < mask.size(); i++) { for (int j = 0; j < mask[0].size(); j++) { if (mask[i][j] == inactive) { continue; } if (mask[i][j] == one && image(x + i - 1, y + j - 1, 0) == 0) { isMin = true; break; } } if (isMin) { break; } } if (isMin) { for (int c = 0; c < image.spectrum(); c++) { result(x, y, 0,c) = 0; } } } } return result; } CImg<int> opening(CImg<int>& image, vector<vector<maskItem>> mask) { CImg<int> temp; temp = erosion(image, mask); return dilation(temp, mask); } CImg<int> closing(CImg<int>& image, vector<vector<maskItem>> mask) { CImg<int> temp; temp = dilation(image, mask); return erosion(temp, mask); } CImg<int> hmt(CImg<int>& image, vector<vector<maskItem>> mask) { CImg<int> result = image; for (int x = 1; x < image.width() - 1; x++) { for (int y = 1; y < image.height() - 1; y++) { bool isMin = false; bool isMax = false; for (int i = 0; i < mask.size(); i++) { for (int j = 0; j < mask[0].size(); j++) { if (mask[i][j] == inactive) { continue; } if (mask[i][j] == one && image(x + i - 1, y + j - 1, 0) == 0) { isMin = true; break; } if (mask[i][j] == zero && image(x + i - 1, y + j - 1, 0) == 255) { isMax = true; break; } } if (isMin || isMax) { break; } } if (isMin) { for (int c = 0; c < image.spectrum(); c++) { result(x, y, 0, c) = 0; } } if (isMax) { for (int c = 0; c < image.spectrum(); c++) { result(x, y, 0, c) = 255; } } } } return result; }
[ "noreply@github.com" ]
devtot0.noreply@github.com
c67ad96fb03c1c1ef11a47fd563889e0dc577a8b
b405fd9cd3c53a3ed279e75aca3fec89ba745df5
/299.Bulls and Cows/299.Bulls and Cows/main.cpp
719bdbcc440c50ddbfb7108eeecb2f0440af9755
[]
no_license
Abysman/MyLeetCode
4842db63f4914022a3773be1e9d9ce068cb6d3bd
a4eb8af658996e7ba4501342f4aa4bbd113e6cfb
refs/heads/master
2021-04-06T20:48:17.260497
2020-01-23T23:09:35
2020-01-23T23:09:35
125,452,898
0
0
null
null
null
null
UTF-8
C++
false
false
1,896
cpp
// // main.cpp // 299.Bulls and Cows // // Created by Abysman on 2018/9/27. // Copyright © 2018年 Abysman. All rights reserved. // #include <iostream> #include <unordered_map> using namespace std; //class Solution { //public: // // only contains digits // string getHint(string secret, string guess) { // int aCnt = 0; // int bCnt = 0; // vector<int> sVec(10, 0); // 0 ~ 9 for secret // vector<int> gVec(10, 0); // 0 ~ 9 for guess // if (secret.size() != guess.size() || secret.empty()) { return "0A0B"; } // for (int i = 0; i < secret.size(); ++i) { // char c1 = secret[i]; char c2 = guess[i]; // if (c1 == c2) { // ++aCnt; // } else { // ++sVec[c1-'0']; // ++gVec[c2-'0']; // } // } // // count b // for (int i = 0; i < sVec.size(); ++i) { // bCnt += min(sVec[i], gVec[i]); // } // return to_string(aCnt) + 'A' + to_string(bCnt) + 'B'; // } //}; class Solution { public: string getHint(string secret, string guess) { string res = "A"; unordered_map<char, int> record_A; unordered_map<char, int> record_B; int count = 0; for (int i = 0; i < secret.length(); ++i) { if (secret[i] == guess[i]) { count += 1; } else { record_A[secret[i]]++; record_B[guess[i]]++; } } res = to_string(count) + res; count = 0; for (auto k = record_A.begin(); k != record_A.end(); ++k) { count += min(k->second, record_B[k->first]); } res = res + to_string(count) + 'B'; return res; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
[ "756884429@qq.com" ]
756884429@qq.com
8dc0779714c5aaddaab412b4e897977da72c0254
ca45c2183600d80290f874eef48cba3a7b4ebf18
/yolo_detector.cpp
7c3c1839df223360fdd8b87cc8ccf10d407772ad
[]
no_license
koodg123/systolic-array
22d587719f460b560ef75afaf64825937b937da5
ba980bb62e82a7984c38b252a933118dbbea7d13
refs/heads/master
2021-08-11T00:07:14.253720
2017-11-13T03:08:33
2017-11-13T03:08:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,738
cpp
//======================================================================== // yolo_detector header file //======================================================================== // @brief: Application for detecting objects #include "yolo_detector.h" /* // transfer value // argv[0] - datacfg : cfg/coco.data // argv[1] - cfgfile : cfg/tiny-yolo.cfg // argv[2] - weightfile : tiny-yolo.weights // argv[3] - filename : data/dog.jpg // argv[4] - thresh : 0.24 // argv[5] - hier_thresh : 0.5 */ void detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh) { // load datacfg printf("datacfg:%s\n",datacfg); list *options = read_data_cfg(datacfg); /* // print options node *pnode = options->front; kvp *dis; int counter = 0; printf("Option size:%d\n",options->size); while (pnode) { dis = (kvp *)pnode->val; printf("NO. %d: (1)key: %s; (2)value: %s;\n",counter,(char*)dis->key,(char*)dis->val); counter++; pnode = pnode->next; } */ char *name_list = option_find_str(options, "names", "data/names.list"); //printf("name_list:%s\n",name_list); // name_list: data/coco.names char **names = get_labels(name_list); /* int size_names = sizeof(names); for (int i = 0; i < 80; i++) { printf("names NO. %d: %s;\n",i,names[i]); } */ // read labels image **alphabet = load_alphabet(); // load cfgfile network net = parse_network_cfg(cfgfile); // load weitht file if (weightfile) { load_weights(&net,weightfile); } // setup net.batch = 1 set_batch_network(&net, 1); char buffer[255]; char *input = buffer; float nms = 0.4; // start timer Timer timer("yolo_detector"); while (1) { // copy image name if (filename) { strncpy (input,filename,256); } else { printf("Please enter image path: "); fflush(stdout); input = fgets(input, 256, stdin); if (!input) { return; } strtok(input,"\n"); } // image im = load_image_color(input,0,0); image sized = resize_image(im, net.w, net.h); //printf("sized.h:%d; sized.w:%d; sized.c:%d;\n",sized.h,sized.w,sized.c); /* // print input image for (int m = 0; m < 100; m++) { printf("im.data[%d]:%.12f;\n",m,im.data[m]); } */ // region layer layer l = net.layers[net.n-1]; // box *boxes = (box *)calloc(l.w * l.h * l.n, sizeof(box)); float **probs = (float **)calloc(l.w * l.h * l.n, sizeof(float *)); for (int i = 0; i < l.w*l.h*l.n; i++) { probs[i] = (float *)calloc(l.classes+1, sizeof(float)); // ??? } // float *X = sized.data; Timer timer("Total time"); // start prediction printf("Start prediction...\n"); timer.start(); network_predict(net,X); timer.stop(); printf("Prediction finishes!\n"); // draw region boxes printf("Getting region boxes...\n"); get_region_boxes(l, 1, 1, thresh, probs, boxes, 0, 0, hier_thresh); /* // verify **probs float sum = 0.0; printf("max_i:%d; max_j:%d;\n",l.w * l.h * l.n,l.classes+1); for (int i = 0; i < l.w * l.h * l.n; i++) { for (int j = 0; j < l.classes+1; j++) { if (probs[i][j] != 0) { printf("probs[%d][%d]:%.12f;\n",i,j,probs[i][j]); } sum += probs[i][j]; } } printf("sum:%.12f;\n",sum); */ // if (l.softmax_tree && nms) { //printf("Enter 111111\n"); do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); } else if (nms) { //printf("Enter 222222\n"); do_nms_sort(boxes, probs, l.w*l.h*l.n, l.classes, nms); } /* // verify **probs float sum = 0.0; printf("max_i:%d; max_j:%d;\n",l.w * l.h * l.n,l.classes+1); for (int i = 0; i < l.w * l.h * l.n; i++) { for (int j = 0; j < l.classes+1; j++) { if (probs[i][j] != 0) { printf("probs[%d][%d]:%.12f;\n",i,j,probs[i][j]); } sum += probs[i][j]; } } printf("sum:%.12f;\n",sum); */ printf("Start draw predictions...\n"); draw_detections(im, l.w*l.h*l.n, thresh, boxes, probs, names, alphabet, l.classes); printf("Save & print images...\n"); save_image(im, "predictions"); show_image(im, "predictions"); //printf("ch0\n"); // free memory free_image(im); free_image(sized); //printf("ch1\n"); free_ptrs((void **)probs, l.w*l.h*l.n); //printf("ch2\n"); free(boxes); //printf("ch3\n"); // where did we modify the value filename to jump out of the while loop????? if (filename) { break; } } printf("Exit program.\n"); }
[ "dpjiuzhu@126.com" ]
dpjiuzhu@126.com
10e8703c9b2a51b4bc9e06db76a89600936c2277
c1e25a487002d11b2bbe433c351658a92261b973
/Assignment/GGraphic.h
35994a23b594be267452046f78ddf7259ce07862
[]
no_license
shifungyeo/CGP-Assignment
c6a0758d00e5ba8d67b2caffbb8b51636d36e98c
498c9c473ec6af2f1964b840e7909b9029ca5018
refs/heads/master
2023-03-25T03:09:15.130453
2021-03-22T01:33:19
2021-03-22T01:33:19
350,170,472
0
0
null
null
null
null
UTF-8
C++
false
false
346
h
#pragma once #include <d3d9.h> #include <d3dx9.h> #include "GWindow.h" class GGraphic { private: GGraphic(); ~GGraphic(); static GGraphic* instance; public: static GGraphic* getInstance(); static void releaseInstance(); void begin(); void end(); IDirect3D9* direct3D9; D3DPRESENT_PARAMETERS d3dPP; IDirect3DDevice9* d3dDevice; };
[ "shifungyeo@gmail.com" ]
shifungyeo@gmail.com
c5ef74a4fb432c744de81f1644bc699204617404
0adf6466ad731be8f551c5472c2e5ea132c5115e
/shared/GLHUD.h
f7801e60f35e22b6e1b0e3bbbd10642493b9f3ef
[]
no_license
kkaushalp/aphid
bef46e068e21e72a3a2515a7da0ae9085f6712ad
93e4e4102fae93428608205d000ff90a9edc69f1
refs/heads/master
2020-04-08T00:00:23.798704
2015-08-17T07:25:43
2015-08-17T07:25:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
522
h
#pragma once #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <OpenGL/glext.h> #include <GLUT/glut.h> #endif #ifdef WIN32 #include <windows.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glext.h> #endif #include <string> class BaseCamera; class GLHUD { public: GLHUD(); virtual ~GLHUD(); void reset(); void setCamera(BaseCamera * cam); void drawString(const std::string & str, const int & row) const; private: static GLuint m_texture; BaseCamera * m_camera; };
[ "zhangmdev@gmail.com" ]
zhangmdev@gmail.com
88d0e49b3654423fe9c1a961e7be5118ebf9346b
d281caf8d3f36b0432203624af5e950039591734
/flashlight/app/benchmark/ModelBenchmarker.h
21855de3d4764ecf54b35aab34bfba5f4c2d39a8
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mtmd/flashlight
ae4b7ab2c4986cf8a647fb0cda657cf389ac1812
36595da7e1ed752471f3e7b1f0196c514f244945
refs/heads/master
2021-08-15T12:46:01.743974
2021-08-03T21:26:54
2021-08-03T21:28:10
209,403,798
0
0
NOASSERTION
2019-09-18T21:04:33
2019-09-18T21:04:33
null
UTF-8
C++
false
false
1,425
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <vector> #include "flashlight/fl/flashlight.h" namespace fl { namespace app { namespace benchmark { using Criterion = std::function<fl::Variable(const std::vector<fl::Variable>&)>; class ModelBenchmarker { public: ModelBenchmarker( std::shared_ptr<fl::Module>& model, const Criterion& criterion, const int worldSize = 1); void runBenchmark(const std::vector<fl::Variable>& input); // Return time splits in seconds double getBatchTime() const; double getForwardTime() const; double getCriterionTime() const; double getBackwardTime() const; double getOptimizationTime() const; private: std::shared_ptr<fl::Module> model_; Criterion criterion_; std::shared_ptr<fl::Reducer> reducer_; std::shared_ptr<fl::SGDOptimizer> optimizer_; fl::TimeMeter batchTimerMeter_{true}; fl::TimeMeter fwdTimeMeter_{true}; fl::TimeMeter critFwdTimeMeter_{true}; fl::TimeMeter bwdTimeMeter_{true}; fl::TimeMeter optimTimeMeter_{true}; void syncMeters(); // TODO: support optimizer selection void createOptimizer(); // TODO: support reducer selection void createReducer(const int worldSize); }; } // namespace benchmark } // namespace app } // namespace fl
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
cb97a4e24cfe61fd0fe090ab657c25e3ad463980
43fe4d201f86a83f87589b8f519cd066a94fe7a5
/srcs/commonlib/comm/data/JointQuaternionData.h
90a429b89761f437ffabf7007b8d2e07c6670dd7
[]
no_license
Aharobot/SIGServer
b7ddcfe5627efe5b975a2f30a310b2bf5547b21b
7b7657afe21573e4f08baa24ff8e2fac6a60b7e0
refs/heads/master
2021-01-22T00:13:10.628330
2014-10-31T20:22:31
2014-10-31T20:22:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,171
h
#ifndef JointQuaternionData_h #define JointQuaternionData_h #include <string> class JointQuaternionData { private: typedef std::string S; private: S m_agentName; S m_jointName; double m_qw; double m_qx; double m_qy; double m_qz; bool m_offset; public: JointQuaternionData(const char *agentName_, const char *jointName_, double qw_, double qx_, double qy_, double qz_, bool b_) : m_agentName(agentName_), m_jointName(jointName_), m_qw(qw_), m_qx(qx_), m_qy(qy_), m_qz(qz_), m_offset(b_) {} JointQuaternionData() : m_qw(0.0), m_qx(0.0), m_qy(0.0), m_qz(0.0) {} void agentName(const char *n) { m_agentName = n; } const char * agentName() { return m_agentName.c_str(); } void jointName(const char *n) { m_jointName = n; } const char * jointName() { return m_jointName.c_str(); } void qw(double v) { m_qw = v; } double qw() { return m_qw; } void qx(double v) { m_qx = v; } double qx() { return m_qx; } void qy(double v) { m_qy = v; } double qy() { return m_qy; } void qz(double v) { m_qz = v; } double qz() { return m_qz; } void offset(bool b) { m_offset = b; } const bool offset() { return m_offset; } }; #endif
[ "inamura@nii.ac.jp" ]
inamura@nii.ac.jp
87849225be999a1907f624223cd6440c7fa14ff2
19fd75fe50eb82ddb770f641d2dbd475d361f8cc
/t9_2/t9_2/t9_2Doc.cpp
9b8fc70905f9c8bb680fbaeaae9467d9f45e61ca
[]
no_license
xmm123-456/Experiment
48dc037e01a28540e0a97be163975aa1d6fb0f32
90382b7b415637616464bd54e3b214abbb080fec
refs/heads/master
2021-02-15T09:34:14.793651
2020-06-01T12:23:20
2020-06-01T12:23:20
247,668,370
0
1
null
null
null
null
GB18030
C++
false
false
2,507
cpp
// t9_2Doc.cpp : Ct9_2Doc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "t9_2.h" #endif #include "t9_2Doc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // Ct9_2Doc IMPLEMENT_DYNCREATE(Ct9_2Doc, CDocument) BEGIN_MESSAGE_MAP(Ct9_2Doc, CDocument) END_MESSAGE_MAP() // Ct9_2Doc 构造/析构 Ct9_2Doc::Ct9_2Doc() { // TODO: 在此添加一次性构造代码 } Ct9_2Doc::~Ct9_2Doc() { } BOOL Ct9_2Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // Ct9_2Doc 序列化 void Ct9_2Doc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } list.Serialize(ar); } #ifdef SHARED_HANDLERS // 缩略图的支持 void Ct9_2Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void Ct9_2Doc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void Ct9_2Doc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // Ct9_2Doc 诊断 #ifdef _DEBUG void Ct9_2Doc::AssertValid() const { CDocument::AssertValid(); } void Ct9_2Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // Ct9_2Doc 命令
[ "2524398565@qq.com" ]
2524398565@qq.com
70fd7d65945441dbe7299edc93b1ff0f21cd18bc
0d094e5f52560449751177f54c0a24aa59c72498
/packaged_task.cpp
237d5b424db5b9ece0e48316b037199cdfe7026d
[]
no_license
xlnwel/Cpp-concurrency
d593af22080315b8b1bad9d60d2cd7f8915acfe1
da6f0875d2da86ec3a7a4fb65fce80e1e3ddeed2
refs/heads/main
2023-03-22T23:22:36.770412
2021-03-20T08:06:36
2021-03-20T08:06:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
cpp
#include <atomic> #include <functional> #include <future> #include <iostream> #include "queue.hpp" #include "join_thread.hpp" using namespace std; using namespace utility; /* A reimplementation of List 4.9 */ using Func = double(); atomic<bool> go; LockBasedQueue<std::packaged_task<Func>, std::list<std::packaged_task<Func>>> task_queue; // thread safe queue, which handles locks inside void task_execution_thread() { while (!go.load()) this_thread::yield(); packaged_task<double()> task; while (!task_queue.empty()) { // for debugging purpose, we only execute this loop once auto flag = task_queue.try_pop(task); // Returns the front task and removes it from queue. Waits if task_queue is empty if (flag) task(); // execute task else { cout << this_thread::get_id() << "yield\n"; this_thread::yield(); } } } double task(int n=1) { static std::atomic<int> i = 1; std::cout << i.fetch_add(1, std::memory_order_relaxed) << "task\n"; return i.load(std::memory_order_relaxed); } int main() { go = false; JoinThread t1(task_execution_thread); JoinThread t2(task_execution_thread); // auto f1 = post_task(task_queue, task, 3); // auto f2 = post_task(task_queue, task, 5); // std::cout << "f1: " << f1.get() << '\n'; // std::cout << "f2: " << f2.get() << '\n'; vector<future<double>> v; for (auto i = 0; i != 10; ++i) { v.push_back(post_task(task_queue, task, i)); } go = true; for (auto& f: v) cout << f.get() << '\n'; }
[ "122134545@qq.com" ]
122134545@qq.com
73220b97cefd52d644c1f3adc1783e16934e1da4
eaf0c24a620807e1304c4d663a493637a85f6d84
/client/src/EventLoop.cpp
2d1718b2a095755397a726eb2d09055d1be03551
[]
no_license
xiaopeifeng/dbproxy
71f488e61c0a50ffdd74d0e1671cde0eb76cbb78
0c972e2db766e6bfd15ad9e98e8867566f41a43c
refs/heads/master
2021-01-10T01:19:24.529260
2016-03-10T14:04:46
2016-03-10T14:04:46
52,366,310
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
#include "EventLoop.h" #include "DBProxyClient.h" EventLoop::EventLoop() {} EventLoop::~EventLoop() {} void EventLoop::loop() { while(true) { Task<DBProxyClient>* t = m_tasks.pop(); if( t->m_obj ){ (t->m_obj->*(t->m_fun))(t->m_arg); // task_call_back_t cb = t->m_fun; }else{ // t->m_fun(t->m_arg); } delete t; } } void EventLoop::runInLoop(Task<DBProxyClient>* t) { m_tasks.push(t); }
[ "xiaopeifenng@gmail.com" ]
xiaopeifenng@gmail.com
dcd6a7c6a829d84c19e5032f0973001c25ed9f46
322e889e9d1fe58b62428ed320ce54c4d519bbd2
/RMQSQ.cpp
52f1496e82fea80fb0f97997cc160799bb63e009
[]
no_license
shikharmay7/spoj
86d996babf27bf63a058bd4bbbc36ba002eac754
da39dc571387fb9bfccd41e43e6e3ffc93684074
refs/heads/master
2021-07-24T05:33:13.789362
2020-08-04T09:16:59
2020-08-04T09:16:59
205,915,082
0
0
null
null
null
null
UTF-8
C++
false
false
1,160
cpp
SPOJ submission 26231331 (CPP14) plaintext list. Status: AC, problem RMQSQ, contest SPOJ. By shikhar_may7 (shikhar), 2020-07-03 13:54:00. #include<bits/stdc++.h> using namespace std; typedef long long int lli; lli arr[100001], st[400004]; void buildTree(lli si, lli ss, lli se) { if(ss==se) { st[si] = arr[ss]; return ; } int mid = (ss+se)/2; buildTree(2*si, ss, mid); buildTree(2*si+1, mid+1, se); st[si] = min(st[2*si], st[2*si+1]); // min of left child and right child } lli query(lli si, lli ss, lli se, lli qs, lli qe) { if(se<qs || ss>qe) return INT_MAX; if(ss>=qs && se<=qe) return st[si]; lli mid = (ss+se)/2; lli l = query(2*si,ss,mid,qs,qe); lli r = query(2*si+1,mid+1,se,qs,qe); return min(l,r); } int main() { lli n; cin>>n; for(lli i=1;i<=n;i++) cin>>arr[i]; buildTree(1,1,n); lli q; cin>>q; while(q--) { lli l,r; cin>>l>>r; cout<<query(1,1,n,l+1,r+1)<<endl; } return 0; }
[ "noreply@github.com" ]
shikharmay7.noreply@github.com
52542226fedc67f53583e0c54a67641d6183d34b
88dd6468b61673b45b777fc3bcb6763f6f0d7457
/C++/Dynamic/3.cpp
74e20c42009e399aed9a43e2612bda283207fd16
[]
no_license
theja0473/C-Programs
c76db967ca02edc6bb0382ebd212d8bf4627dba6
ed09d9d3ac8b3ac5f9b35d4c26cf411a3d8e0185
refs/heads/master
2021-01-01T04:12:51.031288
2016-05-23T11:25:45
2016-05-23T11:25:45
59,474,377
0
1
null
null
null
null
UTF-8
C++
false
false
414
cpp
#include<iostream> using namespace std; int main() { int *ptr; int number, i; cout<<"Enter the number of elements : "; cin>>number; ptr = new int[number]; for(i = 0; i < number; i++) { cout<<"Enter the value : "; cin>> *(ptr + i); } cout<<"Elements given : "; for(i = 0; i < number; i++) { cout<<ptr[i]<<" "; } cout<<"\n"; delete[] ptr; return 0; }
[ "theja0473@mail.com" ]
theja0473@mail.com
a543990e8cfc83f83e13758a96b1b060af3b5cc8
12c135847b8b67ae33017600861e25ad5751efc0
/constant/turbulenceProperties
df876d926ff02db105d048e88fb14d516d7109a6
[]
no_license
kamakiri1225/Karman_vortex_sheet
57623ecdb2ed1d255a6e95663fc60ffbe285ba49
bda2dfd09f39e6ee0241d8b95043615ef9a08193
refs/heads/main
2023-01-02T00:58:06.813039
2020-10-28T04:43:40
2020-10-28T04:43:40
307,907,577
0
0
null
null
null
null
UTF-8
C++
false
false
987
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 4.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "constant"; object turbulenceProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // simulationType laminar; RAS { RASModel laminar; turbulence off; printCoeffs on; } // ************************************************************************* //
[ "noreply@github.com" ]
kamakiri1225.noreply@github.com
079f15cf7d22015ccf28051fc41b3e464c67c2a6
f75b4132456b9f33a47a4ddc86b3faa2f2b8dff7
/Aseets/Programs/before/GameFlag.cpp
dfd6059722607e0f8cf90e2a336795a7f6f926fd
[]
no_license
edonasi/make0903
4a71b58b9f755192575dedb53846b78518ebe234
901b7a7d06e914f4c61459def3369a7d4f3a4233
refs/heads/master
2023-08-02T22:07:57.064369
2021-10-01T03:25:34
2021-10-01T03:25:34
402,603,486
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,368
cpp
//*--------------------------------------------------------------------------------* // ゲーム続行のフラグを管理する //*--------------------------------------------------------------------------------* //*--------------------------------------------------------------------------------* // ヘッダファイル読み込み //*--------------------------------------------------------------------------------* // CommonUseファイル #include "IncludeFile.hpp" // 自身のファイル #include GAME_FLAG_HPP using namespace n_game_flag; //*--------------------------------------------------------------------------------* // シングルトン実装 //*--------------------------------------------------------------------------------* //シングルトンなGameStateManagerクラスのオブジェクト ClGameFlag* ClGameFlag::m_ins = nullptr; /// <summary> /// コンストラクタ、初期化 /// </summary> ClGameFlag::ClGameFlag() { m_is_play = TRUE; } /// <summary> /// コピーコンストラクタ /// </summary> /// <param name="src">コピー元アドレス</param> ClGameFlag::ClGameFlag(const ClGameFlag& src){ //アドレスをコピーしておく m_ins = src.m_ins; } /// <summary> /// コピーコンストラクタ /// </summary> /// <param name="src">コピー元アドレス</param> /// <returns>このインスタンスのアドレス</returns> ClGameFlag& ClGameFlag::operator=(const ClGameFlag& src){ //アドレスをコピーしておく m_ins = src.m_ins; return *this; } /// <summary> /// デストラクタ /// </summary> ClGameFlag::~ClGameFlag() { return; } /// <summary> /// インスタンス取得(初めて参照するときはインスタンスを生成) /// </summary> /// <returns><シングルトンなインスタンス/returns> ClGameFlag* ClGameFlag::GetIns(){ //初めて取得する時、そのオブジェクトを生成を生成 if (m_ins == nullptr) { //メモリの確保 m_ins = new ClGameFlag(); } return m_ins; } /// <summary> /// オブジェクトの破棄 /// </summary> VOID ClGameFlag::Destroy(){ //メモリの破棄 delete m_ins; m_ins = nullptr; } //ゲーム続行のフラグをおろす VOID ClGameFlag::SetEndPlay() { m_is_play = FALSE; } //ゲームを行っているのか参照する BOOL ClGameFlag::GetIsPlay() { return m_is_play; }
[ "hj-g20030@sist.ac.jp" ]
hj-g20030@sist.ac.jp
813861b2f91c2ec52e92f1c7148a6580122f393f
4fb6ac5060727f05abd056cf9f3ee830a0734aee
/atcoder/gc24b.cpp
1c9a6cb58de3d4c5e31c133f67ef3a6de21f621c
[]
no_license
booneng/competitive_programming
6141c1ab60e49ffd1ae1cf4ede018622b122ed6b
b6a39e1574c4b8b513945d6fa6e9075a4f458370
refs/heads/master
2021-04-15T12:50:59.351207
2019-07-23T08:01:06
2019-07-23T08:01:06
126,816,788
0
0
null
null
null
null
UTF-8
C++
false
false
483
cpp
#include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; int q[n + 1]; for (int i = 1; i <= n; i++) { int p; cin >> p; q[p] = i; } int max_length = 1; int cur_length = 1; for (int i = 1; i < n; i++) { if (q[i] < q[i + 1]) { cur_length++; } else { max_length = max(max_length, cur_length); cur_length = 1; } } max_length = max(max_length, cur_length); cout << n - max_length; }
[ "ohbooneng@gmail.com" ]
ohbooneng@gmail.com
cf71e28ff69cfcd76b913e7e4d921a69bcbe2e9c
23efe1d0a2d3469ebf0fc43bbb5359aeb25c1a51
/modules/gdscript/gd_function.h
1f790eaadcf95cd241a3739e55291856ae0290ab
[ "MIT", "CC-BY-4.0", "CC-BY-3.0" ]
permissive
est31/godot
868c5b09f86edb18e338feb45ac410e776cd4ab8
c4c6797fc1d700f59ea8d4927d42c1838bcfb3b9
refs/heads/master
2021-01-14T12:02:46.420109
2016-06-16T12:24:15
2016-06-16T12:24:15
34,761,514
1
1
null
2015-04-28T23:34:27
2015-04-28T23:34:26
null
UTF-8
C++
false
false
4,497
h
#ifndef GD_FUNCTION_H #define GD_FUNCTION_H #include "self_list.h" #include "os/thread.h" #include "pair.h" #include "variant.h" #include "string_db.h" #include "reference.h" class GDInstance; class GDScript; class GDFunction { public: enum Opcode { OPCODE_OPERATOR, OPCODE_EXTENDS_TEST, OPCODE_SET, OPCODE_GET, OPCODE_SET_NAMED, OPCODE_GET_NAMED, OPCODE_ASSIGN, OPCODE_ASSIGN_TRUE, OPCODE_ASSIGN_FALSE, OPCODE_CONSTRUCT, //only for basic types!! OPCODE_CONSTRUCT_ARRAY, OPCODE_CONSTRUCT_DICTIONARY, OPCODE_CALL, OPCODE_CALL_RETURN, OPCODE_CALL_BUILT_IN, OPCODE_CALL_SELF, OPCODE_CALL_SELF_BASE, OPCODE_YIELD, OPCODE_YIELD_SIGNAL, OPCODE_YIELD_RESUME, OPCODE_JUMP, OPCODE_JUMP_IF, OPCODE_JUMP_IF_NOT, OPCODE_JUMP_TO_DEF_ARGUMENT, OPCODE_RETURN, OPCODE_ITERATE_BEGIN, OPCODE_ITERATE, OPCODE_ASSERT, OPCODE_BREAKPOINT, OPCODE_LINE, OPCODE_END }; enum Address { ADDR_BITS=24, ADDR_MASK=((1<<ADDR_BITS)-1), ADDR_TYPE_MASK=~ADDR_MASK, ADDR_TYPE_SELF=0, ADDR_TYPE_CLASS=1, ADDR_TYPE_MEMBER=2, ADDR_TYPE_CLASS_CONSTANT=3, ADDR_TYPE_LOCAL_CONSTANT=4, ADDR_TYPE_STACK=5, ADDR_TYPE_STACK_VARIABLE=6, ADDR_TYPE_GLOBAL=7, ADDR_TYPE_NIL=8 }; struct StackDebug { int line; int pos; bool added; StringName identifier; }; private: friend class GDCompiler; StringName source; mutable Variant nil; mutable Variant *_constants_ptr; int _constant_count; const StringName *_global_names_ptr; int _global_names_count; const int *_default_arg_ptr; int _default_arg_count; const int *_code_ptr; int _code_size; int _argument_count; int _stack_size; int _call_size; int _initial_line; bool _static; GDScript *_script; StringName name; Vector<Variant> constants; Vector<StringName> global_names; Vector<int> default_arguments; Vector<int> code; #ifdef TOOLS_ENABLED Vector<StringName> arg_names; #endif List<StackDebug> stack_debug; _FORCE_INLINE_ Variant *_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self,Variant *p_stack,String& r_error) const; _FORCE_INLINE_ String _get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const; friend class GDScriptLanguage; SelfList<GDFunction> function_list; #ifdef DEBUG_ENABLED CharString func_cname; const char*_func_cname; struct Profile { StringName signature; uint64_t call_count; uint64_t self_time; uint64_t total_time; uint64_t frame_call_count; uint64_t frame_self_time; uint64_t frame_total_time; uint64_t last_frame_call_count; uint64_t last_frame_self_time; uint64_t last_frame_total_time; } profile; #endif public: struct CallState { GDInstance *instance; Vector<uint8_t> stack; int stack_size; Variant self; uint32_t alloca_size; GDScript *_class; int ip; int line; int defarg; Variant result; }; _FORCE_INLINE_ bool is_static() const { return _static; } const int* get_code() const; //used for debug int get_code_size() const; Variant get_constant(int p_idx) const; StringName get_global_name(int p_idx) const; StringName get_name() const; int get_max_stack_size() const; int get_default_argument_count() const; int get_default_argument_addr(int p_idx) const; GDScript *get_script() const { return _script; } void debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const; _FORCE_INLINE_ bool is_empty() const { return _code_size==0; } int get_argument_count() const { return _argument_count; } StringName get_argument_name(int p_idx) const { #ifdef TOOLS_ENABLED ERR_FAIL_INDEX_V(p_idx,arg_names.size(),StringName()); return arg_names[p_idx]; #endif return StringName(); } Variant get_default_argument(int p_idx) const { ERR_FAIL_INDEX_V(p_idx,default_arguments.size(),Variant()); return default_arguments[p_idx]; } Variant call(GDInstance *p_instance,const Variant **p_args, int p_argcount,Variant::CallError& r_err,CallState *p_state=NULL); GDFunction(); ~GDFunction(); }; class GDFunctionState : public Reference { OBJ_TYPE(GDFunctionState,Reference); friend class GDFunction; GDFunction *function; GDFunction::CallState state; Variant _signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error); protected: static void _bind_methods(); public: bool is_valid() const; Variant resume(const Variant& p_arg=Variant()); GDFunctionState(); ~GDFunctionState(); }; #endif // GD_FUNCTION_H
[ "reduzio@gmail.com" ]
reduzio@gmail.com
85ff6e04e93d8e11b3fa48615f969e624b4cb0bf
13727538d2bf70ad83864ee44e5594fa0facd4f5
/task122.cpp
6d9f360a1df8904bf208f072b9e162b805c94387
[]
no_license
shaimerdenova/shaimerdenova
f941299d672e464e7c0de610eac499a44ebc8a64
6039a392ca26d49e6c27409a527fcfc7975e3585
refs/heads/master
2020-09-12T13:59:47.441112
2019-11-22T21:48:21
2019-11-22T21:48:21
222,446,962
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> using namespace std; int main() { int number, count=0; cin >> number; while (number) { if ((number % 10 >3)&&(number%10<8)) { count ++; } number= number/ 10; } cout << count; return 0; }
[ "noreply@github.com" ]
shaimerdenova.noreply@github.com
4ee139897b2bc1b73c79570666d664e3e6e56cae
2c77b4f88e9c3353db2593c0abe9498ae3264d22
/routing/time_tests/wall_time/11x11/main.cpp
588511461b23212af26b3d4fab0152f704dff9a0
[]
no_license
formal-verification-research/IVy-Models
968c79a7315043b70f15addce28ff03ac05a54cd
487cd40efa206fdfe7f17ca61938011714f57c8f
refs/heads/master
2022-05-20T17:07:29.533257
2022-05-04T00:49:03
2022-05-04T00:49:03
218,392,388
1
0
null
null
null
null
UTF-8
C++
false
false
4,976
cpp
#define MAX_X 10 #define MAX_Y 10 #include <iostream> #include <bits/stdc++.h> #include <string> #include <sstream> #include <time.h> #include "Utils.hpp" Count one_fault; Count two_fault; #include "Route.hpp" using namespace std; void make_files(); // void make_makefile(); int main() { struct timespec begin, end; clock_gettime(CLOCK_REALTIME, &begin); make_files(); // make_makefile(); cout << "TERMINATED." << endl; clock_gettime(CLOCK_REALTIME, &end); long seconds = end.tv_sec - begin.tv_sec; int minutes = seconds / 60; ofstream timer("_time.txt", ios::out | ios::app); timer << "Runtime: " << endl; timer << "Total Elapsed time: " << seconds << " seconds" << endl; timer << "Total Elapsed time: " << seconds / 60 << " minutes with " << seconds % 60 << " seconds" << endl; timer << "Total Elapsed time: " << seconds / (60*60) << " hours with " << seconds / 60 << " minutes with " << seconds % 60 << " seconds" << endl; cout << "Runtime: " << endl; cout << "Total Elapsed time: " << seconds << " seconds" << endl; cout << "Total Elapsed time: " << seconds / 60 << " minutes with " << seconds % 60 << " seconds" << endl; cout << "Total Elapsed time: " << seconds / (60*60) << " hours with " << seconds / 60 << " minutes with " << seconds % 60 << " seconds" << endl; return 0; } void make_files() { int cur_x = 0; int cur_y = 0; int dest_x = 0; int dest_y = 0; int faulty_x1 = 0; int faulty_y1 = 0; char faulty_dir1 = 0; int faulty_x2 = 0; int faulty_y2 = 0; char faulty_dir2 = 1; int max_moves_1 = 0; int max_moves_2 = 0; long int t = 0; for (cur_x = 0; cur_x <= MAX_X; cur_x++) { for (cur_y = 0; cur_y <= MAX_Y; cur_y++) { cout << "Testing starting node: " << cur_x << cur_y << " - (1:" << max_moves_1 << " | 2:" << max_moves_2 << ")" << endl; for (dest_x = 0; dest_x <= MAX_X; dest_x++) { for (dest_y = 0; dest_y <= MAX_Y; dest_y++) { // cout << "Testing: " << cur_x << cur_y << " to " << dest_x << dest_y << " - (1:" << max_moves_1 << " | 2:" << max_moves_2 << ")" << endl; for (faulty_x1 = 0; faulty_x1 <= MAX_X; faulty_x1++) { for (faulty_y1 = 0; faulty_y1 <= MAX_Y; faulty_y1++) { for (faulty_dir1 = 0; faulty_dir1 < 4; faulty_dir1++) { //ONE FAULT if ((cur_x != dest_x || cur_y != dest_y)) { if ((faulty_y1 != MAX_Y || faulty_dir1 != 0) && (faulty_x1 != MAX_X || faulty_dir1 != 1) && (faulty_y1 != 0 || faulty_dir1 != 2) && (faulty_x1 != 0 || faulty_dir1 != 3)) { t = route(cur_x, cur_y, dest_x, dest_y, faulty_x1, faulty_y1, faulty_dir1, -9, -9, 'x', one_fault); if (t > max_moves_1 && t != 1000) { max_moves_1 = t; } faulty_x2 = faulty_x1; faulty_y2 = faulty_y1; faulty_dir2 = faulty_dir1; //TWO FAULTS for ( /* blank */ ; faulty_x2 <= MAX_X; faulty_x2++, faulty_y2 = 0) { for ( /* blank */ ; faulty_y2 <= MAX_Y; faulty_y2++, faulty_dir2 = 0) { //changed to 0 // if ((faulty_x2 > faulty_x1 || faulty_y2 > faulty_y1)) { // faulty_dir2 = 0; // } // else { // faulty_dir2 = faulty_dir1; // } for ( /* blank */ ; faulty_dir2 < 4; faulty_dir2++) { if ((cur_x != dest_x || cur_y != dest_y) && (faulty_x1 != faulty_x2 || faulty_y1 != faulty_y2 || faulty_dir1 != faulty_dir2) && (faulty_y2 != MAX_Y || faulty_dir2 != 0) && (faulty_x2 != MAX_X || faulty_dir2 != 1) && (faulty_y2 != 0 || faulty_dir2 != 2) && (faulty_x2 != 0 || faulty_dir2 != 3)) { t = route(cur_x, cur_y, dest_x, dest_y, faulty_x1, faulty_y1, faulty_dir1, faulty_x2, faulty_y2, faulty_dir2, two_fault); if (t > max_moves_2 && t != 1000) { max_moves_2 = t; } } } } } } } } } } } } } } cout << "GENERATING REPORT..." << endl; one_fault.print_report(1, max_moves_1); two_fault.print_report(2, max_moves_2); }
[ "56940292+landonjefftaylor@users.noreply.github.com" ]
56940292+landonjefftaylor@users.noreply.github.com
4f0a28ee1287ba9e0ff101af2e00d045b38db9b3
29868bf4aa31c1ca8b8c86e5b5b07cc3509caf64
/Hoja de calculo/Hoja de calculo/Funcioneshoja.hpp
cbb720e2d9bab68b7f07d1886b1ea087f9c792f5
[]
no_license
Laura-Mora/PC-2016-03
a137746a8c1939235a5176a0ecc2d8234ee87348
0cf0826bdb8a3be89c9da0e70a6726388c6ba0c6
refs/heads/master
2023-07-20T15:16:07.676365
2019-12-30T01:52:28
2019-12-30T01:52:28
222,524,088
0
0
null
null
null
null
UTF-8
C++
false
false
434
hpp
// // Funciones hoja.hpp // Hoja de calculo // // Created by Laura Juliana Mora on 21/08/16. // Copyright © 2016 Laura Juliana Mora. All rights reserved. // #ifndef Funciones_hoja_hpp #define Funciones_hoja_hpp #include <stdio.h> #include <iostream> void crear(char ***hojaInicial, int nfilas, int ncolumnas); void CalcularHoja (char ***hojaInicial, int nfilas, int ncolumnas, int **hojaFinal); #endif /* Funciones_hoja_hpp */
[ "noreply@github.com" ]
Laura-Mora.noreply@github.com
dd09fab0320f33d59d561519f8b98ddbec558577
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
/third_party/WebKit/Source/bindings/core/v8/V8ThrowException.cpp
6b6b1433b32d43aa99bd7b577b53da567d30c65f
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
cool2528/miniblink49
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
7f646289d8074f098cf1244adc87b95e34ab87a8
refs/heads/master
2020-06-05T03:18:43.211372
2019-06-01T08:57:37
2019-06-01T08:59:56
192,294,645
2
0
Apache-2.0
2019-06-17T07:16:28
2019-06-17T07:16:27
null
UTF-8
C++
false
false
7,798
cpp
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "bindings/core/v8/V8ThrowException.h" #include "bindings/core/v8/BindingSecurity.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8DOMException.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" namespace blink { static void domExceptionStackGetter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); v8::Local<v8::Value> value; if (info.Data().As<v8::Object>()->Get(isolate->GetCurrentContext(), v8AtomicString(isolate, "stack")).ToLocal(&value)) v8SetReturnValue(info, value); } static void domExceptionStackSetter(v8::Local<v8::Name> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info) { v8::Maybe<bool> unused = info.Data().As<v8::Object>()->Set(info.GetIsolate()->GetCurrentContext(), v8AtomicString(info.GetIsolate(), "stack"), value); ALLOW_UNUSED_LOCAL(unused); } v8::Local<v8::Value> V8ThrowException::createDOMException(v8::Isolate* isolate, int ec, const String& sanitizedMessage, const String& unsanitizedMessage, const v8::Local<v8::Object>& creationContext) { if (ec <= 0 || v8::V8::IsExecutionTerminating()) return v8Undefined(); ASSERT(ec == SecurityError || unsanitizedMessage.isEmpty()); if (ec == V8GeneralError) return V8ThrowException::createGeneralError(isolate, sanitizedMessage); if (ec == V8TypeError) return V8ThrowException::createTypeError(isolate, sanitizedMessage); if (ec == V8RangeError) return V8ThrowException::createRangeError(isolate, sanitizedMessage); if (ec == V8SyntaxError) return V8ThrowException::createSyntaxError(isolate, sanitizedMessage); if (ec == V8ReferenceError) return V8ThrowException::createReferenceError(isolate, sanitizedMessage); v8::Local<v8::Object> sanitizedCreationContext = creationContext; // FIXME: Is the current context always the right choice? Frame* frame = toFrameIfNotDetached(creationContext->CreationContext()); if (!frame || !BindingSecurity::shouldAllowAccessToFrame(isolate, frame, DoNotReportSecurityError)) sanitizedCreationContext = isolate->GetCurrentContext()->Global(); v8::TryCatch tryCatch(isolate); DOMException* domException = DOMException::create(ec, sanitizedMessage, unsanitizedMessage); v8::Local<v8::Value> exception = toV8(domException, sanitizedCreationContext, isolate); if (tryCatch.HasCaught()) { ASSERT(exception.IsEmpty()); return tryCatch.Exception(); } ASSERT(!exception.IsEmpty()); // Attach an Error object to the DOMException. This is then lazily used to get the stack value. v8::Local<v8::Value> error = v8::Exception::Error(v8String(isolate, domException->message())); ASSERT(!error.IsEmpty()); v8::Local<v8::Object> exceptionObject = exception.As<v8::Object>(); v8::Maybe<bool> result = exceptionObject->SetAccessor(isolate->GetCurrentContext(), v8AtomicString(isolate, "stack"), domExceptionStackGetter, domExceptionStackSetter, v8::MaybeLocal<v8::Value>(error)); ASSERT_UNUSED(result, result.FromJust()); V8HiddenValue::setHiddenValue(isolate, exceptionObject, V8HiddenValue::error(isolate), error); return exception; } v8::Local<v8::Value> V8ThrowException::throwDOMException(int ec, const String& sanitizedMessage, const String& unsanitizedMessage, const v8::Local<v8::Object>& creationContext, v8::Isolate* isolate) { ASSERT(ec == SecurityError || unsanitizedMessage.isEmpty()); v8::Local<v8::Value> exception = createDOMException(isolate, ec, sanitizedMessage, unsanitizedMessage, creationContext); if (exception.IsEmpty()) return v8Undefined(); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::createGeneralError(v8::Isolate* isolate, const String& message) { return v8::Exception::Error(v8String(isolate, message.isNull() ? "Error" : message)); } v8::Local<v8::Value> V8ThrowException::throwGeneralError(v8::Isolate* isolate, const String& message) { v8::Local<v8::Value> exception = V8ThrowException::createGeneralError(isolate, message); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::createTypeError(v8::Isolate* isolate, const String& message) { return v8::Exception::TypeError(v8String(isolate, message.isNull() ? "Type error" : message)); } v8::Local<v8::Value> V8ThrowException::throwTypeError(v8::Isolate* isolate, const String& message) { v8::Local<v8::Value> exception = V8ThrowException::createTypeError(isolate, message); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::createRangeError(v8::Isolate* isolate, const String& message) { return v8::Exception::RangeError(v8String(isolate, message.isNull() ? "Range error" : message)); } v8::Local<v8::Value> V8ThrowException::throwRangeError(v8::Isolate* isolate, const String& message) { v8::Local<v8::Value> exception = V8ThrowException::createRangeError(isolate, message); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::createSyntaxError(v8::Isolate* isolate, const String& message) { return v8::Exception::SyntaxError(v8String(isolate, message.isNull() ? "Syntax error" : message)); } v8::Local<v8::Value> V8ThrowException::throwSyntaxError(v8::Isolate* isolate, const String& message) { v8::Local<v8::Value> exception = V8ThrowException::createSyntaxError(isolate, message); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::createReferenceError(v8::Isolate* isolate, const String& message) { return v8::Exception::ReferenceError(v8String(isolate, message.isNull() ? "Reference error" : message)); } v8::Local<v8::Value> V8ThrowException::throwReferenceError(v8::Isolate* isolate, const String& message) { v8::Local<v8::Value> exception = V8ThrowException::createReferenceError(isolate, message); return V8ThrowException::throwException(exception, isolate); } v8::Local<v8::Value> V8ThrowException::throwException(v8::Local<v8::Value> exception, v8::Isolate* isolate) { if (!v8::V8::IsExecutionTerminating()) isolate->ThrowException(exception); return v8::Undefined(isolate); } } // namespace blink
[ "22249030@qq.com" ]
22249030@qq.com
fbd0098746441c94508bcaca543dc9f2333759b0
608cf243607bfa7a2f4c91298463f2f199ae0ec1
/ios/versioned-react-native/ABI40_0_0/ReactNative/ReactCommon/fabric/components/textinput/iostextinput/ABI40_0_0TextInputState.cpp
ac286d1cbb48b409f1d4ab26f75c19baed0f00fc
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
kodeco835/symmetrical-happiness
ca79bd6c7cdd3f7258dec06ac306aae89692f62a
4f91cb07abef56118c35f893d9f5cc637b9310ef
refs/heads/master
2023-04-30T04:02:09.478971
2021-03-23T03:19:05
2021-03-23T03:19:05
350,565,410
0
1
MIT
2023-04-12T19:49:48
2021-03-23T03:18:02
Objective-C
UTF-8
C++
false
false
346
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ABI40_0_0TextInputState.h" namespace ABI40_0_0facebook { namespace ABI40_0_0React {} // namespace ABI40_0_0React } // namespace ABI40_0_0facebook
[ "81201147+kodeco835@users.noreply.github.com" ]
81201147+kodeco835@users.noreply.github.com
ee01d31d31fc28f98c1be8d6a5ddefb9ec4b4b22
8d8e64230c6abcad18aa3fb6ae10d1f03e6d0c99
/NetworkDriveServer/NetworkDriveServer.cpp
81db15ecf817a0eee9dd08aad8fe14538af67fab
[]
no_license
shi-yan/QtDokanyExamples
1462c13ceee52292d89175faf41b69245fab57b7
93e94c2120712f82898e9585694272b9daa6fa33
refs/heads/master
2021-01-10T03:51:12.621096
2016-01-12T22:48:35
2016-01-12T22:48:35
47,361,247
4
0
null
null
null
null
UTF-8
C++
false
false
24,300
cpp
#include "NetworkDriveServer.h" #include <QDataStream> #include "FileSystemThread.h" NetworkDriveServer::RequestBarrier::RequestBarrier(qint32 messageId) :m_messageId(messageId) { } NetworkDriveServer::RequestBarrier::~RequestBarrier() { } void NetworkDriveServer::RequestBarrier::acquire() { m_semaphore.acquire(); } void NetworkDriveServer::RequestBarrier::release() { m_semaphore.release(); } void NetworkDriveServer::RequestBarrier::dumpData(const QByteArray &data) { quint32 offset = sizeof(quint32) + sizeof(qint32); m_data.append(data.data() + offset, data.size() - offset); } void NetworkDriveServer::RequestBarrier::getData(QByteArray &out) { out.append(m_data); } NetworkDriveServer::NetworkDriveServer() :QTcpServer(), m_socket(NULL), m_currentDataSize(-1) { } void NetworkDriveServer::incomingConnection(qintptr handle) { if (!m_socket) { m_socket = new QTcpSocket(this); connect(this, SIGNAL(sendMessageToClient(QByteArray*)),this,SLOT(onSendMessageToClient(QByteArray*)), Qt::QueuedConnection); connect(m_socket, SIGNAL(readyRead()),this,SLOT(onSocketReadyRead())); m_socket->setSocketDescriptor(handle); } } void NetworkDriveServer::onSocketReadyRead() { //qDebug() << "server received something"; m_dataBuffer.append(m_socket->readAll()); processData(); } void NetworkDriveServer::processData() { while(1) { if (m_currentDataSize == -1) { if (m_dataBuffer.size() < sizeof(quint32)) { return; } else { QDataStream stream(m_dataBuffer); quint32 size; stream >> size; m_currentDataSize = size; qDebug() << m_currentDataSize; m_dataBuffer.remove(0, sizeof(quint32)); } } if (m_currentDataSize != -1 && m_dataBuffer.size() >= m_currentDataSize) { QByteArray messageData(m_dataBuffer.data(), m_currentDataSize); m_dataBuffer.remove(0, m_currentDataSize); m_currentDataSize = -1; processMessage(messageData); } else { return; } } } void NetworkDriveServer::processMessage(QByteArray &message) { QDataStream messageStream(message); quint32 messageType = 0; messageStream >> messageType; qint32 messageId = 0; messageStream >> messageId; qDebug() << "server process message" << messageType << messageId; switch(messageType) { case MOUNT: { QString directory; QString letter; messageStream >> directory >> letter; qDebug() << "mount" << directory << "as drive" << letter; FileSystemThread *fsThread = new FileSystemThread(directory, letter, this); fsThread->start(); } break; case UNMOUNT: break; case CREATE_FILE: //qDebug() << "create file"; m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case CLOSE_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case CLEAN_UP_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case READ_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case WRITE_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case FLUSH_FILE_BUFFERS: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case GET_FILE_INFORMATION: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case FIND_FILES: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case DELETE_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case DELETE_DIRECTORY: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case MOVE_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case LOCK_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case SET_END_OF_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case SET_ALLOCATION_SIZE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case SET_FILE_ATTRIBUTES: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case SET_FILE_TIME: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case UNLOCK_FILE: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case GET_FILE_SECURITY: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case SET_FILE_SECURITY: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case GET_VOLUME_INFORMATION: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; case ENUMERATE_NAMED_STREAMS: m_semaphoreTable[messageId]->dumpData(message); m_semaphoreTable[messageId]->release(); break; } } void NetworkDriveServer::remoteCreateFile(QByteArray &result,const QString &filePath, quint64 AccessMode, quint64 CreateDisposition, quint64 CreateOptions) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = CREATE_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId << filePath << AccessMode << CreateDisposition << CreateOptions; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); //qDebug() << "-------- before the acquire"; semaphore->acquire(); //qDebug() << "-------- after the acquire"; semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteCloseFile(QByteArray &result,const QString &filePath, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = CLOSE_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteCleanUp(QByteArray &result,const QString &filePath, quint64 DokanFileInfo_context, bool DokanFileInfo_deleteOnClose) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = CLEAN_UP_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << DokanFileInfo_context << DokanFileInfo_deleteOnClose; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteReadFile(QByteArray &result,const QString &filePath, quint64 BufferLength, quint64 Offset, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = READ_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << BufferLength << Offset << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteWriteFile(QByteArray &result,const QString &filePath, char *buffer, quint64 NumberOfBytesToWrite, quint64 Offset, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = WRITE_FILE; qint32 currentMessageId = m_messageId++; QByteArray dataBuffer(buffer, NumberOfBytesToWrite); messageDataStream << messageType << currentMessageId <<filePath << NumberOfBytesToWrite << Offset << DokanFileInfo_context << dataBuffer; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteFlushFileBuffers(QByteArray &result,const QString &filePath, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = FLUSH_FILE_BUFFERS; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteGetFileInformation(QByteArray &result,const QString &filePath, bool DokanFileInfo_isDirectory) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = GET_FILE_INFORMATION; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << DokanFileInfo_isDirectory; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteFindFiles(QByteArray &result,const QString &filePath) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = FIND_FILES; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteDeleteFile(QByteArray &result,const QString &filePath) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = DELETE_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteDeleteDirectory(QByteArray &result,const QString &filePath) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = DELETE_DIRECTORY; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteMoveFile(QByteArray &result,const QString &filePath, const QString &NewFileName, bool ReplaceIfExisting) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = MOVE_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << NewFileName << ReplaceIfExisting; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteLockFile(QByteArray &result,const QString &filePath, quint64 ByteOffset, quint64 Length, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = LOCK_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << ByteOffset << Length << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteSetEndOfFile(QByteArray &result,const QString &filePath, quint64 ByteOffset, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = SET_END_OF_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << ByteOffset << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteSetAllocationSize(QByteArray &result,const QString &filePath, quint64 AllocSize, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = SET_ALLOCATION_SIZE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << AllocSize << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteSetFileAttributes(QByteArray &result,const QString &filePath, quint64 FileAttributes, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = SET_FILE_ATTRIBUTES; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << FileAttributes << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteSetFileTime(QByteArray &result,const QString &filePath, QDateTime &CreationTime, QDateTime &LastAccessTime, QDateTime &LastWriteTime, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = SET_FILE_TIME; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << CreationTime << LastAccessTime <<LastWriteTime << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteUnlockFile(QByteArray &result,const QString &filePath, quint64 ByteOffset, quint64 Length, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = UNLOCK_FILE; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << ByteOffset << Length << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteGetFileSecurity(QByteArray &result,const QString &filePath, quint64 SecurityInformation, quint64 SecurityDescriptor, quint64 BufferLength, quint64 LengthNeeded, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = GET_FILE_SECURITY; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << SecurityInformation << SecurityDescriptor << BufferLength << LengthNeeded << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteSetFileSecurity(QByteArray &result,const QString &filePath, quint64 SecurityInformation, quint64 SecurityDescriptor, quint64 SecurityDescriptorLength, quint64 DokanFileInfo_context) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = SET_FILE_SECURITY; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<filePath << SecurityInformation << SecurityDescriptor<< SecurityDescriptorLength << DokanFileInfo_context; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteGetVolumeInformation(QByteArray &result,const QString &VolumeNameBuffer, quint64 VolumeNameSize, quint64 VolumeSerialNumber, quint64 MaximumComponentLength, const QString &FileSystemFlags, const QString &FileSystemNameBuffer, quint64 FileSystemNameSize) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = GET_VOLUME_INFORMATION; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId <<VolumeNameBuffer << VolumeNameSize << VolumeSerialNumber << MaximumComponentLength << FileSystemFlags << FileSystemNameBuffer << FileSystemNameSize; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteUnmount() { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = UNMOUNT; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); // semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::remoteEnumerateNamedStreams(QByteArray &result,const QString &filePath, quint64 EnumContext, const QString &StreamName, quint64 StreamNameLength, quint64 StreamSize) { QByteArray *messageArray = new QByteArray(); QDataStream messageDataStream(messageArray, QIODevice::WriteOnly); quint32 messageType = ENUMERATE_NAMED_STREAMS; qint32 currentMessageId = m_messageId++; messageDataStream << messageType << currentMessageId << filePath << EnumContext << StreamName << StreamNameLength << StreamSize; RequestBarrier *semaphore = new RequestBarrier(currentMessageId); m_semaphoreTable[currentMessageId] = semaphore; emit sendMessageToClient(messageArray); semaphore->acquire(); semaphore->getData(result); m_semaphoreTable.remove(currentMessageId); delete semaphore; } void NetworkDriveServer::onSendMessageToClient(QByteArray *data) { if (m_socket) { QByteArray sizeData; QDataStream sds(&sizeData, QIODevice::WriteOnly); sds << (quint32) data->size(); m_socket->write(sizeData); m_socket->write(*data); } if (data) { delete data; } }
[ "billconan@gmail.com" ]
billconan@gmail.com
8a681b25fda8b2401d2db6a82a6f5170e27f84e6
35f575c997f226e4662ae214735e29186e93d1bf
/dependencies/Ogre/src/Components/MeshLodGenerator/src/OgreLodCollapser.cpp
a65051dc14d6f20d9683b73c6e2ff80b8c5a4b1c
[ "MIT", "Apache-2.0" ]
permissive
PTSD-3D/PTSD-Engine
b227aa52b9f948a7794c0075295e70d4a71c4353
2f523b8a7fd768c8e3cfd634e53d8c34b3b359ef
refs/heads/main
2023-05-04T03:25:26.093194
2021-05-27T21:10:25
2021-05-27T21:10:25
345,047,719
3
0
Apache-2.0
2021-05-27T21:10:26
2021-03-06T08:50:35
C++
UTF-8
C++
false
false
13,886
cpp
/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2014 Torus Knot Software Ltd * * 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 "OgreMeshLodPrecompiledHeaders.h" namespace Ogre { void LodCollapser::collapse( LodData* data, LodCollapseCost* cost, LodOutputProvider* output, int vertexCountLimit, Real collapseCostLimit ) { while (data->mCollapseCostHeap.size() > static_cast<size_t>(vertexCountLimit)) { LodData::CollapseCostHeap::iterator nextVertex = data->mCollapseCostHeap.begin(); if (nextVertex->first < collapseCostLimit) { mLastReducedVertex = nextVertex->second; collapseVertex(data, cost, output, mLastReducedVertex); } else { break; } } } #if OGRE_DEBUG_MODE void LodCollapser::assertValidMesh(LodData* data) { // Allows to find bugs in collapsing. // size_t s1 = mUniqueVertexSet.size(); // size_t s2 = mCollapseCostHeap.size(); LodData::CollapseCostHeap::iterator it = data->mCollapseCostHeap.begin(); LodData::CollapseCostHeap::iterator itEnd = data->mCollapseCostHeap.end(); while (it != itEnd) { assertValidVertex(data, it->second); it++; } } void LodCollapser::assertValidVertex(LodData* data, LodData::Vertex* v) { // Allows to find bugs in collapsing. LodData::VTriangles::iterator it = v->triangles.begin(); LodData::VTriangles::iterator itEnd = v->triangles.end(); for (; it != itEnd; it++) { LodData::Triangle* t = *it; for (int i = 0; i < 3; i++) { OgreAssert(t->vertex[i]->costHeapPosition != data->mCollapseCostHeap.end(), ""); t->vertex[i]->edges.findExists(LodData::Edge(t->vertex[i]->collapseTo)); for (int n = 0; n < 3; n++) { if (i != n) { LodData::VEdges::iterator edgeIt = t->vertex[i]->edges.findExists(LodData::Edge(t->vertex[n])); OgreAssert(edgeIt->collapseCost != LodData::UNINITIALIZED_COLLAPSE_COST, ""); } else { OgreAssert(t->vertex[i]->edges.find(LodData::Edge(t->vertex[n])) == t->vertex[i]->edges.end(), ""); } } } } } void LodCollapser::assertOutdatedCollapseCost( LodData* data, LodCollapseCost* cost, LodData::Vertex* vertex ) { // Validates that collapsing has updated all edges needed by computeEdgeCollapseCost. // This will OgreAssert if the dependencies inside computeEdgeCollapseCost changes. LodData::VEdges::iterator it = vertex->edges.begin(); LodData::VEdges::iterator itEnd = vertex->edges.end(); for (; it != itEnd; it++) { OgreAssert(it->collapseCost == cost->computeEdgeCollapseCost(data, vertex, &*it), ""); LodData::Vertex* neighbor = it->dst; LodData::VEdges::iterator it2 = neighbor->edges.begin(); LodData::VEdges::iterator it2End = neighbor->edges.end(); for (; it2 != it2End; it2++) { OgreAssert(it2->collapseCost == cost->computeEdgeCollapseCost(data, neighbor, &*it2), ""); } } } #endif // if OGRE_DEBUG_MODE bool LodCollapser::hasSrcID(unsigned int srcID, size_t submeshID) { // This will only return exact matches. for (size_t i = 0; i < tmpCollapsedEdges.size(); i++) { if (tmpCollapsedEdges[i].srcID == srcID && tmpCollapsedEdges[i].submeshID == submeshID) { return true; } } return false; // Not found } void LodCollapser::removeTriangleFromEdges(LodData::Triangle* triangle, LodData::Vertex* skip) { triangle->isRemoved = true; // skip is needed if we are iterating on the vertex's edges or triangles. for (int i = 0; i < 3; i++) { if (triangle->vertex[i] != skip) { triangle->vertex[i]->triangles.removeExists(triangle); } } for (int i = 0; i < 3; i++) { for (int n = 0; n < 3; n++) { if (i != n && triangle->vertex[i] != skip) { triangle->vertex[i]->removeEdge(LodData::Edge(triangle->vertex[n])); } } } } size_t LodCollapser::findDstID(unsigned int srcID, size_t submeshID) { // Tries to find a compatible edge. // Exact match search. for (size_t i = 0; i < tmpCollapsedEdges.size(); i++) { if (tmpCollapsedEdges[i].srcID == srcID && tmpCollapsedEdges[i].submeshID == submeshID) { return i; } } // Usable match search. for (size_t i = 0; i < tmpCollapsedEdges.size(); i++) { if (tmpCollapsedEdges[i].submeshID == submeshID) { return i; } } return std::numeric_limits<size_t>::max(); // Not found } void LodCollapser::replaceVertexID(LodData::Triangle* triangle, unsigned int oldID, unsigned int newID, LodData::Vertex* dst) { dst->triangles.addNotExists(triangle); // NOTE: triangle is not removed from src. This is implementation specific optimization. // Its up to the compiler to unroll everything. for (int i = 0; i < 3; i++) { if (triangle->vertexID[i] == oldID) { for (int n = 0; n < 3; n++) { if (i != n) { // This is implementation specific optimization to remove following line. // triangle->vertex[i]->removeEdge(LodData::Edge(triangle->vertex[n])); triangle->vertex[n]->removeEdge(LodData::Edge(triangle->vertex[i])); triangle->vertex[n]->addEdge(LodData::Edge(dst)); dst->addEdge(LodData::Edge(triangle->vertex[n])); } } triangle->vertex[i] = dst; triangle->vertexID[i] = newID; return; } } OgreAssert(0, ""); } void LodCollapser::collapseVertex( LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodData::Vertex* src ) { LodData::Vertex* dst = src->collapseTo; #if OGRE_DEBUG_MODE assertValidVertex(data, dst); assertValidVertex(data, src); #endif OgreAssert(src->costHeapPosition->first != LodData::NEVER_COLLAPSE_COST, ""); OgreAssert(src->costHeapPosition->first != LodData::UNINITIALIZED_COLLAPSE_COST, ""); OgreAssert(!src->edges.empty(), ""); OgreAssert(!src->triangles.empty(), ""); OgreAssert(src->edges.find(LodData::Edge(dst)) != src->edges.end(), ""); // It may have vertexIDs and triangles from different submeshes(different vertex buffers), // so we need to connect them correctly based on deleted triangle's edge. // mCollapsedEdgeIDs will be used, when looking up the connections for replacement. tmpCollapsedEdges.clear(); LodData::VTriangles::iterator it = src->triangles.begin(); LodData::VTriangles::iterator itEnd = src->triangles.end(); for (; it != itEnd; ++it) { LodData::Triangle* triangle = *it; if (triangle->hasVertex(dst)) { // Remove a triangle // Tasks: // 1. Add it to the collapsed edges list. // 2. Reduce index count for the Lods, which will not have this triangle. // 3. Remove references/pointers to this triangle and mark as removed. // 1. task unsigned int srcID = triangle->getVertexID(src); if (!hasSrcID(srcID, triangle->submeshID)) { tmpCollapsedEdges.push_back(CollapsedEdge()); tmpCollapsedEdges.back().srcID = srcID; tmpCollapsedEdges.back().dstID = triangle->getVertexID(dst); tmpCollapsedEdges.back().submeshID = triangle->submeshID; } // 2. task data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; output->triangleRemoved(data, triangle); // 3. task removeTriangleFromEdges(triangle, src); } } OgreAssert(tmpCollapsedEdges.size(), ""); OgreAssert(dst->edges.find(LodData::Edge(src)) == dst->edges.end(), ""); it = src->triangles.begin(); for (; it != itEnd; ++it) { LodData::Triangle* triangle = *it; if (!triangle->hasVertex(dst)) { // Replace a triangle // Tasks: // 1. Determine the edge which we will move along. (we need to modify single vertex only) // 2. Move along the selected edge. // 1. task unsigned int srcID = triangle->getVertexID(src); size_t id = findDstID(srcID, triangle->submeshID); if (id == std::numeric_limits<size_t>::max()) { // Not found any edge to move along. // Destroy the triangle. data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; output->triangleRemoved(data, triangle); removeTriangleFromEdges(triangle, src); continue; } unsigned int dstID = tmpCollapsedEdges[id].dstID; // 2. task replaceVertexID(triangle, srcID, dstID, dst); output->triangleChanged(data, triangle); #if MESHLOD_QUALITY >= 3 triangle->computeNormal(); #endif } } dst->seam |= src->seam; // Inherit seam property #if MESHLOD_QUALITY <= 2 LodData::VEdges::iterator it3 = src->edges.begin(); LodData::VEdges::iterator it3End = src->edges.end(); for (; it3 != it3End; ++it3) { cost->updateVertexCollapseCost(data, it3->dst); } #else // TODO: Find out why is this needed. assertOutdatedCollapseCost() fails on some // rare situations without this. For example goblin.mesh fails. typedef SmallVector<LodData::Vertex*, 64> UpdatableList; UpdatableList updatable; LodData::VEdges::iterator it3 = src->edges.begin(); LodData::VEdges::iterator it3End = src->edges.end(); for (; it3 != it3End; it3++) { updatable.push_back(it3->dst); LodData::VEdges::iterator it4End = it3->dst->edges.end(); LodData::VEdges::iterator it4 = it3->dst->edges.begin(); for (; it4 != it4End; it4++) { updatable.push_back(it4->dst); } } // Remove duplicates. UpdatableList::iterator it5 = updatable.begin(); UpdatableList::iterator it5End = updatable.end(); std::sort(it5, it5End); it5End = std::unique(it5, it5End); for (; it5 != it5End; it5++) { cost->updateVertexCollapseCost(data, *it5); } #if OGRE_DEBUG_MODE it3 = src->edges.begin(); it3End = src->edges.end(); for (; it3 != it3End; it3++) { assertOutdatedCollapseCost(data, cost, it3->dst); } it3 = dst->edges.begin(); it3End = dst->edges.end(); for (; it3 != it3End; it3++) { assertOutdatedCollapseCost(data, cost, it3->dst); } assertOutdatedCollapseCost(data, cost, dst); #endif // ifndef OGRE_DEBUG_MODE #endif // ifndef MESHLOD_QUALITY data->mCollapseCostHeap.erase(src->costHeapPosition); // Remove src from collapse costs. src->edges.clear(); // Free memory src->triangles.clear(); // Free memory #if OGRE_DEBUG_MODE src->costHeapPosition = data->mCollapseCostHeap.end(); assertValidVertex(data, dst); #endif } bool LodCollapser::_getLastVertexPos(LodData* data, Vector3& outVec) { if(mLastReducedVertex){ outVec = mLastReducedVertex->position; return true; } else { return false; } } bool LodCollapser::_getLastVertexCollapseTo(LodData* data, Vector3& outVec ) { if(mLastReducedVertex){ outVec = mLastReducedVertex->collapseTo->position; return true; } else { return false; } } }
[ "adralv01@ucm.es" ]
adralv01@ucm.es
aabe3650feaf4dbcdbfdbcc4c0ae9ad3e3321ede
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/Windows-classic-samples/Samples/Win7Samples/winui/shell/appshellintegration/PlaylistPropertyHandler/Dll.h
aa904acc374557e55a5b3a5026f4cfd2b811ac97
[ "MIT" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
607
h
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include <windows.h> #include <new> // std::nothrow class __declspec(uuid("a8090ad8-8f40-4c62-85b7-28fd60244ade")) CPlaylistPropertyHandler; HRESULT CPlaylistPropertyHandler_CreateInstance(REFIID riid, void **ppv); HRESULT RegisterHandler(); HRESULT UnregisterHandler(); void DllAddRef(); void DllRelease();
[ "126.org@gmail.com" ]
126.org@gmail.com
d79dd4aa58331d61cba37d6ec5bbe9964343b766
a1abe87ee9e276ba60d26a63378c4ea3e35d7517
/Source/SpriteRender/INTERFACE/CONFIG/SpriteRenderConfig.cpp
be7475b601c98f7f191b7030d034881a64a6bbbd
[]
no_license
AlexeyOgurtsov/SpriteRender
c3b1f855c4f869d3b60091a048beecf270577908
f3eb9945dbc1f059fd0b0398ffc5557f7c086f13
refs/heads/master
2020-03-30T23:29:59.105528
2019-02-14T08:05:01
2019-02-14T08:05:01
151,702,572
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
#include "SpriteRenderConfig.h" namespace Dv { namespace Spr { namespace Ren { SConfig::SConfig(const SMinimalConfig& InMinimalConfig) : Log{InMinimalConfig.pLog} , Device{ InMinimalConfig.pDev, InMinimalConfig.pDevCon } , RenderTarget{ InMinimalConfig.RTWidth, InMinimalConfig.RTHeight, InMinimalConfig.pRTView, InMinimalConfig.pDepthStencilView } , Shaders{ InMinimalConfig.ShaderOutputDirectory } , InitialSpriteBufferCapacity{ INITIAL_SPRITE_BUFFER_CAPACITY } { } } // Dv::Spr::Ren } // DV::Spr } // Dv
[ "alexey_eng@mail.ru" ]
alexey_eng@mail.ru
f5ab521c71bee25715579963ebe3f242360fd8d4
2844845145012af7b7cf55bed4be87c613245baa
/dlls/ent_locus.cpp
1c58ba3df1cdbf1e2180f5bc8890ceb6ec16f601
[]
no_license
HLSources/Tyrian-GroundAssault
2ed627558e5902c63ce04d4b9e2e7237565f74f1
9411deab882dd4ae444c0e24debe5bbbff9cfc50
refs/heads/master
2023-01-31T03:30:12.157694
2020-12-03T12:32:34
2020-12-03T12:32:34
318,186,713
1
0
null
null
null
null
ISO-8859-10
C++
false
false
26,192
cpp
//========================================= // NEW file for Spirit of Half-Life 0.7 // Created 14/01/02 //========================================= // Spirit of Half-Life's particle system uses "locus triggers" to tell // entities where to perform their actions. // XDM: unblelievable that such dirty code got here #include "extdll.h" #include "util.h" #include "cbase.h" #include "ent_locus.h" #include "ent_functional.h" #include "ent_alias.h" #include "effects.h" #include "decals.h" Vector CalcLocus_Position(CBaseEntity *pEntity, CBaseEntity *pLocus, const char *szText) { if (isdigit(*szText) || *szText == '-')// XDM3035c: wheel {// it's a vector Vector tmp; if (!UTIL_StringToRandomVector((float *)tmp, szText)) ALERT(at_console, "%s %s bad calc_position vector \"%s\"\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->targetname), szText); return tmp; } CBaseEntity *pCalc = UTIL_FindEntityByTargetname(NULL, szText, pLocus); if (pCalc != NULL) return pCalc->CalcPosition(pLocus); ALERT(at_error, "%s \"%s\" has bad or missing calc_position value \"%s\"\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->targetname), szText); return g_vecZero; } Vector CalcLocus_Velocity(CBaseEntity *pEntity, CBaseEntity *pLocus, const char *szText) { if (isdigit(*szText) || *szText == '-')// XDM3035c: wheel {// it's a vector Vector tmp; if (!UTIL_StringToRandomVector((float *)tmp, szText)) ALERT(at_console, "%s %s bad calc_velocity vector \"%s\"\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->targetname), szText); return tmp; } CBaseEntity *pCalc = UTIL_FindEntityByTargetname(NULL, szText, pLocus); if (pCalc != NULL) return pCalc->CalcVelocity(pLocus); ALERT(at_error, "%s \"%s\" has bad or missing calc_velocity value \"%s\"\n", STRING(pEntity->pev->classname), STRING(pEntity->pev->targetname), szText); return g_vecZero; } float CalcLocus_Ratio(CBaseEntity *pLocus, const char *szText, int mode) //AJH added 'mode' = ratio to return { if (isdigit(*szText) || *szText == '-')// XDM3035c: wheel return atof(szText);// assume it's a float CBaseEntity *pCalc = UTIL_FindEntityByTargetname(NULL, szText, pLocus); if (pCalc != NULL) { //ALERT(at_debug,"Entity \"%s\" found, calling CalcRatio, mode %i.\n",szText,mode); return pCalc->CalcRatio(pLocus); } else { ALERT(at_aiconsole, "Bad or missing calc_ratio entity \"%s\", mode %i\n", szText,mode); // MJB/AJH - might need to be supressed; this error is often returned when there is no error return 0; // we need some signal for "fail". NaN, maybe? } } float CalcLocus_Ratio(CBaseEntity *pLocus, const char *szText) //AJH calls new CalcLocusRatio { return CalcLocus_Ratio(pLocus,szText,0); } //============================================= //locus_x effects //============================================= LINK_ENTITY_TO_CLASS(locus_alias, CLocusAlias); TYPEDESCRIPTION CLocusAlias::m_SaveData[] = { DEFINE_FIELD(CLocusAlias, m_hValue, FIELD_EHANDLE), DEFINE_FIELD(CLocusAlias, m_hChangeTo, FIELD_EHANDLE), }; IMPLEMENT_SAVERESTORE(CLocusAlias, CBaseAlias); void CLocusAlias::PostSpawn(void) { m_hValue = UTIL_FindEntityByTargetname(NULL, STRING(pev->netname)); } void CLocusAlias::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { m_hChangeTo = pActivator; UTIL_AddToAliasList(this); } void CLocusAlias::FlushChanges(void) { m_hValue = m_hChangeTo; m_hChangeTo = NULL; } CBaseEntity *CLocusAlias::FollowAlias(CBaseEntity *pFrom) { if (m_hValue == NULL) return NULL; else if (pFrom == NULL || (OFFSET(m_hValue->pev) > OFFSET(pFrom->pev))) { // ALERT(at_console, "LocusAlias returns %s: %f %f %f\n", STRING(m_pValue->pev->targetname), m_pValue->pev->origin.x, m_pValue->pev->origin.y, m_pValue->pev->origin.z); return m_hValue; } else return NULL; } //============================================= //calc_x entities //============================================= LINK_ENTITY_TO_CLASS(calc_position, CCalcPosition); Vector CCalcPosition::CalcPosition(CBaseEntity *pLocus) { CBaseEntity *pSubject = UTIL_FindEntityByTargetname(NULL, STRING(pev->netname), pLocus); Vector vecOffset = CalcLocus_Velocity( this, pLocus, STRING(pev->message)); Vector vecPosition; Vector vecJunk; Vector vecResult; switch (pev->impulse) { case 1: //eyes vecResult = vecOffset + pSubject->EyePosition(); //ALERT(at_console, "calc_subpos returns %f %f %f\n", vecResult.x, vecResult.y, vecResult.z); return vecResult; //return vecOffset + pLocus->EyePosition(); case 2: // top return vecOffset + pSubject->pev->origin + Vector( (pSubject->pev->mins.x + pSubject->pev->maxs.x)/2, (pSubject->pev->mins.y + pSubject->pev->maxs.y)/2, pSubject->pev->maxs.z); case 3: // centre return vecOffset + pSubject->pev->origin + Vector( (pSubject->pev->mins.x + pSubject->pev->maxs.x)/2, (pSubject->pev->mins.y + pSubject->pev->maxs.y)/2, (pSubject->pev->mins.z + pSubject->pev->maxs.z)/2); case 4: // bottom return vecOffset + pSubject->pev->origin + Vector( (pSubject->pev->mins.x + pSubject->pev->maxs.x)/2, (pSubject->pev->mins.y + pSubject->pev->maxs.y)/2, pSubject->pev->mins.z); case 5: // this could cause problems. // is there a good way to check whether it's really a CBaseAnimating? // assume if (GET_MODEL_PTR(pSubject->edict()) /// ((CBaseAnimating *)pSubject)->GetAttachment( 0, vecPosition, vecJunk ); // XDM: oh well, THEN DON'T DO IT! I suppose RTTI is a good thing too. GET_ATTACHMENT(ENT(pSubject->pev), 0, vecPosition, vecJunk); return vecOffset + vecPosition; case 6: //((CBaseAnimating *)pSubject)->GetAttachment( 1, vecPosition, vecJunk ); GET_ATTACHMENT(ENT(pSubject->pev), 1, vecPosition, vecJunk); return vecOffset + vecPosition; case 7: //((CBaseAnimating *)pSubject)->GetAttachment( 2, vecPosition, vecJunk ); GET_ATTACHMENT(ENT(pSubject->pev), 2, vecPosition, vecJunk); return vecOffset + vecPosition; case 8: //((CBaseAnimating *)pSubject)->GetAttachment( 3, vecPosition, vecJunk ); GET_ATTACHMENT(ENT(pSubject->pev), 3, vecPosition, vecJunk); return vecOffset + vecPosition; case 9: return vecOffset + pSubject->pev->origin + RandomVectors(pSubject->pev->mins, pSubject->pev->maxs); /* Vector( RANDOM_FLOAT(pSubject->pev->mins.x, pSubject->pev->maxs.x), RANDOM_FLOAT(pSubject->pev->mins.y, pSubject->pev->maxs.y), RANDOM_FLOAT(pSubject->pev->mins.z, pSubject->pev->maxs.z));*/ default: return vecOffset + pSubject->pev->origin; } } //======================================================= LINK_ENTITY_TO_CLASS(calc_ratio, CCalcRatio); float CCalcRatio::CalcRatio(CBaseEntity *pLocus, int mode) //AJH 'mode' (ratio to return is overridden) { //ALERT(at_debug,"Calc_ratio 'ratio_to_return' is %i\n",pev->skin); float fBasis = CalcLocus_Ratio(pLocus, STRING(pev->target),pev->skin); //AJH pev->skin is 'ratio to return' switch (pev->impulse) { case 1: fBasis = 1-fBasis; break; //reversed case 2: fBasis = -fBasis; break; //negative case 3: fBasis = 1/fBasis; break; //reciprocal } fBasis += CalcLocus_Ratio(pLocus, STRING(pev->netname),pev->body); //AJH pev->body is 'ratio to return' fBasis = fBasis * CalcLocus_Ratio(pLocus, STRING(pev->message),pev->button);//AJH pev->iuser3 is 'ratio to return' if (!FStringNull(pev->noise)) { float fMin = CalcLocus_Ratio( pLocus, STRING(pev->noise)); if (!FStringNull(pev->noise1)) { float fMax = CalcLocus_Ratio( pLocus, STRING(pev->noise1)); if (fBasis >= fMin && fBasis <= fMax) return fBasis; switch ((int)pev->frags) { case 0: if (fBasis < fMin) return fMin; else return fMax; case 1: while (fBasis < fMin) fBasis += fMax - fMin; while (fBasis > fMax) fBasis -= fMax - fMin; return fBasis; case 2: while (fBasis < fMin || fBasis > fMax) { if (fBasis < fMin) fBasis = fMin + fMax - fBasis; else fBasis = fMax + fMax - fBasis; } return fBasis; } } if (fBasis > fMin) return fBasis; else return fMin; // crop to nearest value } else if (!FStringNull(pev->noise1)) { float fMax = CalcLocus_Ratio( pLocus, STRING(pev->noise1)); if (fBasis < fMax) return fBasis; else return fMax; // crop to nearest value } else return fBasis; } /*// calc_angletransform by MJB. #define SF_ANGLETRANS_DEBUG 1 // MJB - debug info class CCalcAngleTransform : public CPointEntity { public: Vector CalcVelocity( CBaseEntity *pLocus ); }; LINK_ENTITY_TO_CLASS( calc_angletransform, CCalcAngleTransform ); Vector CCalcAngleTransform::CalcVelocity( CBaseEntity *pLocus ) { Vector vecBasis1 = CalcLocus_Velocity( this, pLocus, STRING(pev->netname)); // netname: input 1 velocity if (pev->modelindex != 0) { // modelindex: is 0 - Y Z X vecBasis1 = UTIL_VecToAngles( vecBasis1 ); // is 1 - [LV] if(pev->spawnflags & SF_ANGLETRANS_DEBUG) ALERT(at_debug,"VecToAngles(vecBasis1)\n"); // WOOT! Gotcha lil' bastard! You'll never deceive me again. } float basis1; switch(pev->skin) { // skin: input 1 axis case 0:basis1=vecBasis1.x;break; case 1:basis1=vecBasis1.y;break; case 2:basis1=vecBasis1.z;break; default:ALERT(at_debug,"Invalid input-1 axis\n");break; } Vector vecBasis2 = CalcLocus_Velocity( this, pLocus, STRING(pev->message)); // message: input 2 velocity if (pev->button != 0) { // button: is 0 - Y Z X vecBasis2 = UTIL_VecToAngles( vecBasis2 ); // is 1 - [LV] if(pev->spawnflags & SF_ANGLETRANS_DEBUG) ALERT(at_debug,"VecToAngles(vecBasis2)\n"); // WOOT! And the same to you! } float basis2; switch(pev->body) { // body: input 2 axis case 0:basis2=vecBasis2.x;break; case 1:basis2=vecBasis2.y;break; case 2:basis2=vecBasis2.z;break; default:ALERT(at_debug,"Invalid input-2 axis\n");break; } float pi = 3.14159; float transformation; switch(pev->effects) { // effects: choose calculation case 0:transformation=basis1;break; // output = basis1 case 1:transformation=basis1+basis2;break; // add case 2:transformation=basis1-basis2;break; // subtract case 3:transformation=basis1*basis2;break; // multiply case 4:transformation=basis1/basis2;break; // divide case 5:transformation=basis1*sin(basis2*pi/180);break; // basis1 * sin(basis2) case 6:transformation=basis1*cos(basis2*pi/180);break; // basis1 * cos(basis2) case 7:transformation=basis1*tan(basis2*pi/180);break; // basis1 * tan(basis2) case 8:transformation=basis1*(transformation=sin(basis2*pi/180))*transformation;break; // basis1 * sinē(basis2) case 9:transformation=basis1*(transformation=cos(basis2*pi/180))*transformation;break; // basis1 * cosē(basis2) case 10:transformation=basis1*(transformation=tan(basis2*pi/180))*transformation;break; // basis1 * tanē(basis2) default:ALERT(at_debug,"Invalid transformation\n");break; } Vector vecOutput = g_vecZero; // This is 'mister empty vector' to make sure that whatever targets this only inherits the desired axis. switch(pev->impulse) { // impulse: choose output axis case 0:vecOutput = Vector(transformation, 0, 0);break; case 1:vecOutput = Vector(0, transformation, 0);break; case 2:vecOutput = Vector(0, 0, transformation);break; default:{ALERT(at_debug,"Invalid output axis\n");break;} } if(pev->spawnflags & SF_ANGLETRANS_DEBUG) ALERT(at_debug,"Input-1 = %f, Input-2 = %f, Transformation = %f, Result = %f %f %f\n", basis1,basis2,transformation,vecOutput.x,vecOutput.y,vecOutput.z); // OK - our work here is done. Now spit it out (makevectors vecoutput??)!! UTIL_MakeVectors( vecOutput ); return (gpGlobals->v_forward); // MJB There are two problems with this entity, which is why its commented out: // Problem 1) Whenever it is used, all world surfaces are duplicated and the whole (duplicated) map's corner is positioned where you put the entity(s) // Problem 2) When targeting this with a motion_manager, the 'roll' value appears to be completely ignored - no idea if the problem lies in the motion_manager or in here. }*/ //======================================================= LINK_ENTITY_TO_CLASS(calc_subvelocity, CCalcSubVelocity); Vector CCalcSubVelocity::CalcVelocity( CBaseEntity *pLocus ) { pLocus = UTIL_FindEntityByTargetname( NULL, STRING(pev->netname), pLocus ); Vector vecAngles; Vector vecJunk; switch (pev->impulse) { case 1: //angles return ConvertAngles( pLocus, pLocus->pev->angles ); case 2: //v_angle return ConvertAngles( pLocus, pLocus->pev->v_angle ); case 5: // this could cause problems. // is there a good way to check whether it's really a CBaseAnimating? ((CBaseAnimating*)pLocus)->GetAttachment( 0, vecJunk, vecAngles ); return ConvertAngles( pLocus, vecAngles ); case 6: ((CBaseAnimating*)pLocus)->GetAttachment( 1, vecJunk, vecAngles ); return ConvertAngles( pLocus, vecAngles ); case 7: ((CBaseAnimating*)pLocus)->GetAttachment( 2, vecJunk, vecAngles ); return ConvertAngles( pLocus, vecAngles ); case 8: ((CBaseAnimating*)pLocus)->GetAttachment( 3, vecJunk, vecAngles ); return ConvertAngles( pLocus, vecAngles ); default: return Convert(pLocus, pLocus->pev->velocity); } } Vector CCalcSubVelocity::Convert(CBaseEntity *pLocus, const Vector &vecDir) { float fRatio = CalcLocus_Ratio(pLocus, STRING(pev->noise)); Vector vecOffset = CalcLocus_Velocity(this, pLocus, STRING(pev->message)); Vector vecResult = vecOffset; if (pev->spawnflags & SF_CALCVELOCITY_NORMALIZE) vecResult += (vecDir.Normalize()*fRatio); else vecResult += (vecDir*fRatio); if (pev->spawnflags & SF_CALCVELOCITY_SWAPZ) vecResult.z = -vecResult.z; // ALERT(at_console, "calc_subvel returns (%f %f %f) = (%f %f %f) + ((%f %f %f) * %f)\n", vecResult.x, vecResult.y, vecResult.z, vecOffset.x, vecOffset.y, vecOffset.z, vecDir.x, vecDir.y, vecDir.z, fRatio); return vecResult; } Vector CCalcSubVelocity::ConvertAngles(CBaseEntity *pLocus, const Vector &vecAngles) { // UTIL_MakeVectors(vecAngles); don't you *** touch any globals! Vector fw; ANGLE_VECTORS(vecAngles, fw, NULL, NULL); return Convert(pLocus, fw); } //======================================================= LINK_ENTITY_TO_CLASS(calc_velocity_path, CCalcVelocityPath); Vector CCalcVelocityPath::CalcVelocity( CBaseEntity *pLocus ) { Vector vecStart = CalcLocus_Position( this, pLocus, STRING(pev->target) ); // ALERT(at_console, "vecStart %f %f %f\n", vecStart.x, vecStart.y, vecStart.z); Vector vecOffs; float fFactor = CalcLocus_Ratio( pLocus, STRING(pev->noise) ); switch ((int)pev->armorvalue) { case 0: vecOffs = CalcLocus_Position(this, pLocus, STRING(pev->netname)) - vecStart; break; case 1: vecOffs = CalcLocus_Velocity(this, pLocus, STRING(pev->netname)); break; } // ALERT(at_console, "vecOffs %f %f %f\n", vecOffs.x, vecOffs.y, vecOffs.z); if (pev->health) { float len = vecOffs.Length(); switch ((int)pev->health) { case 1: vecOffs = vecOffs/len; break; case 2: vecOffs = vecOffs/(len*len); break; case 3: vecOffs = vecOffs/(len*len*len); break; case 4: vecOffs = vecOffs*len; break; } } vecOffs = vecOffs * fFactor; if (pev->frags) { TraceResult tr; IGNORE_GLASS iIgnoreGlass = ignore_glass; IGNORE_MONSTERS iIgnoreMonsters = ignore_monsters; switch ((int)pev->frags) { case 2: iIgnoreGlass = dont_ignore_glass; break; case 4: iIgnoreGlass = dont_ignore_glass; // fall through, use both flags case 3: iIgnoreMonsters = dont_ignore_monsters; break; } UTIL_TraceLine(vecStart, vecStart+vecOffs, iIgnoreMonsters, iIgnoreGlass, NULL, &tr); vecOffs = tr.vecEndPos - vecStart; } // ALERT(at_console, "path: %f %f %f\n", vecOffs.x, vecOffs.y, vecOffs.z); return vecOffs; } //======================================================= LINK_ENTITY_TO_CLASS(calc_velocity_polar, CCalcVelocityPolar); Vector CCalcVelocityPolar::CalcVelocity( CBaseEntity *pLocus ) { Vector vecBasis = CalcLocus_Velocity( this, pLocus, STRING(pev->netname) ); Vector vecAngles = UTIL_VecToAngles( vecBasis ) + pev->angles; Vector vecOffset = CalcLocus_Velocity( this, pLocus, STRING(pev->message) ); float fFactor = CalcLocus_Ratio( pLocus, STRING(pev->noise) ); if (!(pev->spawnflags & SF_CALCVELOCITY_NORMALIZE)) fFactor = fFactor * vecBasis.Length(); /*float tempswap; // MJB I've tried adding this code so I can swap the vector components, // but for some reason it just isn't working. I have no idea why. // Perhaps YOU know why and could fix it? // ~X~ Because this whole code is crap from the beginning. I won't bother. if(pev->spawnflags & SF_CALCVELOCITY_SWAPXY) { // MJB axis swapping - X and Y tempswap = vecAngles.y; vecAngles.y = vecAngles.x; vecAngles.x = tempswap; if(pev->spawnflags & SF_CALCVELOCITY_DEBUGSWAP) ALERT(at_debug,"Swapping Pitch = %f, Yaw = %f, Temporary = %f\n", vecAngles.x,vecAngles.y,tempswap); } if(pev->spawnflags & SF_CALCVELOCITY_SWAPYZ) { // MJB axis swapping - Y and Z tempswap = vecAngles.z; vecAngles.z = vecAngles.y; vecAngles.y = tempswap; if(pev->spawnflags & SF_CALCVELOCITY_DEBUGSWAP) ALERT(at_debug,"Swapping Yaw = %f, Roll = %f, Temporary = %f\n", vecAngles.y,vecAngles.z,tempswap); } if(pev->spawnflags & SF_CALCVELOCITY_SWAPXZ) { // MJB axis swapping - X and Z tempswap = vecAngles.z; vecAngles.z = vecAngles.x; vecAngles.x = tempswap; if(pev->spawnflags & SF_CALCVELOCITY_DEBUGSWAP) ALERT(at_debug,"Swapping Pitch = %f, Roll = %f, Temporary = %f\n", vecAngles.x,vecAngles.z,tempswap); } // MJB I've tried adding this code so I can swap the vector components, // but for some reason it just isn't working. I have no idea why. // Perhaps YOU know why and could fix it? */ // UTIL_MakeVectors( vecAngles ); I hate you Vector fw; ANGLE_VECTORS(vecAngles, fw, NULL, NULL); /* MJB - a vain attempt at debugging the nonbehaving code. if(pev->spawnflags & SF_CALCVELOCITY_SWAPXY) // MJB axis swapping - X and Y ALERT(at_debug,"** Swapping Pitch = %f, Yaw = %f, Temporary = %f\n", vecAngles.x,vecAngles.y,tempswap); if(pev->spawnflags & SF_CALCVELOCITY_SWAPYZ) // MJB axis swapping - Y and Z ALERT(at_debug,"** Swapping Yaw = %f, Roll = %f, Temporary = %f\n", vecAngles.y,vecAngles.z,tempswap); if(pev->spawnflags & SF_CALCVELOCITY_SWAPXZ) // MJB axis swapping - X and Z ALERT(at_debug,"** Swapping Pitch = %f, Roll = %f, Temporary = %f\n", vecAngles.x,vecAngles.z,tempswap); */ return (fw * fFactor) + vecOffset; } //======================================================= LINK_ENTITY_TO_CLASS( locus_variable, CLocusVariable ); TYPEDESCRIPTION CLocusVariable::m_SaveData[] = { DEFINE_FIELD( CLocusVariable, m_iszPosition, FIELD_STRING), DEFINE_FIELD( CLocusVariable, m_iszVelocity, FIELD_STRING), DEFINE_FIELD( CLocusVariable, m_iszRatio, FIELD_STRING), DEFINE_FIELD( CLocusVariable, m_iszTargetName, FIELD_STRING), DEFINE_FIELD( CLocusVariable, m_iszFireOnSpawn, FIELD_STRING), DEFINE_FIELD( CLocusVariable, m_fDuration, FIELD_FLOAT), }; IMPLEMENT_SAVERESTORE( CLocusVariable, CPointEntity ); void CLocusVariable::KeyValue(KeyValueData *pkvd) { if (FStrEq(pkvd->szKeyName, "m_iszPosition")) { m_iszPosition = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszVelocity")) { m_iszVelocity = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszRatio")) { m_iszRatio = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszTargetName")) { m_iszTargetName = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszFireOnSpawn")) { m_iszFireOnSpawn = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_fDuration")) { m_fDuration = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CPointEntity::KeyValue(pkvd); } void CLocusVariable::Spawn(void) { SetMovedir(pev); } void CLocusVariable::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { Vector vecPos = g_vecZero; Vector vecDir = g_vecZero; float fRatio = 0; if (m_iszPosition) vecPos = CalcLocus_Position(this, pActivator, STRING(m_iszPosition)); if (m_iszVelocity) vecDir = CalcLocus_Velocity(this, pActivator, STRING(m_iszVelocity)); if (m_iszRatio) fRatio = CalcLocus_Ratio(pActivator, STRING(m_iszRatio)); if (m_iszTargetName) { CMark *pMark = GetClassPtr((CMark *)NULL); pMark->pev->classname = MAKE_STRING("mark"); pMark->pev->origin = vecPos; pMark->pev->movedir = vecDir; pMark->pev->frags = fRatio; pMark->pev->targetname = m_iszTargetName; pMark->SetNextThink(m_fDuration); FireTargets(STRING(m_iszFireOnSpawn), pMark, this, USE_TOGGLE, 0); } else { pev->origin = vecPos; pev->movedir = vecDir; pev->frags = fRatio; FireTargets(STRING(m_iszFireOnSpawn), this, this, USE_TOGGLE, 0); } } LINK_ENTITY_TO_CLASS(locus_beam, CLocusBeam); TYPEDESCRIPTION CLocusBeam::m_SaveData[] = { DEFINE_FIELD( CLocusBeam, m_iszSprite, FIELD_STRING), DEFINE_FIELD( CLocusBeam, m_iszTargetName, FIELD_STRING), DEFINE_FIELD( CLocusBeam, m_iszStart, FIELD_STRING), DEFINE_FIELD( CLocusBeam, m_iszEnd, FIELD_STRING), DEFINE_FIELD( CLocusBeam, m_iWidth, FIELD_INTEGER), DEFINE_FIELD( CLocusBeam, m_iDistortion, FIELD_INTEGER), DEFINE_FIELD( CLocusBeam, m_fFrame, FIELD_FLOAT), DEFINE_FIELD( CLocusBeam, m_iScrollRate, FIELD_INTEGER), DEFINE_FIELD( CLocusBeam, m_fDuration, FIELD_FLOAT), DEFINE_FIELD( CLocusBeam, m_fDamage, FIELD_FLOAT), DEFINE_FIELD( CLocusBeam, m_iDamageType, FIELD_INTEGER), DEFINE_FIELD( CLocusBeam, m_iFlags, FIELD_INTEGER), }; IMPLEMENT_SAVERESTORE(CLocusBeam,CPointEntity); void CLocusBeam :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "m_iszSprite")) { m_iszSprite = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszTargetName")) { m_iszTargetName = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszStart")) { m_iszStart = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszEnd")) { m_iszEnd = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iWidth")) { m_iWidth = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iDistortion")) { m_iDistortion = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_fFrame")) { m_fFrame = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iScrollRate")) { m_iScrollRate = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_fDuration")) { m_fDuration = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_fDamage")) { m_fDamage = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iDamageType")) { m_iDamageType = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CLocusBeam::Precache(void) { PRECACHE_MODEL(STRINGV(m_iszSprite)); } void CLocusBeam::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { CBaseEntity *pStartEnt; CBaseEntity *pEndEnt; Vector vecStartPos; Vector vecEndPos; CBeam *pBeam; switch(pev->impulse) { case 0: // ents pStartEnt = UTIL_FindEntityByTargetname(NULL, STRING(m_iszStart), pActivator); pEndEnt = UTIL_FindEntityByTargetname(NULL, STRING(m_iszEnd), pActivator); if (pStartEnt == NULL || pEndEnt == NULL) return; pBeam = CBeam::BeamCreate( STRING(m_iszSprite), m_iWidth ); pBeam->EntsInit( pStartEnt->entindex(), pEndEnt->entindex() ); break; case 1: // pointent vecStartPos = CalcLocus_Position( this, pActivator, STRING(m_iszStart) ); pEndEnt = UTIL_FindEntityByTargetname(NULL, STRING(m_iszEnd), pActivator); if (pEndEnt == NULL) return; pBeam = CBeam::BeamCreate( STRING(m_iszSprite), m_iWidth ); pBeam->PointEntInit( vecStartPos, pEndEnt->entindex() ); break; case 2: // points vecStartPos = CalcLocus_Position( this, pActivator, STRING(m_iszStart) ); vecEndPos = CalcLocus_Position( this, pActivator, STRING(m_iszEnd) ); pBeam = CBeam::BeamCreate( STRING(m_iszSprite), m_iWidth ); pBeam->PointsInit( vecStartPos, vecEndPos ); break; case 3: // point & offset vecStartPos = CalcLocus_Position( this, pActivator, STRING(m_iszStart) ); vecEndPos = CalcLocus_Velocity( this, pActivator, STRING(m_iszEnd) ); pBeam = CBeam::BeamCreate( STRING(m_iszSprite), m_iWidth ); pBeam->PointsInit( vecStartPos, vecStartPos + vecEndPos ); break; default: ALERT(at_console, "%s %s bad type %d!\n", STRING(pev->classname), STRING(pev->targetname), pev->impulse); pBeam = NULL; break; } if (pBeam) { pBeam->SetColor( pev->rendercolor.x, pev->rendercolor.y, pev->rendercolor.z ); pBeam->SetBrightness( pev->renderamt ); pBeam->SetNoise( m_iDistortion ); pBeam->SetFrame( m_fFrame ); pBeam->SetScrollRate( m_iScrollRate ); pBeam->SetFlags( m_iFlags ); pBeam->pev->dmg = m_fDamage; pBeam->pev->frags = m_iDamageType; pBeam->pev->spawnflags |= pev->spawnflags & (SF_BEAM_RING | SF_BEAM_SPARKSTART | SF_BEAM_SPARKEND | SF_BEAM_DECALS); if (m_fDuration) { pBeam->SetThink(&CBeam::SUB_Remove); pBeam->SetNextThink(m_fDuration); } pBeam->pev->targetname = m_iszTargetName; } if (!FStringNull(pev->target)) FireTargets(STRING(pev->target), pBeam, this, USE_TOGGLE, 0); } void CLocusBeam::Spawn(void) { Precache(); m_iFlags = 0; if (pev->spawnflags & SF_LBEAM_SHADEIN) m_iFlags |= BEAM_FSHADEIN; if (pev->spawnflags & SF_LBEAM_SHADEOUT) m_iFlags |= BEAM_FSHADEOUT; if (pev->spawnflags & SF_LBEAM_SINE) m_iFlags |= BEAM_FSINE; if (pev->spawnflags & SF_LBEAM_SOLID) m_iFlags |= BEAM_FSOLID; }
[ "30539708+Maxxiii@users.noreply.github.com" ]
30539708+Maxxiii@users.noreply.github.com
7dfd546a341ff0eb4d1261526d934f3cc176b0c5
50f2a23b6164e4161d06547d897b979608f9b6d1
/SDK/FG_BP_StarfishSingle_01_functions.cpp
effd27096ba16dcec8efdfbe74a4e9d5831c2b27
[]
no_license
satisfactorymodding/SatisfactorySDK
35433a3bd19f34c7dfd0a4cf141a310be4b9d382
e9a2332e0f76b92c99d4072638c1560b8137e821
refs/heads/master
2020-05-24T11:21:41.715919
2019-10-10T07:48:30
2019-10-10T07:48:30
187,234,176
8
3
null
null
null
null
UTF-8
C++
false
false
11,397
cpp
// Satisfactory SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "FG_BP_StarfishSingle_01_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.IsTooClose // () // Parameters: // bool IsTooClose (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::IsTooClose(bool* IsTooClose) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.IsTooClose"); ABP_StarfishSingle_01_C_IsTooClose_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (IsTooClose != nullptr) *IsTooClose = params.IsTooClose; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.Burrow // () void ABP_StarfishSingle_01_C::Burrow() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.Burrow"); ABP_StarfishSingle_01_C_Burrow_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.canMove // () // Parameters: // bool canMove (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::canMove(bool* canMove) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.canMove"); ABP_StarfishSingle_01_C_canMove_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (canMove != nullptr) *canMove = params.canMove; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.MoveStarFish // () void ABP_StarfishSingle_01_C::MoveStarFish() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.MoveStarFish"); ABP_StarfishSingle_01_C_MoveStarFish_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.UpdateMesh // () // Parameters: // float Position (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // class UStaticMeshComponent* Mesh (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void ABP_StarfishSingle_01_C::UpdateMesh(float Position, class UStaticMeshComponent* Mesh) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.UpdateMesh"); ABP_StarfishSingle_01_C_UpdateMesh_Params params; params.Position = Position; params.Mesh = Mesh; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.UserConstructionScript // () void ABP_StarfishSingle_01_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.UserConstructionScript"); ABP_StarfishSingle_01_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ReceiveBeginPlay // () void ABP_StarfishSingle_01_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ReceiveBeginPlay"); ABP_StarfishSingle_01_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature // () // Parameters: // class UPrimitiveComponent* OverlappedComponent (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // int OtherBodyIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // bool bFromSweep (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // struct FHitResult SweepResult (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData) void ABP_StarfishSingle_01_C::BndEvt__Sphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex, bool bFromSweep, const struct FHitResult& SweepResult) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature"); ABP_StarfishSingle_01_C_BndEvt__Sphere_K2Node_ComponentBoundEvent_0_ComponentBeginOverlapSignature__DelegateSignature_Params params; params.OverlappedComponent = OverlappedComponent; params.OtherActor = OtherActor; params.OtherComp = OtherComp; params.OtherBodyIndex = OtherBodyIndex; params.bFromSweep = bFromSweep; params.SweepResult = SweepResult; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature // () // Parameters: // class UPrimitiveComponent* OverlappedComponent (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // int OtherBodyIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::BndEvt__Sphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature"); ABP_StarfishSingle_01_C_BndEvt__Sphere_K2Node_ComponentBoundEvent_1_ComponentEndOverlapSignature__DelegateSignature_Params params; params.OverlappedComponent = OverlappedComponent; params.OtherActor = OtherActor; params.OtherComp = OtherComp; params.OtherBodyIndex = OtherBodyIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.StartBurrow // () void ABP_StarfishSingle_01_C::StartBurrow() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.StartBurrow"); ABP_StarfishSingle_01_C_StartBurrow_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ReceiveTick // () // Parameters: // float* DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::ReceiveTick(float* DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ReceiveTick"); ABP_StarfishSingle_01_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.StopBurrow // () void ABP_StarfishSingle_01_C::StopBurrow() { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.StopBurrow"); ABP_StarfishSingle_01_C_StopBurrow_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere2_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature // () // Parameters: // class UPrimitiveComponent* OverlappedComponent (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) // int OtherBodyIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::BndEvt__Sphere2_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.BndEvt__Sphere2_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature"); ABP_StarfishSingle_01_C_BndEvt__Sphere2_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature_Params params; params.OverlappedComponent = OverlappedComponent; params.OtherActor = OtherActor; params.OtherComp = OtherComp; params.OtherBodyIndex = OtherBodyIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ExecuteUbergraph_BP_StarfishSingle_01 // () // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void ABP_StarfishSingle_01_C::ExecuteUbergraph_BP_StarfishSingle_01(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_StarfishSingle_01.BP_StarfishSingle_01_C.ExecuteUbergraph_BP_StarfishSingle_01"); ABP_StarfishSingle_01_C_ExecuteUbergraph_BP_StarfishSingle_01_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kronosdev45@gmail.com" ]
kronosdev45@gmail.com
d7885883846d8a44a9aa76139fd4f02d5a319023
afab7b8f4ee33d3ca12a55554d35bfa44f0cf81f
/Scara Final/ScaraArduinoCode/ScaraArduinoCode.ino
ee61bd245a06bb2b7088b3fe2313f918b9f092e4
[]
no_license
modyvj/SeniorDesign
f7466034b86e15ed2b0864b58e04b5cb3f215e88
4ca251f0ad64485e5873a3315eefed8bf67daad6
refs/heads/master
2020-03-07T12:14:16.348712
2018-04-03T19:06:46
2018-04-03T19:06:46
127,473,576
0
0
null
null
null
null
UTF-8
C++
false
false
2,457
ino
// Serial test script #include <Servo.h> #define EAA 1 #define EAB 2 int cntEA = 0; bool curEA = LOW; bool lasEA = LOW; Servo myservoj1; // create servo object to control a servo Servo myservoj2; // create servo object to control a servo int pos = 90; // variable to store the servo position int setPoint = 55; String readString=""; int x =5 ; void setup() { pinMode (EAA, INPUT); pinMode (EAB, INPUT); Serial.begin(9600); // initialize serial communications at 9600 bps myservoj1.attach(9); //Servo connected to D9 myservoj2.attach(10); //Servo connected to D10 } void loop() { // while (Serial.available() > 0) { // // read the incoming byte: // int c = Serial.read(); // Serial.println(c); // char x = Serial.read(); // Serial.println(x); // delay(2); // // say what you got: // //Serial.print("C is "); // Serial.println(c, DEC); // myservoj1.write(c); /////////////////////////////////////////////////// // serial read section lasEA = curEA; while (Serial.available()) // this will be skipped if no data present, leading to // the code sitting in the delay function below { delay(30); //delay to allow buffer to fill if (Serial.available() >0) { char c = Serial.read(); //gets one byte from serial buffer readString += c; //makes the string readString Serial.println(readString); //##### see what my input is } } if (readString.length() ==4) { if (readString ="K000") { // break Serial.print("Killing Code"); } String ard_sends = "a666"; //Serial.print("Arduino sends: "); Serial.println(ard_sends); delayMicroseconds(500); // Serial.print("\n"); ard_sends = "b999"; //Serial.print("Arduino sends: "); Serial.println(ard_sends); // Serial.print("\n"); readString=""; //Serial.print("\n"); Serial.flush(); } //delay(500); // serial write section //read   // Serial.write("A444")  //String ard_sends = "C100"; // Serial.println(ard_sends); // // ard_sends = "D201"; // // Serial.println(ard_sends); // // // ard_sends = "E302"; // // Serial.println(ard_sends); // // delay(500); // //Serial.flush(); //x=x+1; //if (x>9 ) //{ //for (;;); //} }
[ "vishalmody12@gmail.com" ]
vishalmody12@gmail.com
8bd8a885ea950cea350a18f21bee18fa89b91e15
517391f634571536f689cf9402888a9743653b67
/parser.cpp
093f2fdaf66d91d8ca1ffceb98d9a9581e650510
[]
no_license
luk0104/jovita
becdb8f302eb68cd0a81adc4bd6dbe9b3cbb8152
ec21d9d914870e4e980178f293bda3db682ef485
refs/heads/master
2021-01-25T05:16:36.977764
2011-10-11T21:36:11
2011-10-11T21:36:11
2,557,129
1
0
null
null
null
null
UTF-8
C++
false
false
2,576
cpp
#include <cctype> #include <cstring> #include "parser.h" namespace Parser { Parser::Parser (std::string str) { this->str = str; itr = this->str.begin (); } Machine::OPCode * Parser::nextOPCode (void) { char ch; std::cout << "OPCode: " << str << std::endl; while (isData ()) { switch (nextToken ()) { case Parser::WORD: std::cout << "[" << word << "]" << std::endl; OPS_PARSER() break; case Parser::SEMICOLON: while (isData () && nextToken () != Parser::_NEWLINE) ; } } return NULL; } Machine::OPCode * Parser::parse_opcode (Machine::OPCode op, int params) { Machine::Parameter *p[params]; if (parseParameters (params, p) != params) throw new Error::Parser::SyntaxError (); std::cout << "New [?] OPcode" << std::endl; Machine::OPCode * ret = new Machine::OPCode (op); for (int i = 0; i < params; ++i) ret->addParameter (p[i]); return ret; } int Parser::parseParameters (int num, Machine::Parameter* p[]) { int i; for (i = 0; i < num; ++i) { if (nextToken () != Parser::WORD) { std::cout << "Expected word" << std::endl; throw new Error::Parser::SyntaxError (); } p[i] = nextParameter (); if (i < num - 1 && nextToken () != Parser::COMMA) { std::cout << "Expected comma" << std::endl; throw new Error::Parser::SyntaxError (); } } return i; } Machine::Parameter * Parser::nextParameter (void) { bool reg = false; char ch; unsigned long int val = 0; std::string::iterator i = word.begin (); if (*i == 'r' || *i == 'R') { reg = true; ++i; } if (!isdigit (*i)) { std::cout << "Expected digit" << std::endl; throw new Error::Parser::SyntaxError (); } while (i < word.end () && isdigit (*i)) { val = val * 10 + *i - '0'; ++i; } std::cout << "New parameter: 0x" << std::hex << val << ", " << reg << std::endl; return new Machine::Parameter (val, reg); } bool Parser::isData (void) { return (itr < str.end ()); } void Parser::skipWs (void) { while (isspace (*itr) && isData ()) ++itr; } char Parser::nextToken (void) { char ch; std::string ret; skipWs (); switch (*itr) { case ';': ++itr; return Parser::SEMICOLON; case '\n': ++itr; return Parser::_NEWLINE; case ',': ++itr; return Parser::COMMA; } if (!isalnum (*itr)) throw new Error::Parser::SyntaxError (); word.clear (); while (isalnum (*itr) && isData ()) { word.push_back (*itr); ++itr; } return Parser::WORD; } }
[ "luk0104@gmail.com" ]
luk0104@gmail.com
0ddc3fede78ea2f52a66e266522febeb059fef96
f6cb1b34668f4e864836c595efce40083baa8f91
/common/recipes-core/log-util-v2/files/tests/test_selstream.cpp
3778bf77f10d92298dc521fa2363ad2d90bb419b
[]
no_license
isabella232/openbmc
d419d61092f457d2c25a057831fc8d56cd482e8a
7a0ece893ac2d985af85701d8a003fa62a34cae0
refs/heads/helium
2023-04-06T06:29:29.854842
2021-04-16T01:04:35
2021-04-16T01:54:48
358,585,013
0
0
null
2021-04-16T12:02:45
2021-04-16T12:01:40
null
UTF-8
C++
false
false
8,857
cpp
#include <gmock/gmock.h> #include <gtest/gtest.h> #include <sstream> #include "selstream.hpp" using namespace std; using namespace testing; class MockSELFormat : public SELFormat { public: MockSELFormat(uint8_t fru_id) : SELFormat(fru_id) {} MOCK_METHOD1(get_fru_name, string(uint8_t)); MOCK_METHOD0(get_current_time, string()); }; class MockSELStream : public SELStream { public: MockSELStream(OutputFormat fmt) : SELStream(fmt) {} MOCK_METHOD1(make_sel, std::unique_ptr<SELFormat>(uint8_t)); }; TEST(SELStream, BasicReadWrite) { stringstream inp; inp << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; inp << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; inp << " 2020 May 18 10:18:38 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: ncsid: FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; inp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; stringstream exp; exp << "0 all 2020-05-18 10:18:40 healthd BMC Reboot detected - caused by reboot command\n"; exp << "1 mb 2020-04-06 15:00:40 sensord ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; exp << "2 nic 2020-05-18 10:18:38 ncsid FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; exp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; MockSELStream stream(FORMAT_PRINT); auto sel = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel, get_fru_name(AnyOf(1, 2))) .Times(3) .WillOnce(Return(string("mb"))) .WillOnce(Return(string("nic"))) .WillOnce(Return(string("nic"))); EXPECT_CALL(stream, make_sel(SELFormat::FRU_ALL)) .Times(1) .WillOnce(Return(ByMove(std::move(sel)))); stringstream outp; stream.start(inp, outp, {SELFormat::FRU_ALL}); stream.flush(outp); EXPECT_EQ(outp.str(), exp.str()); } TEST(SELStream, BasicFilter) { stringstream inp1, inp2; inp1 << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; inp1 << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; inp2 << " 2020 May 18 10:18:38 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: ncsid: FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; inp2 << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; stringstream exp; exp << "2 nic 2020-05-18 10:18:38 ncsid FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; exp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; MockSELStream stream(FORMAT_PRINT); auto sel1 = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); auto sel2 = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel1, get_fru_name(1)).Times(1).WillOnce(Return(string("mb"))); EXPECT_CALL(*sel2, get_fru_name(2)).WillRepeatedly(Return(string("nic"))); EXPECT_CALL(stream, make_sel(SELFormat::FRU_ALL)) .Times(2) .WillOnce(Return(ByMove(std::move(sel1)))) .WillOnce(Return(ByMove(std::move(sel2)))); stringstream outp; stream.start(inp1, outp, {2}); stream.start(inp2, outp, {2}); stream.flush(outp); EXPECT_EQ(outp.str(), exp.str()); } TEST(SELStream, BasicJSON) { stringstream inp; inp << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; inp << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; inp << " 2020 May 18 10:18:38 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: ncsid: FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; inp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; MockSELStream stream(FORMAT_JSON); auto sel = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel, get_fru_name(AnyOf(1, 2))) .Times(3) .WillOnce(Return(string("mb"))) .WillOnce(Return(string("nic"))) .WillOnce(Return(string("nic"))); EXPECT_CALL(stream, make_sel(SELFormat::FRU_ALL)) .Times(1) .WillOnce(Return(ByMove(std::move(sel)))); stringstream outp; stream.start(inp, outp, {SELFormat::FRU_ALL}); stream.flush(outp); nlohmann::json got = nlohmann::json::parse(outp.str()); EXPECT_NE(got.find("Logs"), got.end()); EXPECT_EQ(got["Logs"].size(), 3); EXPECT_EQ( got["Logs"][0]["MESSAGE"], "BMC Reboot detected - caused by reboot command"); EXPECT_EQ(got["Logs"][1]["APP_NAME"], "sensord"); EXPECT_EQ( string(got["Logs"][2]["MESSAGE"]), "FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7"); EXPECT_EQ(got["Logs"][0]["FRU#"], "0"); EXPECT_EQ(got["Logs"][1]["FRU_NAME"], "mb"); EXPECT_EQ( got["Logs"][1]["MESSAGE"], "ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH"); } TEST(SELStream, ClearAll) { MockSELStream stream(FORMAT_RAW); auto sel = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel, get_fru_name(AnyOf(1, 2))) .Times(3) .WillOnce(Return(string("mb"))) .WillOnce(Return(string("nic"))) .WillOnce(Return(string("nic"))); auto sel2 = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel2, get_current_time()) .Times(1) .WillOnce(Return(string("2020 Jun 21 17:29:55"))); EXPECT_CALL(stream, make_sel(SELFormat::FRU_ALL)) .Times(2) .WillOnce(Return(ByMove(std::move(sel)))) .WillOnce(Return(ByMove(std::move(sel2)))); stringstream inp; inp << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; inp << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; inp << " 2020 May 18 10:18:38 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: ncsid: FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; inp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; stringstream outp; stream.start(inp, outp, {SELFormat::FRU_ALL}); stream.log_cleared(outp, {SELFormat::FRU_ALL}); stream.flush(outp); stringstream exp; exp << "2020 Jun 21 17:29:55 log-util: User cleared all logs\n"; ASSERT_EQ(outp.str(), exp.str()); } TEST(SELStream, ClearFru) { auto sel = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel, get_fru_name(AnyOf(1, 2))) .Times(3) .WillOnce(Return(string("mb"))) .WillOnce(Return(string("nic"))) .WillOnce(Return(string("nic"))); auto sel2 = std::make_unique<MockSELFormat>(SELFormat::FRU_ALL); EXPECT_CALL(*sel2, get_fru_name(2)).Times(1).WillOnce(Return(string("nic"))); EXPECT_CALL(*sel2, get_current_time()) .Times(1) .WillOnce(Return(string("2020 Jun 21 17:29:55"))); MockSELStream stream(FORMAT_RAW); EXPECT_CALL(stream, make_sel(AnyOf(SELFormat::FRU_ALL, 2))) .Times(2) .WillOnce(Return(ByMove(std::move(sel)))) .WillOnce(Return(ByMove(std::move(sel2)))); stringstream inp; inp << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; inp << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; inp << " 2020 May 18 10:18:38 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: ncsid: FRU: 2 NIC AEN Supported: 0x7, AEN Enable Mask=0x7\n"; inp << "2020 May 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; stringstream outp; stream.start(inp, outp, {2}); stream.log_cleared(outp, {2}); stream.flush(outp); stringstream exp; exp << " 2020 May 18 10:18:40 bmc-oob. user.crit fbtp-9b6bf3961d-dirty: healthd: BMC Reboot detected - caused by reboot command\n"; exp << " 2020 Apr 6 15:00:40 bmc-oob. user.crit fbtp-v2020.09.1: sensord: ASSERT: Upper Non Critical threshold - raised - FRU: 1, num: 0xC0 curr_val: 8988.00 RPM, thresh_val: 8500.00 RPM, snr: MB_FAN0_TACH\n"; exp << "2020 Jun 21 17:29:55 log-util: User cleared FRU: 2 logs\n"; ASSERT_EQ(outp.str(), exp.str()); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
0b761d4a555d8774001003fd2f5251c84e504f95
5f94bc08a480660a860c6437614332f702b18dda
/BitMatrix.h
094435fb6e014407c26a55ab809652e654873db1
[]
no_license
matvore/andradion-2
8c566ee1d1b9a2f84aa4a9ec2a958cb6f10a8808
4b14c75a25173f0b08cdea8212bcb32742cea52c
refs/heads/master
2021-01-22T09:27:54.116641
2011-10-10T07:57:33
2011-10-10T07:57:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
886
h
/* Copyright 2011 Matt DeVore Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ class CBitMatrix { public: static std::auto_ptr<CBitMatrix> forDimensions(int width, int height); ~CBitMatrix(); void set(int x, int y); bool get(int x, int y) const; private: CBitMatrix(int width, char *data) : width(width), data(data) {} CBitMatrix& operator=(const CBitMatrix&); int width; char *data; };
[ "matvore@gmail.com" ]
matvore@gmail.com
76f9eb4afee988d524299a15c21336e383974316
fead4a1cec5bbf6d7503ba6c59cb137ee59d57ad
/kld_loss_layer.cpp
81cbe75fc73365c4337acc624b1169fff14a4834
[]
no_license
TianzhongSong/caffe_kld_loss
dd00bfad3e9aafed5c94bfea6eaa12a35dd24510
50a360cfcc6b4c97e9a383c428a96447012f37d3
refs/heads/master
2020-06-19T16:22:04.792360
2019-07-14T01:36:55
2019-07-14T01:36:55
196,781,701
4
1
null
null
null
null
UTF-8
C++
false
false
3,587
cpp
#include <algorithm> #include <cfloat> #include <vector> #include "caffe/layers/kld_loss_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void KLDLossLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); if (!this->layer_param_.loss_param().has_normalization() && this->layer_param_.loss_param().has_normalize()) { normalization_ = this->layer_param_.loss_param().normalize() ? LossParameter_NormalizationMode_VALID : LossParameter_NormalizationMode_BATCH_SIZE; } else { normalization_ = this->layer_param_.loss_param().normalization(); } } template <typename Dtype> void KLDLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(), bottom[1]->count()) << "Input bottoms must have the same size."; outer_num_ = bottom[0]->shape(0); inner_num_ = bottom[0]->count(1); } template <typename Dtype> Dtype KLDLossLayer<Dtype>::get_normalizer( LossParameter_NormalizationMode normalization_mode, Dtype valid_count) { Dtype normalizer; switch (normalization_mode) { case LossParameter_NormalizationMode_FULL: normalizer = Dtype(outer_num_ * inner_num_); break; case LossParameter_NormalizationMode_VALID: if (valid_count < 0) { normalizer = Dtype(outer_num_ * inner_num_); } else { normalizer = valid_count; } break; case LossParameter_NormalizationMode_BATCH_SIZE: normalizer = Dtype(outer_num_); break; case LossParameter_NormalizationMode_NONE: normalizer = Dtype(1); break; default: LOG(FATAL) << "Unknown normalization mode: " << LossParameter_NormalizationMode_Name(normalization_mode); } return std::max(Dtype(1.0), normalizer); } template <typename Dtype> void KLDLossLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* prob_data = bottom[0]->cpu_data(); const Dtype* label = bottom[1]->cpu_data(); Dtype * temp = bottom[0]->mutable_cpu_diff(); int N = bottom[0]->count(); Dtype loss = 0; // Prevent underflow in log for(int i = 0; i < N; ++i) temp[i] = std::max(prob_data[i],Dtype(FLT_MIN)); caffe_log(N,temp,temp); // Subtract entropy of target distribution for(int i = 0; i < N; ++i) temp[i] -= log(std::max(label[i],Dtype(FLT_MIN))); loss = caffe_cpu_dot(N,temp,label); top[0]->mutable_cpu_data()[0] = -loss / get_normalizer(normalization_, Dtype(N)); } template <typename Dtype> void KLDLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to target distribution yet."; } if (propagate_down[0]) { Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* prob_data = bottom[0]->cpu_data(); const Dtype* label = bottom[1]->cpu_data(); int N = bottom[0]->count(); caffe_sub(N,prob_data,label,bottom_diff); Dtype loss_weight = top[0]->cpu_diff()[0] / get_normalizer(normalization_, Dtype(N)); caffe_scal(N, loss_weight, bottom_diff); } } #ifdef CPU_ONLY STUB_GPU(KLDLossLayer); #endif INSTANTIATE_CLASS(KLDLossLayer); REGISTER_LAYER_CLASS(KLDLoss); } // namespace caffe
[ "ssstz@outlook.com" ]
ssstz@outlook.com
95377be0fbbf351b9c55ae7f9223233195914088
7ee32ddb0cdfdf1993aa4967e1045790690d7089
/Codeforces/Round238ProblemC.cpp
47b7337b03e0305dc2c136c355ed7f899a2b14bb
[]
no_license
ajimenezh/Programing-Contests
b9b91c31814875fd5544d63d7365b3fc20abd354
ad47d1f38b780de46997f16fbaa3338c9aca0e1a
refs/heads/master
2020-12-24T14:56:14.154367
2017-10-16T21:05:01
2017-10-16T21:05:01
11,746,917
1
2
null
null
null
null
UTF-8
C++
false
false
2,323
cpp
#include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <utility> #include <set> #include <map> #include <deque> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <stdio.h> using namespace std; #define fo(i,n) for(int i=0; i<(int)n; i++) #define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++) #define mp(a,b) make_pair(a,b) #define pb(x) push_back(x) #define pii pair<int,int> int n; int m; set<int> e[100010]; set<pair<int,int> > q; vector<int> x, y, z; int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); cin>>n>>m; for (int i=0; i<m; i++) { int a,b; scanf("%d%d", &a, &b); a--; b--; e[a].insert(b); e[b].insert(a); } for (int i=0; i<n; i++) q.insert(make_pair(e[i].size(), i)); while (!q.empty()) { int p = (*q.begin()).second; q.erase(q.begin()); if (e[p].size()>1) { int k = *e[p].begin(); x.push_back(k); e[p].erase(e[p].begin()); e[k].erase(p); q.erase(make_pair(e[k].size()+1, k)); if (e[k].size()!=0) q.insert(make_pair(e[k].size(), k)); y.push_back(p); k = *e[p].begin(); z.push_back(k); e[p].erase(e[p].begin()); e[k].erase(p); q.erase(make_pair(e[k].size()+1, k)); if (e[k].size()!=0) q.insert(make_pair(e[k].size(), k)); } else { int k = *e[p].begin(); e[k].erase(p); e[p].erase(k); if (e[k].size()==0) { cout<<"No solution"; return 0; } x.push_back(p); y.push_back(k); int k2 = *e[k].begin(); e[k].erase(k2); e[k2].erase(k); z.push_back(k2); q.erase(make_pair(e[k].size()+2, k)); if (e[k].size()!=0) q.insert(make_pair(e[k].size(), k)); q.erase(make_pair(e[k2].size()+1, k2)); if (e[k2].size()!=0) q.insert(make_pair(e[k2].size(), k2)); } } for (int i=0; i<x.size(); i++) { printf("%d %d %d\n", x[i]+1, y[i]+1, z[i]+1); } return 0; }
[ "alejandrojh90@gmail.com" ]
alejandrojh90@gmail.com
a65de41535e7fdfb1d4a8f5e61e142b876cbdaf8
328abdff9a801faf23b46129fcf114b4c378042f
/INO/myprobes.ino
108456d01f3402fafb9de4302c4dcce638b84f34
[]
no_license
SlyWink/MyProbes
cdd10ec1193c26f105482d5b2436ada8e85c073c
cf1ab5d6eb81ee1a1e701e893765b065a4510232
refs/heads/master
2022-12-11T15:11:47.329351
2020-08-29T20:55:41
2020-08-29T20:55:41
289,576,561
0
0
null
null
null
null
UTF-8
C++
false
false
1,729
ino
//#define INIT //#define LINKY //#define GAZPAR #define METEO #define WANTDEBUG #include <EEPROM.h> #include <ArduinoOTA.h> #include <painlessMesh.h> /* const uint32_t CHIP1_ID = 0x00000000 ; const uint32_t CHIP2_ID = 0x00e67e71 ; const uint32_t CHIP3_ID = 0x00000000 ; const uint32_t CHIP4_ID = 0x00e3c664 ; const uint32_t CHIP5_ID = 0x00e5e70d ; const uint32_t CHIP6_ID = 0x00e5e76b ; #define BRIDGE CHIP2_ID #define LINKY CHIP4_ID #define GAZPAR CHIP5_ID #define METEO CHIP6_ID */ const size_t PROBES_COUNT = 4 ; /* const char CHIP2_NAME[] PROGMEM = "BRIDGE" ; const char CHIP4_NAME[] PROGMEM = "LINKY" ; const char CHIP5_NAME[] PROGMEM = "GAZPAR" ; const char CHIP6_NAME[] PROGMEM = "METEO" ; */ const char DISCOVER_REQUEST_STRING[] PROGMEM = "dcr" ; const char DISCOVER_ANSWER_STRING[] PROGMEM = "dca" ; const char DATA_REQUEST_STRING[] PROGMEM = "dtr" ; const char DATA_ANSWER_STRING[] PROGMEM = "dta" ; const char STORE_REQUEST_STRING[] PROGMEM = "str" ; const char OTA_REQUEST_STRING[] PROGMEM = "otr" ; const char TEST_REQUEST_STRING[] PROGMEM="tsr" ; const char MESSAGE_NUMBER_STRING[] PROGMEM = "num" ; const char FROM_NAME_STRING[] PROGMEM = "frm" ; enum class MsgType { DISCOVER_REQUEST, DISCOVER_ANSWER, DATA_REQUEST, DATA_ANSWER, STORE_REQUEST, OTA_REQUEST, TEST_REQUEST } ; struct CONNECTION_T { String netName ; String netPassword ; } ; struct NETWORK_T { CONNECTION_T mesh ; CONNECTION_T wifi ; } ; struct MESSAGE_T { uint32_t chipId ; String message ; } ; struct ITEM_T { uint32_t id ; String name ; uint8_t msgNum ; } ; #ifdef WANTDEBUG #define debug(s) Serial.print(s) #define debugln(s) Serial.println(s) #else #define debug(s) {} #define debugln(s) {} #endif
[ "24624623+SlyWink@users.noreply.github.com" ]
24624623+SlyWink@users.noreply.github.com
f7d79787e47a0ad4b08d7c3b5bf1e63977492510
4abb17761b75ebe4c227d62ac9ec0c8a5894f6e9
/Plugins/NativeCamera/Source/NativeVideo.h
ab8e27ca883771864fac5b273ff00c948ae8b754
[ "LicenseRef-scancode-nvidia-2002", "BSD-3-Clause", "LicenseRef-scancode-openssl", "LicenseRef-scancode-unicode", "NTP", "CC0-1.0", "curl", "Zlib", "NAIST-2003", "LGPL-2.1-or-later", "Artistic-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "ICU", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
BabylonJS/BabylonNative
1aea5e6e2129d5c6e7e22b6c584d6a760d7bfa65
b612a907325979a26467360039e267c03fb63893
refs/heads/master
2023-08-29T07:06:17.620500
2023-08-14T20:34:04
2023-08-14T20:34:04
189,081,889
723
150
MIT
2023-09-13T20:13:24
2019-05-28T18:27:37
C++
UTF-8
C++
false
false
1,853
h
#pragma once #include <napi/napi.h> #include "CameraDevice.h" #include "MediaStream.h" #include <Babylon/JsRuntime.h> #include <Babylon/Graphics/DeviceContext.h> #include <vector> #include <algorithm> #include <unordered_map> namespace Babylon::Plugins { // NativeVideo provides a polyfill for the HTMLVideoElement which is used in conjunction with a MediaStream object to // pull frames out of a camera and render them into the Babylon scene. class NativeVideo : public Napi::ObjectWrap<NativeVideo> { public: static void Initialize(Napi::Env& env); static Napi::Object New(const Napi::CallbackInfo& info); NativeVideo(const Napi::CallbackInfo& info); ~NativeVideo() = default; void UpdateTexture(bgfx::TextureHandle textureHandle); private: void AddEventListener(const Napi::CallbackInfo& info); void RemoveEventListener(const Napi::CallbackInfo& info); void RaiseEvent(const char* eventType); Napi::Value Play(const Napi::CallbackInfo& info); void Pause(const Napi::CallbackInfo& info); Napi::Value GetVideoWidth(const Napi::CallbackInfo& info); Napi::Value GetVideoHeight(const Napi::CallbackInfo& info); void SetAttribute(const Napi::CallbackInfo&); void RemoveAttribute(const Napi::CallbackInfo&); Napi::Value GetReadyState(const Napi::CallbackInfo& info); Napi::Value GetHaveCurrentData(const Napi::CallbackInfo& info); Napi::Value GetSrcObject(const Napi::CallbackInfo& info); void SetSrcObject(const Napi::CallbackInfo& info, const Napi::Value& value); std::unordered_map<std::string, std::vector<Napi::FunctionReference>> m_eventHandlerRefs{}; bool m_isReady{false}; bool m_IsPlaying{}; Napi::ObjectReference m_streamObject{}; }; }
[ "noreply@github.com" ]
BabylonJS.noreply@github.com
67349053bf09778b30aa840db3bbd2888b4195c2
31406f420f019a191a74b9288a6e37dcd89e8e82
/external/llvh/lib/Support/Unix/Path.inc
dd55605226c5052328bfed93c69526db50d0854f
[ "MIT", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
facebook/hermes
b1bf3cb60b5946450c7c9a421ac8dad7a675e0f5
440578b31ecce46fcc5ba2ad745ffd5712d63a35
refs/heads/main
2023-09-06T04:16:02.263184
2023-09-05T20:12:54
2023-09-05T20:12:54
154,201,259
8,449
593
MIT
2023-09-14T21:25:56
2018-10-22T19:13:00
C++
UTF-8
C++
false
false
30,731
inc
//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Unix specific implementation of the Path API. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only generic UNIX code that //=== is guaranteed to work on *all* UNIX variants. //===----------------------------------------------------------------------===// #include "Unix.h" #include <limits.h> #include <stdio.h> #if HAVE_SYS_STAT_H #include <sys/stat.h> #endif #if HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #include <dirent.h> #include <pwd.h> #ifdef __APPLE__ #include <mach-o/dyld.h> #include <sys/attr.h> #endif // Both stdio.h and cstdio are included via different paths and // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros // either. #undef ferror #undef feof // For GNU Hurd #if defined(__GNU__) && !defined(PATH_MAX) # define PATH_MAX 4096 #endif #include <sys/types.h> #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \ !defined(__linux__) #include <sys/statvfs.h> #define STATVFS statvfs #define FSTATVFS fstatvfs #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize #else #if defined(__OpenBSD__) || defined(__FreeBSD__) #include <sys/mount.h> #include <sys/param.h> #elif defined(__linux__) #if defined(HAVE_LINUX_MAGIC_H) #include <linux/magic.h> #else #if defined(HAVE_LINUX_NFS_FS_H) #include <linux/nfs_fs.h> #endif #if defined(HAVE_LINUX_SMB_H) #include <linux/smb.h> #endif #endif #include <sys/vfs.h> #else #include <sys/mount.h> #endif #define STATVFS statfs #define FSTATVFS fstatfs #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize) #endif #if defined(__NetBSD__) || defined(__EMSCRIPTEN__) #define STATVFS_F_FLAG(vfs) (vfs).f_flag #else #define STATVFS_F_FLAG(vfs) (vfs).f_flags #endif using namespace llvh; namespace llvh { namespace sys { namespace fs { const file_t kInvalidFile = -1; #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \ defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) { struct stat sb; char fullpath[PATH_MAX]; snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin); if (!realpath(fullpath, ret)) return 1; if (stat(fullpath, &sb) != 0) return 1; return 0; } static char * getprogpath(char ret[PATH_MAX], const char *bin) { char *pv, *s, *t; /* First approach: absolute path. */ if (bin[0] == '/') { if (test_dir(ret, "/", bin) == 0) return ret; return nullptr; } /* Second approach: relative path. */ if (strchr(bin, '/')) { char cwd[PATH_MAX]; if (!getcwd(cwd, PATH_MAX)) return nullptr; if (test_dir(ret, cwd, bin) == 0) return ret; return nullptr; } /* Third approach: $PATH */ if ((pv = getenv("PATH")) == nullptr) return nullptr; s = pv = strdup(pv); if (!pv) return nullptr; while ((t = strsep(&s, ":")) != nullptr) { if (test_dir(ret, t, bin) == 0) { free(pv); return ret; } } free(pv); return nullptr; } #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__ /// GetMainExecutable - Return the path to the main executable, given the /// value of argv[0] from program startup. std::string getMainExecutable(const char *argv0, void *MainAddr) { #if defined(__APPLE__) // On OS X the executable path is saved to the stack by dyld. Reading it // from there is much faster than calling dladdr, especially for large // binaries with symbols. char exe_path[MAXPATHLEN]; uint32_t size = sizeof(exe_path); if (_NSGetExecutablePath(exe_path, &size) == 0) { char link_path[MAXPATHLEN]; if (realpath(exe_path, link_path)) return link_path; } #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ defined(__minix) || defined(__DragonFly__) || \ defined(__FreeBSD_kernel__) || defined(_AIX) char exe_path[PATH_MAX]; if (getprogpath(exe_path, argv0) != NULL) return exe_path; #elif defined(__linux__) || defined(__CYGWIN__) char exe_path[MAXPATHLEN]; StringRef aPath("/proc/self/exe"); if (sys::fs::exists(aPath)) { // /proc is not always mounted under Linux (chroot for example). ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path)); if (len >= 0) return std::string(exe_path, len); } else { // Fall back to the classical detection. if (getprogpath(exe_path, argv0)) return exe_path; } #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR) // Use dladdr to get executable path if available. Dl_info DLInfo; int err = dladdr(MainAddr, &DLInfo); if (err == 0) return ""; // If the filename is a symlink, we need to resolve and return the location of // the actual executable. char link_path[MAXPATHLEN]; if (realpath(DLInfo.dli_fname, link_path)) return link_path; #else #error GetMainExecutable is not implemented on this host yet. #endif return ""; } TimePoint<> basic_file_status::getLastAccessedTime() const { return toTimePoint(fs_st_atime); } TimePoint<> basic_file_status::getLastModificationTime() const { return toTimePoint(fs_st_mtime); } UniqueID file_status::getUniqueID() const { return UniqueID(fs_st_dev, fs_st_ino); } uint32_t file_status::getLinkCount() const { return fs_st_nlinks; } ErrorOr<space_info> disk_space(const Twine &Path) { struct STATVFS Vfs; if (::STATVFS(Path.str().c_str(), &Vfs)) return std::error_code(errno, std::generic_category()); auto FrSize = STATVFS_F_FRSIZE(Vfs); space_info SpaceInfo; SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize; SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize; SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize; return SpaceInfo; } std::error_code current_path(SmallVectorImpl<char> &result) { result.clear(); const char *pwd = ::getenv("PWD"); llvh::sys::fs::file_status PWDStatus, DotStatus; if (pwd && llvh::sys::path::is_absolute(pwd) && !llvh::sys::fs::status(pwd, PWDStatus) && !llvh::sys::fs::status(".", DotStatus) && PWDStatus.getUniqueID() == DotStatus.getUniqueID()) { result.append(pwd, pwd + strlen(pwd)); return std::error_code(); } #ifdef MAXPATHLEN result.reserve(MAXPATHLEN); #else // For GNU Hurd result.reserve(1024); #endif while (true) { if (::getcwd(result.data(), result.capacity()) == nullptr) { // See if there was a real error. if (errno != ENOMEM) return std::error_code(errno, std::generic_category()); // Otherwise there just wasn't enough space. result.reserve(result.capacity() * 2); } else break; } result.set_size(strlen(result.data())); return std::error_code(); } std::error_code set_current_path(const Twine &path) { SmallString<128> path_storage; StringRef p = path.toNullTerminatedStringRef(path_storage); if (::chdir(p.begin()) == -1) return std::error_code(errno, std::generic_category()); return std::error_code(); } std::error_code create_directory(const Twine &path, bool IgnoreExisting, perms Perms) { SmallString<128> path_storage; StringRef p = path.toNullTerminatedStringRef(path_storage); if (::mkdir(p.begin(), Perms) == -1) { if (errno != EEXIST || !IgnoreExisting) return std::error_code(errno, std::generic_category()); } return std::error_code(); } // Note that we are using symbolic link because hard links are not supported by // all filesystems (SMB doesn't). std::error_code create_link(const Twine &to, const Twine &from) { // Get arguments. SmallString<128> from_storage; SmallString<128> to_storage; StringRef f = from.toNullTerminatedStringRef(from_storage); StringRef t = to.toNullTerminatedStringRef(to_storage); if (::symlink(t.begin(), f.begin()) == -1) return std::error_code(errno, std::generic_category()); return std::error_code(); } std::error_code create_hard_link(const Twine &to, const Twine &from) { // Get arguments. SmallString<128> from_storage; SmallString<128> to_storage; StringRef f = from.toNullTerminatedStringRef(from_storage); StringRef t = to.toNullTerminatedStringRef(to_storage); if (::link(t.begin(), f.begin()) == -1) return std::error_code(errno, std::generic_category()); return std::error_code(); } std::error_code remove(const Twine &path, bool IgnoreNonExisting) { SmallString<128> path_storage; StringRef p = path.toNullTerminatedStringRef(path_storage); struct stat buf; if (lstat(p.begin(), &buf) != 0) { if (errno != ENOENT || !IgnoreNonExisting) return std::error_code(errno, std::generic_category()); return std::error_code(); } // Note: this check catches strange situations. In all cases, LLVM should // only be involved in the creation and deletion of regular files. This // check ensures that what we're trying to erase is a regular file. It // effectively prevents LLVM from erasing things like /dev/null, any block // special file, or other things that aren't "regular" files. if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode)) return make_error_code(errc::operation_not_permitted); if (::remove(p.begin()) == -1) { if (errno != ENOENT || !IgnoreNonExisting) return std::error_code(errno, std::generic_category()); } return std::error_code(); } static bool is_local_impl(struct STATVFS &Vfs) { #if defined(__linux__) #ifndef NFS_SUPER_MAGIC #define NFS_SUPER_MAGIC 0x6969 #endif #ifndef SMB_SUPER_MAGIC #define SMB_SUPER_MAGIC 0x517B #endif #ifndef CIFS_MAGIC_NUMBER #define CIFS_MAGIC_NUMBER 0xFF534D42 #endif switch ((uint32_t)Vfs.f_type) { case NFS_SUPER_MAGIC: case SMB_SUPER_MAGIC: case CIFS_MAGIC_NUMBER: return false; default: return true; } #elif defined(__CYGWIN__) // Cygwin doesn't expose this information; would need to use Win32 API. return false; #elif defined(__Fuchsia__) // Fuchsia doesn't yet support remote filesystem mounts. return true; #elif defined(__HAIKU__) // Haiku doesn't expose this information. return false; #elif defined(__sun) // statvfs::f_basetype contains a null-terminated FSType name of the mounted target StringRef fstype(Vfs.f_basetype); // NFS is the only non-local fstype?? return !fstype.equals("nfs"); #elif defined(__EMSCRIPTEN__) return false; #else return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL); #endif } std::error_code is_local(const Twine &Path, bool &Result) { struct STATVFS Vfs; if (::STATVFS(Path.str().c_str(), &Vfs)) return std::error_code(errno, std::generic_category()); Result = is_local_impl(Vfs); return std::error_code(); } std::error_code is_local(int FD, bool &Result) { struct STATVFS Vfs; if (::FSTATVFS(FD, &Vfs)) return std::error_code(errno, std::generic_category()); Result = is_local_impl(Vfs); return std::error_code(); } std::error_code rename(const Twine &from, const Twine &to) { // Get arguments. SmallString<128> from_storage; SmallString<128> to_storage; StringRef f = from.toNullTerminatedStringRef(from_storage); StringRef t = to.toNullTerminatedStringRef(to_storage); if (::rename(f.begin(), t.begin()) == -1) return std::error_code(errno, std::generic_category()); return std::error_code(); } std::error_code resize_file(int FD, uint64_t Size) { #if defined(HAVE_POSIX_FALLOCATE) // If we have posix_fallocate use it. Unlike ftruncate it always allocates // space, so we get an error if the disk is full. if (int Err = ::posix_fallocate(FD, 0, Size)) { if (Err != EINVAL && Err != EOPNOTSUPP) return std::error_code(Err, std::generic_category()); } #endif // Use ftruncate as a fallback. It may or may not allocate space. At least on // OS X with HFS+ it does. if (::ftruncate(FD, Size) == -1) return std::error_code(errno, std::generic_category()); return std::error_code(); } static int convertAccessMode(AccessMode Mode) { switch (Mode) { case AccessMode::Exist: return F_OK; case AccessMode::Write: return W_OK; case AccessMode::Execute: return R_OK | X_OK; // scripts also need R_OK. } llvm_unreachable("invalid enum"); } std::error_code access(const Twine &Path, AccessMode Mode) { SmallString<128> PathStorage; StringRef P = Path.toNullTerminatedStringRef(PathStorage); if (::access(P.begin(), convertAccessMode(Mode)) == -1) return std::error_code(errno, std::generic_category()); if (Mode == AccessMode::Execute) { // Don't say that directories are executable. struct stat buf; if (0 != stat(P.begin(), &buf)) return errc::permission_denied; if (!S_ISREG(buf.st_mode)) return errc::permission_denied; } return std::error_code(); } bool can_execute(const Twine &Path) { return !access(Path, AccessMode::Execute); } bool equivalent(file_status A, file_status B) { assert(status_known(A) && status_known(B)); return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino; } std::error_code equivalent(const Twine &A, const Twine &B, bool &result) { file_status fsA, fsB; if (std::error_code ec = status(A, fsA)) return ec; if (std::error_code ec = status(B, fsB)) return ec; result = equivalent(fsA, fsB); return std::error_code(); } static void expandTildeExpr(SmallVectorImpl<char> &Path) { StringRef PathStr(Path.begin(), Path.size()); if (PathStr.empty() || !PathStr.startswith("~")) return; PathStr = PathStr.drop_front(); StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); }); StringRef Remainder = PathStr.substr(Expr.size() + 1); SmallString<128> Storage; if (Expr.empty()) { // This is just ~/..., resolve it to the current user's home dir. if (!path::home_directory(Storage)) { // For some reason we couldn't get the home directory. Just exit. return; } // Overwrite the first character and insert the rest. Path[0] = Storage[0]; Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end()); return; } // This is a string of the form ~username/, look up this user's entry in the // password database. struct passwd *Entry = nullptr; std::string User = Expr.str(); Entry = ::getpwnam(User.c_str()); if (!Entry) { // Unable to look up the entry, just return back the original path. return; } Storage = Remainder; Path.clear(); Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir)); llvh::sys::path::append(Path, Storage); } static file_type typeForMode(mode_t Mode) { if (S_ISDIR(Mode)) return file_type::directory_file; else if (S_ISREG(Mode)) return file_type::regular_file; else if (S_ISBLK(Mode)) return file_type::block_file; else if (S_ISCHR(Mode)) return file_type::character_file; else if (S_ISFIFO(Mode)) return file_type::fifo_file; else if (S_ISSOCK(Mode)) return file_type::socket_file; else if (S_ISLNK(Mode)) return file_type::symlink_file; return file_type::type_unknown; } static std::error_code fillStatus(int StatRet, const struct stat &Status, file_status &Result) { if (StatRet != 0) { std::error_code EC(errno, std::generic_category()); if (EC == errc::no_such_file_or_directory) Result = file_status(file_type::file_not_found); else Result = file_status(file_type::status_error); return EC; } perms Perms = static_cast<perms>(Status.st_mode) & all_perms; Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev, Status.st_nlink, Status.st_ino, Status.st_atime, Status.st_mtime, Status.st_uid, Status.st_gid, Status.st_size); return std::error_code(); } std::error_code status(const Twine &Path, file_status &Result, bool Follow) { SmallString<128> PathStorage; StringRef P = Path.toNullTerminatedStringRef(PathStorage); struct stat Status; int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status); return fillStatus(StatRet, Status, Result); } std::error_code status(int FD, file_status &Result) { struct stat Status; int StatRet = ::fstat(FD, &Status); return fillStatus(StatRet, Status, Result); } std::error_code setPermissions(const Twine &Path, perms Permissions) { SmallString<128> PathStorage; StringRef P = Path.toNullTerminatedStringRef(PathStorage); if (::chmod(P.begin(), Permissions)) return std::error_code(errno, std::generic_category()); return std::error_code(); } std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime) { #if defined(HAVE_FUTIMENS) timespec Times[2]; Times[0] = sys::toTimeSpec(AccessTime); Times[1] = sys::toTimeSpec(ModificationTime); if (::futimens(FD, Times)) return std::error_code(errno, std::generic_category()); return std::error_code(); #elif defined(HAVE_FUTIMES) timeval Times[2]; Times[0] = sys::toTimeVal( std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime)); Times[1] = sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>( ModificationTime)); if (::futimes(FD, Times)) return std::error_code(errno, std::generic_category()); return std::error_code(); #else #warning Missing futimes() and futimens() return make_error_code(errc::function_not_supported); #endif } std::error_code mapped_file_region::init(int FD, uint64_t Offset, mapmode Mode) { assert(Size != 0); int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE; int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE); #if defined(__APPLE__) //---------------------------------------------------------------------- // Newer versions of MacOSX have a flag that will allow us to read from // binaries whose code signature is invalid without crashing by using // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media // is mapped we can avoid crashing and return zeroes to any pages we try // to read if the media becomes unavailable by using the // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping // with PROT_READ, so take care not to specify them otherwise. //---------------------------------------------------------------------- if (Mode == readonly) { #if defined(MAP_RESILIENT_CODESIGN) flags |= MAP_RESILIENT_CODESIGN; #endif #if defined(MAP_RESILIENT_MEDIA) flags |= MAP_RESILIENT_MEDIA; #endif } #endif // #if defined (__APPLE__) Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset); if (Mapping == MAP_FAILED) return std::error_code(errno, std::generic_category()); return std::error_code(); } mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length, uint64_t offset, std::error_code &ec) : Size(length), Mapping(), Mode(mode) { (void)Mode; ec = init(fd, offset, mode); if (ec) Mapping = nullptr; } mapped_file_region::~mapped_file_region() { if (Mapping) ::munmap(Mapping, Size); } size_t mapped_file_region::size() const { assert(Mapping && "Mapping failed but used anyway!"); return Size; } char *mapped_file_region::data() const { assert(Mapping && "Mapping failed but used anyway!"); return reinterpret_cast<char*>(Mapping); } const char *mapped_file_region::const_data() const { assert(Mapping && "Mapping failed but used anyway!"); return reinterpret_cast<const char*>(Mapping); } int mapped_file_region::alignment() { return Process::getPageSize(); } std::error_code detail::directory_iterator_construct(detail::DirIterState &it, StringRef path, bool follow_symlinks) { SmallString<128> path_null(path); DIR *directory = ::opendir(path_null.c_str()); if (!directory) return std::error_code(errno, std::generic_category()); it.IterationHandle = reinterpret_cast<intptr_t>(directory); // Add something for replace_filename to replace. path::append(path_null, "."); it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks); return directory_iterator_increment(it); } std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) { if (it.IterationHandle) ::closedir(reinterpret_cast<DIR *>(it.IterationHandle)); it.IterationHandle = 0; it.CurrentEntry = directory_entry(); return std::error_code(); } static file_type direntType(dirent* Entry) { // Most platforms provide the file type in the dirent: Linux/BSD/Mac. // The DTTOIF macro lets us reuse our status -> type conversion. #if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF) return typeForMode(DTTOIF(Entry->d_type)); #else // Other platforms such as Solaris require a stat() to get the type. return file_type::type_unknown; #endif } std::error_code detail::directory_iterator_increment(detail::DirIterState &It) { errno = 0; dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle)); if (CurDir == nullptr && errno != 0) { return std::error_code(errno, std::generic_category()); } else if (CurDir != nullptr) { StringRef Name(CurDir->d_name); if ((Name.size() == 1 && Name[0] == '.') || (Name.size() == 2 && Name[0] == '.' && Name[1] == '.')) return directory_iterator_increment(It); It.CurrentEntry.replace_filename(Name, direntType(CurDir)); } else return directory_iterator_destruct(It); return std::error_code(); } ErrorOr<basic_file_status> directory_entry::status() const { file_status s; if (auto EC = fs::status(Path, s, FollowSymlinks)) return EC; return s; } #if !defined(F_GETPATH) static bool hasProcSelfFD() { // If we have a /proc filesystem mounted, we can quickly establish the // real name of the file with readlink static const bool Result = (::access("/proc/self/fd", R_OK) == 0); return Result; } #endif static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags, FileAccess Access) { int Result = 0; if (Access == FA_Read) Result |= O_RDONLY; else if (Access == FA_Write) Result |= O_WRONLY; else if (Access == (FA_Read | FA_Write)) Result |= O_RDWR; // This is for compatibility with old code that assumed F_Append implied // would open an existing file. See Windows/Path.inc for a longer comment. if (Flags & F_Append) Disp = CD_OpenAlways; if (Disp == CD_CreateNew) { Result |= O_CREAT; // Create if it doesn't exist. Result |= O_EXCL; // Fail if it does. } else if (Disp == CD_CreateAlways) { Result |= O_CREAT; // Create if it doesn't exist. Result |= O_TRUNC; // Truncate if it does. } else if (Disp == CD_OpenAlways) { Result |= O_CREAT; // Create if it doesn't exist. } else if (Disp == CD_OpenExisting) { // Nothing special, just don't add O_CREAT and we get these semantics. } if (Flags & F_Append) Result |= O_APPEND; #ifdef O_CLOEXEC if (!(Flags & OF_ChildInherit)) Result |= O_CLOEXEC; #endif return Result; } std::error_code openFile(const Twine &Name, int &ResultFD, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode) { int OpenFlags = nativeOpenFlags(Disp, Flags, Access); SmallString<128> Storage; StringRef P = Name.toNullTerminatedStringRef(Storage); // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal // when open is overloaded, such as in Bionic. auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); }; if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0) return std::error_code(errno, std::generic_category()); #ifndef O_CLOEXEC if (!(Flags & OF_ChildInherit)) { int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC); (void)r; assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed"); } #endif return std::error_code(); } Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode) { int FD; std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode); if (EC) return errorCodeToError(EC); return FD; } std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags, SmallVectorImpl<char> *RealPath) { std::error_code EC = openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666); if (EC) return EC; // Attempt to get the real name of the file, if the user asked if(!RealPath) return std::error_code(); RealPath->clear(); #if defined(F_GETPATH) // When F_GETPATH is availble, it is the quickest way to get // the real path name. char Buffer[MAXPATHLEN]; if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1) RealPath->append(Buffer, Buffer + strlen(Buffer)); #else char Buffer[PATH_MAX]; if (hasProcSelfFD()) { char ProcPath[64]; snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD); ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer)); if (CharCount > 0) RealPath->append(Buffer, Buffer + CharCount); } else { SmallString<128> Storage; StringRef P = Name.toNullTerminatedStringRef(Storage); // Use ::realpath to get the real path name if (::realpath(P.begin(), Buffer) != nullptr) RealPath->append(Buffer, Buffer + strlen(Buffer)); } #endif return std::error_code(); } Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags, SmallVectorImpl<char> *RealPath) { file_t ResultFD; std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath); if (EC) return errorCodeToError(EC); return ResultFD; } void closeFile(file_t &F) { ::close(F); F = kInvalidFile; } template <typename T> static std::error_code remove_directories_impl(const T &Entry, bool IgnoreErrors) { std::error_code EC; directory_iterator Begin(Entry, EC, false); directory_iterator End; while (Begin != End) { auto &Item = *Begin; ErrorOr<basic_file_status> st = Item.status(); if (!st && !IgnoreErrors) return st.getError(); if (is_directory(*st)) { EC = remove_directories_impl(Item, IgnoreErrors); if (EC && !IgnoreErrors) return EC; } EC = fs::remove(Item.path(), true); if (EC && !IgnoreErrors) return EC; Begin.increment(EC); if (EC && !IgnoreErrors) return EC; } return std::error_code(); } std::error_code remove_directories(const Twine &path, bool IgnoreErrors) { auto EC = remove_directories_impl(path, IgnoreErrors); if (EC && !IgnoreErrors) return EC; EC = fs::remove(path, true); if (EC && !IgnoreErrors) return EC; return std::error_code(); } std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest, bool expand_tilde) { dest.clear(); if (path.isTriviallyEmpty()) return std::error_code(); if (expand_tilde) { SmallString<128> Storage; path.toVector(Storage); expandTildeExpr(Storage); return real_path(Storage, dest, false); } SmallString<128> Storage; StringRef P = path.toNullTerminatedStringRef(Storage); char Buffer[PATH_MAX]; if (::realpath(P.begin(), Buffer) == nullptr) return std::error_code(errno, std::generic_category()); dest.append(Buffer, Buffer + strlen(Buffer)); return std::error_code(); } } // end namespace fs namespace path { bool home_directory(SmallVectorImpl<char> &result) { char *RequestedDir = getenv("HOME"); if (!RequestedDir) { struct passwd *pw = getpwuid(getuid()); if (pw && pw->pw_dir) RequestedDir = pw->pw_dir; } if (!RequestedDir) return false; result.clear(); result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); return true; } static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) { #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR) // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR. // macros defined in <unistd.h> on darwin >= 9 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR; size_t ConfLen = confstr(ConfName, nullptr, 0); if (ConfLen > 0) { do { Result.resize(ConfLen); ConfLen = confstr(ConfName, Result.data(), Result.size()); } while (ConfLen > 0 && ConfLen != Result.size()); if (ConfLen > 0) { assert(Result.back() == 0); Result.pop_back(); return true; } Result.clear(); } #endif return false; } static const char *getEnvTempDir() { // Check whether the temporary directory is specified by an environment // variable. const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"}; for (const char *Env : EnvironmentVariables) { if (const char *Dir = std::getenv(Env)) return Dir; } return nullptr; } static const char *getDefaultTempDir(bool ErasedOnReboot) { #ifdef P_tmpdir if ((bool)P_tmpdir) return P_tmpdir; #endif if (ErasedOnReboot) return "/tmp"; return "/var/tmp"; } void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) { Result.clear(); if (ErasedOnReboot) { // There is no env variable for the cache directory. if (const char *RequestedDir = getEnvTempDir()) { Result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); return; } } if (getDarwinConfDir(ErasedOnReboot, Result)) return; const char *RequestedDir = getDefaultTempDir(ErasedOnReboot); Result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); } } // end namespace path } // end namespace sys } // end namespace llvh
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
c41cd21df8985b3b0de875c7a239f45ce75157e9
063b8adb6e966f0c22cb9ccb2f531aee3f3f9d30
/Exercicios de Linguagem C/14. OperadorCast.cpp
4cc311823107fbade5682575781b52a9a1bc560c
[ "MIT" ]
permissive
Patricia-Bianca-Lana-Largura/Linguagem-C
97edd20d12ae3c9860e88a2aa19b23838c421558
f78fec1c3560a2324e1f1cd3b1b92c40632a3495
refs/heads/master
2023-05-28T00:07:36.099010
2021-06-12T17:57:43
2021-06-12T17:57:43
252,269,686
0
0
null
null
null
null
ISO-8859-1
C++
false
false
287
cpp
#include <stdio.h> #include <stdlib.h> #include<locale.h> int main (int argc, char *argv[]){ setlocale(LC_ALL,"Portuguese"); //O operador cast converte os resultados de um tipo de dados para outro. float div; div =(float) 9/2; printf("Divisão: %.2f",div); return 0; }
[ "patricia.largura@outlook.com" ]
patricia.largura@outlook.com
bb1efea43289635b1533e6cb87d967f0ae988578
1f53cd338954fab08dfe242b010b2cdaec61b047
/4 listat/ushtrimi 2.cpp
f5b79c7cee5cf975028378f7338cfc0fc41bd893
[]
no_license
XhesikaLeka/ushtrime_ne_C_2
248b07d9c48f1447b41df342394240ed0b4a7182
7d8404a40c4a63471bcaf9b6d29886d6474f6b69
refs/heads/master
2020-09-17T07:22:39.370824
2019-11-25T20:27:00
2019-11-25T20:27:00
224,034,362
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
cpp
#include <stdio.h> #include <conio.h> #include <stdlib.h> typedef struct nyje { int vlere; struct nyje *pas; } nyje; nyje *krijo_nyje(int vlere) { nyje *n; n=(nyje*)malloc(sizeof(nyje)); n->vlere=vlere; n->pas=NULL; return n; } nyje *krijo_liste(int n) { if(n==0) return NULL; nyje *koka=NULL; int vlere; scanf("%d",&vlere); koka=krijo_nyje(vlere); nyje *eliri=koka; for(int i=2;i<=n;i++) { scanf("%d",&vlere); eliri->pas=krijo_nyje(vlere); eliri=eliri->pas; } eliri->pas=koka; return koka; } void afisho(nyje *L) { nyje *tmp=L; while(tmp->pas!=L) {printf("%d ",tmp->vlere); tmp=tmp->pas; } printf("%d ",tmp->vlere); } //Te ndertohet nje funksion qe merr si parameter nje liste nje-drejtimore rrethore dhe shton ne fund te listes nje nyje te re te barabarte me nyjen e fundit. nyje *shto (nyje *L) {nyje *tmp=L, *eliri=L; if(L==NULL) return NULL; else { eliri=(nyje*)malloc(sizeof(nyje)); while(tmp->pas!=L) {tmp=tmp->pas; } eliri->vlere=tmp->vlere; tmp->pas=eliri; eliri->pas=L; return L; } } int main () { int n; printf("Jep numrin e elementeve te listes: "); scanf("%d",&n); printf("Jep elementet e listes: "); nyje *L=krijo_liste(n); L=shto(L); afisho(L); getch(); return 0; }
[ "noreply@github.com" ]
XhesikaLeka.noreply@github.com
463776a140d2be772faaf2bdfae6377e6c6ae31f
9a94e85ef2820d626cd76123b9aa49190c991003
/HSPF_MRO_ANDR/build/iOS/Preview/include/Fuse.Elements.SimpleAlignment.h
0ecb9f203749785fb41395605e90f16edb9a76cb
[]
no_license
jaypk-104/FUSE
448db1717a29052f7b551390322a6167dfea34cd
0464afa07998eea8de081526a9337bd9af42dcf3
refs/heads/master
2023-03-13T14:32:43.855977
2021-03-18T01:57:10
2021-03-18T01:57:10
348,617,284
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Elements/1.12.0/Enums.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Fuse{ namespace Elements{ // internal enum SimpleAlignment uEnumType* SimpleAlignment_typeof(); }}} // ::g::Fuse::Elements
[ "sommelier0052@gmail.com" ]
sommelier0052@gmail.com
7c37a8e80e9ea70461033068e377f32eccea52a3
e4f93064a729d05ec4ae014038f59347ad191273
/DiscreteRods/thread_discrete_ref.cpp
42df5433de6fc37346b18bd3302e43de26e1e256
[]
no_license
joschu/surgical
221c349f8ba4e2c9c636931232821ce320004bac
5b26795b0cc2cb8ba02e3a4a27d2c0568134d83e
refs/heads/master
2021-01-17T22:52:12.573487
2011-07-19T00:56:31
2011-07-19T00:56:31
1,912,239
2
1
null
null
null
null
UTF-8
C++
false
false
57,324
cpp
#include "thread_discrete.h" Thread::Thread() { _thread_pieces.resize(0); } Thread::Thread(vector<Vector3d>& vertices, vector<double>& twist_angles, Matrix3d& start_rot) { _thread_pieces.resize(vertices.size()); _thread_pieces_backup.resize(vertices.size()); _angle_twist_backup.resize(vertices.size()); for (int i=0; i < vertices.size(); i++) { _thread_pieces[i] = ThreadPiece(vertices[i], twist_angles[i]); // _thread_pieces.push_back(ThreadPiece(vertices[i], twist_angles[i])); } for (int i=1; i < vertices.size(); i++) { _thread_pieces[i].set_prev(&_thread_pieces[i-1]); } for (int i=0; i < vertices.size()-1; i++) { _thread_pieces[i].set_next(&_thread_pieces[i+1]); } _thread_pieces.front().set_bishop_frame(start_rot); _thread_pieces.front().set_material_frame(start_rot); _thread_pieces.front().initializeFrames(); // _saved_last_thetas.resize(_thread_pieces.size()); //_saved_last_theta_changes.resize(_thread_pieces.size()); set_start_constraint(vertices.front(), start_rot); Matrix3d end_bishop = _thread_pieces[_thread_pieces.size()-2].bishop_frame(); Matrix3d end_rot = Eigen::AngleAxisd(twist_angles[twist_angles.size()-2], end_bishop.col(0).normalized())*end_bishop; set_end_constraint(vertices.back(), end_rot); //set_end_constraint(vertices.back(), end_rot); //project_length_constraint(); /* vector<Vector3d> vertices_actual; vector<Matrix3d> material_frames; get_thread_data(vertices_actual, material_frames); std::cout << "init data:\n"; for (int i=0; i < _thread_pieces.size(); i++) { if (i < _thread_pieces.size()-2) _thread_pieces[i].update_material_frame(); std::cout << "vertex:\n" << vertices_actual[i] << "\nmaterial frame:\n" << material_frames[i] << std::endl; } Matrix3d last_bishop = _thread_pieces[_thread_pieces.size()-2].bishop_frame(); std::cout << "last bishop:\n" << last_bishop << std::endl; std::cout << "last material:\n" << _thread_pieces.back().material_frame() << std::endl; std::cout << "last angle:\n" << _thread_pieces[_thread_pieces.size()-2].angle_twist() << std::endl; Vector3d offset(2.0, 2.0, 0.0); // set_start_constraint(offset, start_rot); _thread_pieces[3].offset_vertex(offset); */ /* int numInit = 50; Vector3d positions[numInit]; double angles[numInit]; for (int i=0; i < numInit; i++) { positions[i](0) = 10*(int)((i)/2.0)%2; positions[i](1) = 10*floor((i+1)/2); positions[i](2) = i*10; angles[i] =0; _thread_pieces.push_back(ThreadPiece(positions[i], angles[i])); //std::cout << positions[i] << std::endl << std::endl; } Vector3d tan = (_thread_pieces[1].vertex() - _thread_pieces[0].vertex()).normalized(); Vector3d toRotAxis; Matrix3d rot_for_frame; if ( (tan -Vector3d::UnitX()).norm() < 0.01 ) { rot_for_frame = Matrix3d::Identity(); } else { toRotAxis = Vector3d::UnitX().cross(tan); double Axisnorm = toRotAxis.norm(); double toRotAng = asin(Axisnorm); toRotAxis /= Axisnorm; // std::cout << "axis: " << toRotAxis << std::endl; // std::cout << "ang: " << toRotAng << std::endl; rot_for_frame = (Eigen::AngleAxisd(toRotAng, toRotAxis)); } //std::cout << "rot for frame: " << rot_for_frame << std::endl; _start_rot = rot_for_frame*Matrix3d::Identity(); //std::cout << "start frame: " << _start_rot << std::endl; std::cout << "energy: " << calculate_energy() << std::endl; */ } Thread::Thread(vector<Vector3d>& vertices, vector<double>& twist_angles, Matrix3d& start_rot, Matrix3d& end_rot) { //_thread_pieces.resize(vertices.size()); _thread_pieces_backup.resize(vertices.size()); _angle_twist_backup.resize(vertices.size()); _thread_pieces.resize(vertices.size()); for (int i=0; i < vertices.size(); i++) { _thread_pieces[i] = ThreadPiece(vertices[i], twist_angles[i]); //_thread_pieces.push_back(ThreadPiece(vertices[i], twist_angles[i])); } for (int i=1; i < vertices.size(); i++) { _thread_pieces[i].set_prev(&_thread_pieces[i-1]); } for (int i=0; i < vertices.size()-1; i++) { _thread_pieces[i].set_next(&_thread_pieces[i+1]); } _thread_pieces.front().set_bishop_frame(start_rot); _thread_pieces.front().set_material_frame(start_rot); _thread_pieces.front().initializeFrames(); // _saved_last_thetas.resize(_thread_pieces.size()); //_saved_last_theta_changes.resize(_thread_pieces.size()); set_constraints(vertices.front(), start_rot, vertices.back(), end_rot); //set_end_constraint(vertices.back(), end_rot); //project_length_constraint(); /* vector<Vector3d> vertices_actual; vector<Matrix3d> material_frames; get_thread_data(vertices_actual, material_frames); std::cout << "init data:\n"; for (int i=0; i < _thread_pieces.size(); i++) { if (i < _thread_pieces.size()-2) _thread_pieces[i].update_material_frame(); std::cout << "vertex:\n" << vertices_actual[i] << "\nmaterial frame:\n" << material_frames[i] << std::endl; } Matrix3d last_bishop = _thread_pieces[_thread_pieces.size()-2].bishop_frame(); std::cout << "last bishop:\n" << last_bishop << std::endl; std::cout << "last material:\n" << _thread_pieces.back().material_frame() << std::endl; std::cout << "last angle:\n" << _thread_pieces[_thread_pieces.size()-2].angle_twist() << std::endl; Vector3d offset(2.0, 2.0, 0.0); // set_start_constraint(offset, start_rot); _thread_pieces[3].offset_vertex(offset); */ /* int numInit = 50; Vector3d positions[numInit]; double angles[numInit]; for (int i=0; i < numInit; i++) { positions[i](0) = 10*(int)((i)/2.0)%2; positions[i](1) = 10*floor((i+1)/2); positions[i](2) = i*10; angles[i] =0; _thread_pieces.push_back(ThreadPiece(positions[i], angles[i])); //std::cout << positions[i] << std::endl << std::endl; } Vector3d tan = (_thread_pieces[1].vertex() - _thread_pieces[0].vertex()).normalized(); Vector3d toRotAxis; Matrix3d rot_for_frame; if ( (tan -Vector3d::UnitX()).norm() < 0.01 ) { rot_for_frame = Matrix3d::Identity(); } else { toRotAxis = Vector3d::UnitX().cross(tan); double Axisnorm = toRotAxis.norm(); double toRotAng = asin(Axisnorm); toRotAxis /= Axisnorm; // std::cout << "axis: " << toRotAxis << std::endl; // std::cout << "ang: " << toRotAng << std::endl; rot_for_frame = (Eigen::AngleAxisd(toRotAng, toRotAxis)); } //std::cout << "rot for frame: " << rot_for_frame << std::endl; _start_rot = rot_for_frame*Matrix3d::Identity(); //std::cout << "start frame: " << _start_rot << std::endl; std::cout << "energy: " << calculate_energy() << std::endl; */ } Thread::Thread(const Thread& rhs) { _thread_pieces.resize(rhs._thread_pieces.size()); _thread_pieces_backup.resize(rhs._thread_pieces.size()); _angle_twist_backup.resize(rhs._thread_pieces.size()); for (int piece_ind =0; piece_ind < rhs._thread_pieces.size(); piece_ind++) { //_thread_pieces.push_back(rhs._thread_pieces[piece_ind]); _thread_pieces[piece_ind] = rhs._thread_pieces[piece_ind]; } for (int i=1; i < _thread_pieces.size(); i++) { _thread_pieces[i].set_prev(&_thread_pieces[i-1]); } for (int i=0; i < _thread_pieces.size()-1; i++) { _thread_pieces[i].set_next(&_thread_pieces[i+1]); } _thread_pieces.front().set_bishop_frame(rhs.start_rot()); _thread_pieces.front().set_material_frame(rhs.start_rot()); _thread_pieces.front().initializeFrames(); //_saved_last_theta_changes.resize(_thread_pieces.size()); Matrix3d start_rot = rhs.start_rot(); Matrix3d end_rot = rhs.end_rot(); Vector3d start_pos = rhs.start_pos(); Vector3d end_pos = rhs.end_pos(); //set_constraints(start_pos, start_rot, end_pos, end_rot); set_start_constraint(start_pos, start_rot); set_end_constraint(end_pos, this->end_rot()); //project_length_constraint(); } Thread::~Thread() { } double Thread::calculate_energy() { /* double energy = 0.0; Matrix3d frame_prev = _start_rot; _thread_pieces.front().applyTwist(frame_prev); Matrix3d frame_after; Vector3d edge_prev = _thread_pieces[1].vertex() - _thread_pieces[0].vertex(); Vector3d edge_after; for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { //std::cout << "piece ind: " << piece_ind << " out of " << _thread_pieces.size() << std::endl; //std::cout << "vertex:\n" << _thread_pieces[piece_ind].vertex() << std::endl; energy += _thread_pieces[piece_ind].energy(frame_prev, edge_prev, _thread_pieces[piece_ind+1], frame_after, edge_after); //std::cout << energy << std::endl; //std::cout << "frame after:\n" << frame_after << std::endl; frame_prev = frame_after; edge_prev = edge_after; if (isnan(energy)) { std::cout << "energy is nan in calc energy" << std::endl; exit(0); } } //for final piece, tell it to twist to goal frame energy += _thread_pieces[_thread_pieces.size()-2].energy_with_goalframe(frame_prev, edge_prev, _thread_pieces[_thread_pieces.size()-1], frame_after, edge_after, _end_rot); return energy; */ #ifdef ISOTROPIC double energy = _thread_pieces[2].get_twist_coeff()*(pow(_thread_pieces[_thread_pieces.size()-2].angle_twist()-_thread_pieces.front().angle_twist(),2))/(2.0*_rest_length*(_thread_pieces.size()-2)); for (int piece_ind = 0; piece_ind < _thread_pieces.size(); piece_ind++) { energy += _thread_pieces[piece_ind].energy_curvature() + _thread_pieces[piece_ind].energy_grav(); } return energy; #else double energy = 0.0; for (int piece_ind = 0; piece_ind < _thread_pieces.size(); piece_ind++) { energy += _thread_pieces[piece_ind].energy(); } return energy; #endif } void Thread::minimize_energy_bfgs() { double step_in_grad_dir_vertices = 1.0; double grad_alpha = 0.4; double grad_beta = 0.8; num_iters_twist_est = num_iters_twist_est_max; const int num_opt_iters = 6000; const double energy_error_for_convergence = 1e-5; int N = _thread_pieces.size(); VectorXd vertex_gradients(3*N); vertex_gradients.setZero(); VectorXd new_gradients(3*N); new_gradients.setZero(); VectorXd yk(3*N); new_gradients.setZero(); MatrixXd Binv = MatrixXd::Identity(3*N,3*N); int opt_iter; double max_movement_vertices = MAX_MOVEMENT_VERTICES; for (opt_iter = 0; opt_iter < num_opt_iters; opt_iter++) { save_thread_pieces(); calculate_gradient_vertices_vectorized(&new_gradients); yk = new_gradients - vertex_gradients; vertex_gradients = Binv*new_gradients; //add_momentum_to_gradient(vertex_gradients, new_gradients, step_in_grad_dir_vertices); double curr_energy = calculate_energy(); double next_energy = 0.0; //binary search on energy function while satisfying wolfe condition step_in_grad_dir_vertices = max_movement_vertices/2.0; apply_vertex_offsets_vectorized(vertex_gradients, true, -(step_in_grad_dir_vertices)); double search_step = max_movement_vertices/4.0; double start_energy = calculate_energy(); while (search_step > MIN_MOVEMENT_VERTICES) //while (search_step > 1e-12) { //energy for adding search_step to current step size apply_vertex_offsets_vectorized(vertex_gradients, true, -search_step); minimize_energy_twist_angles(); double energy_add = calculate_energy(); //energy for subtracting search_step to current step size apply_vertex_offsets_vectorized(vertex_gradients, true, 2.0*search_step); minimize_energy_twist_angles(); double energy_subtract = calculate_energy(); if (start_energy < energy_add || start_energy < energy_subtract) { if (energy_add < energy_subtract) { apply_vertex_offsets_vectorized(vertex_gradients, true, -2.0*search_step); step_in_grad_dir_vertices += search_step; start_energy = energy_add; } else { step_in_grad_dir_vertices -= search_step; start_energy = energy_subtract; } } search_step /= 2.0; } minimize_energy_twist_angles(); double energy_before_projection = calculate_energy(); project_length_constraint(); minimize_energy_twist_angles(true); next_energy = calculate_energy(); if (next_energy + energy_error_for_convergence > curr_energy) { max_movement_vertices = step_in_grad_dir_vertices / 2.0; restore_thread_pieces(); if (max_movement_vertices <= MIN_MOVEMENT_VERTICES) break; } else { max_movement_vertices = min(step_in_grad_dir_vertices*2.0, MAX_MOVEMENT_VERTICES); } //std::cout << "max: " << max_movement_vertices << std::endl; VectorXd sk = -step_in_grad_dir_vertices*vertex_gradients; double skTyk = (sk.transpose()*yk)(0); Binv = Binv + (skTyk + (yk.transpose()*Binv*yk)(0))*(sk*sk.transpose()) / (skTyk*skTyk) - (Binv*yk*sk.transpose() + sk*yk.transpose()*Binv)/skTyk; cout << "Binv: " << endl; for(int i = 0; i < 3*N; i++) { for(int j = 0; j < 3*N; j++) { if (abs(i-j) > 0) { Binv(i,j) = 0; } if (Binv(i,j) < 1e-3) { Binv(i,j) = 0; } cout << Binv(i,j) << " "; } cout << endl; } } double curr_energy, next_energy; curr_energy = calculate_energy(); project_length_constraint(); minimize_energy_twist_angles(true); next_energy = calculate_energy(); //std::cout << "num iters: " << opt_iter << " curr energy final: " << curr_energy << " next energy final: " << next_energy << std::endl; } void Thread::minimize_energy_noiseStart() { //add noise double vertex_noise_factor = 0.1; vector<Vector3d> noise_offsets(_thread_pieces.size()); Vector3d ones_vec(1,1,1); for (int piece_ind =2; piece_ind < _thread_pieces.size()-2; piece_ind++) { Vector3d noise( ((double)(rand()%20000))/ 10000.0, ((double)(rand()%20000)) / 10000.0, ((double)(rand()%20000)) / 10000.0); noise_offsets[piece_ind] = noise-ones_vec; } apply_vertex_offsets(noise_offsets, true, vertex_noise_factor); minimize_energy(); } void Thread::minimize_energy() { double step_in_grad_dir_vertices = 1.0; // double grad_alpha = 0.4; // double grad_beta = 0.8; //vector<Vector3d> old_vertices; //vector<double> old_angles; num_iters_twist_est = num_iters_twist_est_max; const int num_opt_iters = 6000; const double energy_error_for_convergence = 1e-5; vector<Vector3d> vertex_gradients(_thread_pieces.size()); for (int piece_ind=0; piece_ind < vertex_gradients.size(); piece_ind++) { vertex_gradients[piece_ind].setZero(); } //vector<Vector3d> new_gradients(_thread_pieces.size()); int opt_iter; double max_movement_vertices = MAX_MOVEMENT_VERTICES; project_length_constraint(); bool recalc_vertex_grad = true; double curr_energy = calculate_energy(); double next_energy = 0.0; for (opt_iter = 0; opt_iter < num_opt_iters; opt_iter++) { //save_thread_pieces(); //_saved_last_theta = _thread_pieces[_thread_pieces.size()-2].angle_twist(); /*for (int piece_ind=0; piece_ind < _thread_pieces.size()-2; piece_ind++) { _saved_last_thetas[piece_ind] = _thread_pieces[piece_ind].angle_twist(); }*/ //std::cout << "opt iter vert: " << opt_iter << std::endl; //calculate_gradient_vertices(vertex_gradients); //calculate_gradient_vertices(new_gradients); // add_momentum_to_gradient(vertex_gradients, new_gradients, step_in_grad_dir_vertices); //for backtracing line search: /*double wolfe_condition_vertices = 0.0; for (int piece_ind = 2; piece_ind < _thread_pieces.size()-2; piece_ind++) { wolfe_condition_vertices += new_gradients[piece_ind].squaredNorm(); //std::cout << "piece " << piece_ind << " has gradient " << vertex_gradients[piece_ind].transpose() << std::endl; } wolfe_condition_vertices *= -grad_alpha; */ double curr_energy = calculate_energy(); double next_energy = 0.0; //get_thread_data(old_vertices, old_angles); //double curr_energy = calculate_energy(); //double next_energy = 0.0; //add_momentum_to_gradient(vertex_gradients, new_gradients, step_in_grad_dir_vertices); //step_in_grad_dir_vertices = 1.2/grad_beta; //step_in_grad_dir_vertices = MAX_MOVEMENT_VERTICES; //make sure step size not greater than limit /*double max_grad_norm = (*(std::max_element(vertex_gradients.begin()+2, vertex_gradients.end()-2, compare_vector_norms))).norm(); //std::cout << "max grad norm: " << max_grad_norm << std::endl; if (max_grad_norm*step_in_grad_dir_vertices > MAX_MOVEMENT_VERTICES*_rest_length) { step_in_grad_dir_vertices = (MAX_MOVEMENT_VERTICES*_rest_length / max_grad_norm); //std::cout << "new step: " << step_in_grad_dir_vertices << std::endl; }*/ /* apply_vertex_offsets(vertex_gradients, true, -(2.0-grad_beta)*(step_in_grad_dir_vertices)); do { step_in_grad_dir_vertices *= grad_beta; apply_vertex_offsets(vertex_gradients, true, (1.0-grad_beta)*step_in_grad_dir_vertices); next_energy = calculate_energy(); if (isnan(next_energy)) { std::cout << "energy nan" << std::endl; exit(0); } /std::cout << "opt iter num: " << opt_iter << " curr energy final: " << curr_energy << " next energy final: " << next_energy << "wolfe: " << wolfe_condition_vertices*step_in_grad_dir_vertices << std::endl; } while (next_energy > curr_energy + wolfe_condition_vertices*step_in_grad_dir_vertices && step_in_grad_dir_vertices > 1e-20); */ //binary search on energy function while satisfying wolfe condition save_thread_pieces(); if (recalc_vertex_grad) { calculate_gradient_vertices(vertex_gradients); make_max_norm_one(vertex_gradients); curr_energy = calculate_energy(); } step_in_grad_dir_vertices = max_movement_vertices/2.0; apply_vertex_offsets(vertex_gradients, true, -(step_in_grad_dir_vertices)); minimize_energy_twist_angles(); double search_step = max_movement_vertices/4.0; while (search_step > MIN_MOVEMENT_VERTICES) { //energy for adding search_step to current step size apply_vertex_offsets(vertex_gradients, true, -search_step); #ifndef ISOTROPIC minimize_energy_twist_angles(); #endif double energy_add = calculate_energy(); // if (energy_add > curr_energy + wolfe_condition_vertices*(step_in_grad_dir_vertices+search_step)) // energy_add = DBL_MAX; //energy for subtracting search_step to current step size apply_vertex_offsets(vertex_gradients, true, 2.0*search_step); #ifndef ISOTROPIC minimize_energy_twist_angles(); #endif double energy_subtract = calculate_energy(); // if (energy_subtract > curr_energy + wolfe_condition_vertices*(step_in_grad_dir_vertices-search_step)) // energy_subtract = DBL_MAX; //std::cout << "energy add: " << energy_add << " energy_subtract: " << energy_subtract << " search step: " << search_step << " curr step: " << step_in_grad_dir_vertices << std::endl; if (energy_add < energy_subtract) { apply_vertex_offsets(vertex_gradients, true, -2.0*search_step); step_in_grad_dir_vertices += search_step; } else { step_in_grad_dir_vertices -= search_step; } search_step /= 2.0; minimize_energy_twist_angles(); } minimize_energy_twist_angles(); double energy_before_projection = calculate_energy(); project_length_constraint(); minimize_energy_twist_angles(true); next_energy = calculate_energy(); //std::cout << "curr energy: " << curr_energy << " next energy: " << next_energy << " before projection: " << energy_before_projection << " last step: " << step_in_grad_dir_vertices << std::endl; recalc_vertex_grad = true; if (next_energy + energy_error_for_convergence > curr_energy) { if (next_energy >= curr_energy) { restore_thread_pieces(); recalc_vertex_grad = false; } if (max_movement_vertices <= MIN_MOVEMENT_VERTICES) { break; } max_movement_vertices = step_in_grad_dir_vertices / 2.0; } else { max_movement_vertices = min(step_in_grad_dir_vertices*2.0, MAX_MOVEMENT_VERTICES); //max_movement_vertices = MAX_MOVEMENT_VERTICES; } /* if (next_energy + energy_error_for_convergence > curr_energy) { restore_thread_pieces(); recalc_vertex_grad = false; max_movement_vertices = step_in_grad_dir_vertices / 2.0; if (max_movement_vertices <= MIN_MOVEMENT_VERTICES) { break; } } else { max_movement_vertices = min(step_in_grad_dir_vertices*2.0, MAX_MOVEMENT_VERTICES); //max_movement_vertices = MAX_MOVEMENT_VERTICES; } //std::cout << "max: " << max_movement_vertices << std::endl; } */ curr_energy = calculate_energy(); project_length_constraint(); minimize_energy_twist_angles(true); next_energy = calculate_energy(); //std::cout << "num iters: " << opt_iter << " curr energy final: " << curr_energy << " next energy final: " << next_energy << std::endl; } void Thread::one_step_project() { vector<Vector3d> vertex_gradients(_thread_pieces.size()); /* for (int piece_ind=0; piece_ind < vertex_gradients.size(); piece_ind++) { vertex_gradients[piece_ind].setZero(); } */ calculate_gradient_vertices(vertex_gradients); double norm_vecs = 0.0; for (int piece_ind=2; piece_ind < _thread_pieces.size()-2; piece_ind++) { norm_vecs += pow(vertex_gradients[piece_ind].norm(),2); //norm_vecs += vertex_gradients[piece_ind].norm(); } norm_vecs = sqrt(norm_vecs); //std::cout << "norm vecs: " << norm_vecs << std::endl; // make_max_norm_one(vertex_gradients); apply_vertex_offsets(vertex_gradients, true, -(0.1/norm_vecs), true); project_length_constraint(); } void Thread::minimize_energy_twist_angles(bool force_optimization) { #ifdef ISOTROPIC double angle_per = (_thread_pieces[_thread_pieces.size()-2].angle_twist())/((double)_thread_pieces.size()-2); //std::cout << "angle per: " << angle_per << std::endl; //#pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].set_angle_twist(angle_per*piece_ind); _thread_pieces[piece_ind].updateFrames_twistOnly(); } #else /* //if (num_iters_twist_est < num_iters_twist_est_max && !force_optimization && abs(_saved_last_theta_change) > 1e-20) if (num_iters_twist_est < num_iters_twist_est_max && !force_optimization) { num_iters_twist_est++; //this time, just estimate /* double theta_ratio = (_thread_pieces[_thread_pieces.size()-2].angle_twist() -_saved_last_theta)/_saved_last_theta_change; double new_thetas[_thread_pieces.size()]; //apply_angle_twist_offsets(_saved_last_theta_changes, true, theta_change); new_thetas[0] = _thread_pieces[0].angle_twist(); #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { //offset_thetas[piece_ind] = _saved_last_theta_changes[piece_ind] new_thetas[piece_ind] = _thread_pieces[piece_ind].angle_twist() + _saved_last_theta_changes[piece_ind]*theta_ratio; } #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].set_angle_twist(new_thetas[piece_ind]); _thread_pieces[piece_ind].updateFrames_twistOnly(); } */ /* double total_theta = _thread_pieces[_thread_pieces.size()-2].angle_twist(); double theta_ratio = total_theta/_saved_last_theta; double new_thetas[_thread_pieces.size()]; #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { new_thetas[piece_ind] = ((_thread_pieces[piece_ind].angle_twist() - _thread_pieces[piece_ind-1].angle_twist()) * theta_ratio + _thread_pieces[piece_ind-1].angle_twist()); } #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].set_angle_twist(new_thetas[piece_ind]); _thread_pieces[piece_ind].updateFrames_twistOnly(); } return; } */ num_iters_twist_est = 0; double step_in_grad_dir_twist = 1.0; double max_rotation_twist = MAX_ROTATION_TWIST; // double grad_alpha = 0.4; // double grad_beta = 0.8; const int num_opt_iters = 100; const double energy_error_for_convergence = 1e-20; vector<double> angle_twist_gradients; angle_twist_gradients.resize(_thread_pieces.size()); //vector<double> angles_before(_thread_pieces.size()); //vector<double> angles_after(_thread_pieces.size()); //save_angle_twists(angles_before); int opt_iter; for (opt_iter = 0; opt_iter < num_opt_iters; opt_iter++) { // std::cout << "opt iter twist: " << opt_iter << std::endl; calculate_gradient_twist(angle_twist_gradients); double max_grad_norm = (*(std::max_element(angle_twist_gradients.begin()+1, angle_twist_gradients.end()-2))); double mult_const = 1.0/max_grad_norm; for (int piece_ind=1; piece_ind < _thread_pieces.size()-1; piece_ind++) { angle_twist_gradients[piece_ind] *= mult_const; } /* //for backtracing line search: double wolfe_condition_angles = 0.0; for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { wolfe_condition_angles += angle_twist_gradients[piece_ind]*angle_twist_gradients[piece_ind]; } */ double curr_energy = calculate_energy(); double next_energy = 0.0; step_in_grad_dir_twist = max_rotation_twist/2.0; apply_angle_twist_offsets(angle_twist_gradients, true, -(step_in_grad_dir_twist)); double search_step = max_rotation_twist/4.0; while (search_step > MIN_ROTATION_TWIST) { //energy for adding search_step to current step size apply_angle_twist_offsets(angle_twist_gradients, true, -search_step); double energy_add = calculate_energy(); apply_angle_twist_offsets(angle_twist_gradients, true, 2.0*search_step); double energy_subtract = calculate_energy(); if (energy_add < energy_subtract) { apply_angle_twist_offsets(angle_twist_gradients, true, -2.0*search_step); step_in_grad_dir_twist += search_step; } else { step_in_grad_dir_twist -= search_step; } search_step /= 2.0; } next_energy = calculate_energy(); //std::cout << "curr energy: " << curr_energy << " next energy: " << next_energy << " last step: " << step_in_grad_dir_twist << std::endl; if (next_energy + energy_error_for_convergence > curr_energy) { break; } else { max_rotation_twist = min(step_in_grad_dir_twist*2.0, MAX_ROTATION_TWIST); } //std::cout << "max: " << max_movement_vertices << std::endl; } double curr_energy, next_energy; curr_energy = calculate_energy(); next_energy = calculate_energy(); //std::cout << "num iters: " << opt_iter << " curr energy final: " << curr_energy << " next energy final: " << next_energy << std::endl; /*step_in_grad_dir_twist *= 2.0/grad_beta; wolfe_condition_angles *= -grad_alpha; //std::cout << "energy: " << curr_energy << " plus: " << wolfe_condition << std::endl; apply_angle_twist_offsets(angle_twist_gradients, true, -(2.0-grad_beta)*(step_in_grad_dir_twist*grad_beta)); do { //std::cout << "step size: " << step_in_grad_dir << std::endl; step_in_grad_dir_twist *= grad_beta; apply_angle_twist_offsets(angle_twist_gradients, true, (1.0-grad_beta)*step_in_grad_dir_twist); next_energy = calculate_energy(); //std::cout << "next energy: " << next_energy << std::endl; if (isnan(next_energy)) { std::cout << "energy nan" << std::endl; exit(0); } } while (next_energy > curr_energy + wolfe_condition_angles*step_in_grad_dir_twist && step_in_grad_dir_twist > 1e-10); next_energy = calculate_energy(); if (next_energy + energy_error_for_convergence > curr_energy) break; } */ //_saved_last_theta_change = _thread_pieces[_thread_pieces.size()-2].angle_twist() - _saved_last_theta; //save_angle_twists(angles_after); //save_angle_twist_changes(angles_before, angles_after); #endif } void Thread::minimize_energy_vertices() { double step_in_grad_dir_vertices = 1.0; double grad_alpha = 0.4; double grad_beta = 0.8; const int num_opt_iters = 1000; const double energy_error_for_convergence = 1e-6; vector<Vector3d> vertex_gradients; vertex_gradients.resize(_thread_pieces.size()); for (int opt_iter = 0; opt_iter < num_opt_iters; opt_iter++) { //std::cout << "opt iter vert: " << opt_iter << std::endl; calculate_gradient_vertices(vertex_gradients); //for backtracing line search: double wolfe_condition_vertices = 0.0; for (int piece_ind = 2; piece_ind < _thread_pieces.size()-2; piece_ind++) { wolfe_condition_vertices += vertex_gradients[piece_ind].squaredNorm(); // std::cout << "piece " << piece_ind << " has gradient " << vertex_gradients[piece_ind].transpose() << std::endl; } double curr_energy = calculate_energy(); double next_energy = 0.0; step_in_grad_dir_vertices *= 2.0/grad_beta; wolfe_condition_vertices *= -grad_alpha; apply_vertex_offsets(vertex_gradients, true, -(2.0-grad_beta)*(step_in_grad_dir_vertices*grad_beta)); do { step_in_grad_dir_vertices *= grad_beta; apply_vertex_offsets(vertex_gradients, true, (1.0-grad_beta)*step_in_grad_dir_vertices); next_energy = calculate_energy(); if (isnan(next_energy)) { std::cout << "energy nan" << std::endl; exit(0); } } while (next_energy > curr_energy + wolfe_condition_vertices*step_in_grad_dir_vertices && step_in_grad_dir_vertices > 1e-10); project_length_constraint(); next_energy = calculate_energy(); /* double curr_energy = calculate_energy(); std::cout << "curr energy: " << curr_energy << std::endl; step_in_grad_dir_vertices = pow(0.95, opt_iter); apply_vertex_offsets(vertex_gradients, true, step_in_grad_dir_vertices); project_length_constraint(); minimize_energy_twist_angles(); */ } project_length_constraint(); } void Thread::calculate_gradient(vector<Vector3d>& vertex_gradients, vector<double>& angle_twist_gradients) { calculate_gradient_vertices(vertex_gradients); calculate_gradient_twist(angle_twist_gradients); } void Thread::calculate_gradient_vertices_vectorized(VectorXd* gradient) { Vector3d tmp; for (int piece_ind = 2; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].gradient_vertex(tmp); gradient->segment<3>(3*piece_ind) = tmp; } } void Thread::calculate_gradient_vertices(vector<Vector3d>& vertex_gradients) { //#pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 2; piece_ind < _thread_pieces.size()-2; piece_ind++) { //_thread_pieces[piece_ind].gradient_vertex_numeric(vertex_gradients[piece_ind]); //std::cout << "piece ind " << piece_ind << " old grad: " << vertex_gradients[piece_ind].transpose() << std::endl; _thread_pieces[piece_ind].gradient_vertex(vertex_gradients[piece_ind]); //std::cout << "piece ind " << piece_ind << " new grad: " << vertex_gradients[piece_ind].transpose() << std::endl; } } void Thread::make_max_norm_one(vector<Vector3d>& to_normalize) { double max_grad_norm = (*(std::max_element(to_normalize.begin()+2, to_normalize.end()-2, compare_vector_norms))).norm(); // #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int pieceInd = 2; pieceInd < _thread_pieces.size()-2; pieceInd++) { to_normalize[pieceInd] /= max_grad_norm; } } void Thread::add_momentum_to_gradient(vector<Vector3d>& vertex_gradients, vector<Vector3d>& new_gradients, double last_step_size) { double max_grad_norm = (*(std::max_element(new_gradients.begin()+2, new_gradients.end()-2, compare_vector_norms))).norm(); double mult_const = 1.0/max_grad_norm; double last_vertex_mult_const = MOMENTUM_CONSTANT*last_step_size/MAX_MOVEMENT_VERTICES; //#pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 2; piece_ind < new_gradients.size()-2; piece_ind++) { vertex_gradients[piece_ind] = new_gradients[piece_ind]*mult_const + last_vertex_mult_const*vertex_gradients[piece_ind]; } } void Thread::calculate_gradient_twist(vector<double>& angle_twist_gradients) { //#pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].gradient_twist(angle_twist_gradients[piece_ind]); } } void Thread::project_length_constraint_old() { const int num_iters_project = 5000; const double projection_scale_factor = 0.75; const double max_norm_to_break = 1e-5; vector<Vector3d> vertex_offsets(_thread_pieces.size()); for (int i=0; i < _thread_pieces.size(); i++) { vertex_offsets[i].setZero(); } int iter_num; for (iter_num=0; iter_num < num_iters_project; iter_num++) { //first and last 2 pieces are special cases - assumed length is correct //so 2nd edge and 2nd to last edge are treated as special cases Vector3d curr_edge = _thread_pieces[2].vertex() - _thread_pieces[1].vertex(); double edge_norm = curr_edge.norm(); bool projected_enough = abs(edge_norm-_rest_length) < max_norm_to_break; vertex_offsets[2] = (curr_edge/edge_norm)*((_rest_length-edge_norm)); for (int edge_ind = 2; edge_ind < _thread_pieces.size()-3; edge_ind++) { curr_edge = _thread_pieces[edge_ind+1].vertex() - _thread_pieces[edge_ind].vertex(); edge_norm = curr_edge.norm(); curr_edge = curr_edge/edge_norm; //this already set by previous iteration, so just add this offset vertex_offsets[edge_ind] += (curr_edge)*((edge_norm - _rest_length)/2.0); //initialize this vertex vertex_offsets[edge_ind+1] = (curr_edge)*((_rest_length - edge_norm)/2.0); projected_enough &= (abs(edge_norm-_rest_length) < max_norm_to_break); } curr_edge = _thread_pieces[_thread_pieces.size()-2].vertex() - _thread_pieces[_thread_pieces.size()-3].vertex(); edge_norm = curr_edge.norm(); vertex_offsets[_thread_pieces.size()-3] += (curr_edge/edge_norm)*((edge_norm - _rest_length)); projected_enough &= (abs(edge_norm-_rest_length) < max_norm_to_break); /* Vector3d edge_before = _thread_pieces[2].vertex() - _thread_pieces[1].vertex(); double edge_before_norm = edge_before.norm(); Vector3d edge_after = _thread_pieces[2].vertex() - _thread_pieces[3].vertex(); double edge_after_norm = edge_after.norm(); vertex_offsets[2] = (edge_before/edge_before_norm) * (_rest_length-edge_before_norm) + 0.5*(edge_after/edge_after_norm) * (_rest_length-edge_after_norm); bool projected_enough = abs(edge_before_norm-_rest_length) < max_norm_to_break; edge_before = _thread_pieces[_thread_pieces.size()-3].vertex() - _thread_pieces[_thread_pieces.size()-4].vertex(); edge_before_norm = edge_before.norm(); edge_after = _thread_pieces[_thread_pieces.size()-3].vertex() - _thread_pieces[_thread_pieces.size()-2].vertex(); edge_after_norm = edge_after.norm(); vertex_offsets[_thread_pieces.size()-3] = 0.5*(edge_before/edge_before_norm)*(_rest_length-edge_before_norm) + (edge_after/edge_after_norm) * (_rest_length-edge_after_norm); //projected_enough &= abs(edge_after_norm-_rest_length) < max_norm_to_break; #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int edge_ind = 3; edge_ind < _thread_pieces.size()-4; edge_ind++) { Vector3d edge_before_curr = _thread_pieces[edge_ind].vertex() - _thread_pieces[edge_ind-1].vertex(); double edge_before_norm_curr = edge_before_curr.norm(); Vector3d edge_after_curr = _thread_pieces[edge_ind].vertex() - _thread_pieces[edge_ind+1].vertex(); double edge_after_norm_curr = edge_after_curr.norm(); vertex_offsets[edge_ind] = 0.5* ((edge_before_curr/edge_before_norm_curr) * (_rest_length-edge_before_norm_curr) + (edge_after_curr/edge_after_norm_curr) * (_rest_length-edge_after_norm_curr)); if (abs(edge_before_norm_curr-_rest_length) > max_norm_to_break) projected_enough = false; } */ /* if (vertex_offsets[_thread_pieces.size()-3].norm() > 3) { std::cout << "iter " << iter_num << "piece " << (_thread_pieces.size()-3) << " projection offset big " << vertex_offsets[_thread_pieces.size()-3]<< std::endl; } */ //apply the actual offsets apply_vertex_offsets(vertex_offsets, true, projection_scale_factor, iter_num == (num_iters_project-1) || projected_enough); if (projected_enough) break; } //std::cout << "num projs: " << iter_num << std::endl; } void Thread::project_length_constraint() { const int num_iters_project = 50; const double projection_scale_factor = 1.0; const double max_norm_to_break = 1e-5; // set up the augmented lagrangian system: need C, grad C, mass mat. // y is the coordinates of all vertices // dy is what we are solving for // optimize dy ' * dy + C lambda // what is h? // \nabla C(x) nabla C(x)^T lambda = C, // dy = nabla C(x_j) lambda // dy = -nabla C(x_j)^T (nabla C(x) nabla C(x)^T)^-1 C(x) int N = _thread_pieces.size(); VectorXd C(N-3); MatrixXd gradC(N-3, 3*(N-4)); vector<Vector3d> vertex_offsets(_thread_pieces.size()); int iter_num; Vector3d next_point; Vector3d cur_point; double normerror; VectorXd dy(3*(N-4)); for (iter_num=0; iter_num < num_iters_project; iter_num++) { C.setZero(); gradC.setZero(); dy.setZero(); for(int i = 0; i < N-3; i++) { next_point = _thread_pieces[i+2].vertex(); cur_point = _thread_pieces[i+1].vertex(); C[i] = (next_point - cur_point).squaredNorm() - _rest_length*_rest_length; } gradC.block<1,3>(0,0) = (_thread_pieces[2].vertex() - _thread_pieces[1].vertex())*2; for(int i = 1; i < N-4; i++) { gradC.block<1,3>(i,3*(i-1)) = (_thread_pieces[i+2].vertex() - _thread_pieces[i+1].vertex())*-2; gradC.block<1,3>(i,3*i) = (_thread_pieces[i+2].vertex() - _thread_pieces[i+1].vertex())*2; } gradC.block<1,3>(N-4,3*(N-5)) = (_thread_pieces[N-2].vertex() - _thread_pieces[N-3].vertex())*-2; // slower lu decomposition // VectorXd dl(N-5); // (gradC*gradC.transpose()).lu().solve(C,&dl); // VectorXd dy = -gradC.transpose()*dl; (gradC*gradC.transpose()).llt().solveInPlace(C); dy = -gradC.transpose()*C; for(int i = 2; i < N-2; i++) { for(int j = 0; j < 3; j++) { vertex_offsets[i](j) = dy(3*(i-2)+j); } } bool projected_enough = true; normerror = 0.0; for(int i = 0; i < N-5; i++) { projected_enough &= (abs(C[i]) < max_norm_to_break); normerror += abs(C[i]); } //apply the actual offsets apply_vertex_offsets(vertex_offsets, true, projection_scale_factor, iter_num == (num_iters_project-1) || projected_enough); if (projected_enough) break; } // cout << iter_num << " " << normerror << endl; } void Thread::project_length_constraint_slow() { const int num_iters_project = 900000; const double projection_scale_factor = 0.33; const double max_norm_to_break = 1e-8; vector<Vector3d> vertex_offsets(_thread_pieces.size()); for (int i=0; i < _thread_pieces.size(); i++) { vertex_offsets[i] = Vector3d::Zero(); } int iter_num; for (iter_num=0; iter_num < num_iters_project; iter_num++) { //first and last 2 pieces are special cases - assumed length is correct //so 2nd edge and 2nd to last edge are treated as special cases Vector3d curr_edge = _thread_pieces[2].vertex() - _thread_pieces[1].vertex(); double edge_norm = curr_edge.norm(); bool projected_enough = abs(edge_norm-_rest_length) < max_norm_to_break; vertex_offsets[2] = (curr_edge/edge_norm)*((_rest_length-edge_norm)); for (int edge_ind = 2; edge_ind < _thread_pieces.size()-3; edge_ind++) { curr_edge = _thread_pieces[edge_ind+1].vertex() - _thread_pieces[edge_ind].vertex(); edge_norm = curr_edge.norm(); curr_edge = curr_edge/edge_norm; //this already set by previous iteration, so just add this offset vertex_offsets[edge_ind] += (curr_edge)*((edge_norm - _rest_length)/2.0); //initialize this vertex vertex_offsets[edge_ind+1] = (curr_edge)*((_rest_length - edge_norm)/2.0); projected_enough &= (abs(edge_norm-_rest_length) < max_norm_to_break); } curr_edge = _thread_pieces[_thread_pieces.size()-2].vertex() - _thread_pieces[_thread_pieces.size()-3].vertex(); edge_norm = curr_edge.norm(); vertex_offsets[_thread_pieces.size()-3] += (curr_edge/edge_norm)*((edge_norm - _rest_length)); projected_enough &= (abs(edge_norm-_rest_length) < max_norm_to_break); /* Vector3d edge_before = _thread_pieces[2].vertex() - _thread_pieces[1].vertex(); double edge_before_norm = edge_before.norm(); Vector3d edge_after = _thread_pieces[2].vertex() - _thread_pieces[3].vertex(); double edge_after_norm = edge_after.norm(); vertex_offsets[2] = (edge_before/edge_before_norm) * (_rest_length-edge_before_norm) + 0.5*(edge_after/edge_after_norm) * (_rest_length-edge_after_norm); bool projected_enough = abs(edge_before_norm-_rest_length) < max_norm_to_break; edge_before = _thread_pieces[_thread_pieces.size()-3].vertex() - _thread_pieces[_thread_pieces.size()-4].vertex(); edge_before_norm = edge_before.norm(); edge_after = _thread_pieces[_thread_pieces.size()-3].vertex() - _thread_pieces[_thread_pieces.size()-2].vertex(); edge_after_norm = edge_after.norm(); vertex_offsets[_thread_pieces.size()-3] = 0.5*(edge_before/edge_before_norm)*(_rest_length-edge_before_norm) + (edge_after/edge_after_norm) * (_rest_length-edge_after_norm); //projected_enough &= abs(edge_after_norm-_rest_length) < max_norm_to_break; #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int edge_ind = 3; edge_ind < _thread_pieces.size()-4; edge_ind++) { Vector3d edge_before_curr = _thread_pieces[edge_ind].vertex() - _thread_pieces[edge_ind-1].vertex(); double edge_before_norm_curr = edge_before_curr.norm(); Vector3d edge_after_curr = _thread_pieces[edge_ind].vertex() - _thread_pieces[edge_ind+1].vertex(); double edge_after_norm_curr = edge_after_curr.norm(); vertex_offsets[edge_ind] = 0.5* ((edge_before_curr/edge_before_norm_curr) * (_rest_length-edge_before_norm_curr) + (edge_after_curr/edge_after_norm_curr) * (_rest_length-edge_after_norm_curr)); if (abs(edge_before_norm_curr-_rest_length) > max_norm_to_break) projected_enough = false; } */ /* if (vertex_offsets[_thread_pieces.size()-3].norm() > 3) { std::cout << "iter " << iter_num << "piece " << (_thread_pieces.size()-3) << " projection offset big " << vertex_offsets[_thread_pieces.size()-3]<< std::endl; } */ //apply the actual offsets apply_vertex_offsets(vertex_offsets, true, projection_scale_factor, iter_num == (num_iters_project-1) || projected_enough); if (projected_enough) break; } //std::cout << "num projs: " << iter_num << std::endl; } void Thread::apply_vertex_offsets(vector<Vector3d>& offsets, bool skip_edge_cases, double step_size, bool update_frames) { if (!skip_edge_cases) { exit(0); _thread_pieces[0].offset_vertex(step_size*offsets[0]); _thread_pieces[1].offset_vertex(step_size*offsets[1]); _thread_pieces[_thread_pieces.size()-2].offset_vertex(step_size*offsets[_thread_pieces.size()-2]); _thread_pieces[_thread_pieces.size()-1].offset_vertex(step_size*offsets[_thread_pieces.size()-1]); } // #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 2; piece_ind < (_thread_pieces.size()-2); piece_ind++) { _thread_pieces[piece_ind].offset_vertex(step_size*offsets[piece_ind]); } if (update_frames) { _thread_pieces.front().updateFrames_all(); /* // std::cout << "last angle before: " << _thread_pieces[_thread_pieces.size()-2].angle_twist() << std::endl; Matrix3d end_rot = this->end_rot(); // std::cout << "end rot before:\n" << end_rot << std::endl; Vector3d end_pos = _thread_pieces[_thread_pieces.size()-1].vertex(); _thread_pieces.front().initializeFrames(); //update_all_frames(); // std::cout << "last angle mid: " << _thread_pieces[_thread_pieces.size()-2].angle_twist() << std::endl; end_rot = this->end_rot();//_thread_pieces[_thread_pieces.size()-1].material_frame(); // std::cout << "end rot mid:\n" << end_rot << std::endl; set_end_constraint(end_pos, end_rot); // std::cout << "last angle after: " << _thread_pieces[_thread_pieces.size()-2].angle_twist() << std::endl; end_rot = this->end_rot();//_thread_pieces[_thread_pieces.size()-1].material_frame(); // std::cout << "end rot after:\n" << end_rot << std::endl; // */ } } void Thread::apply_vertex_offsets_vectorized(const VectorXd& offsets, bool skip_edge_cases, double step_size, bool update_frames) { if (!skip_edge_cases) { exit(0); // _thread_pieces[0].offset_vertex(step_size*offsets[0]); // _thread_pieces[1].offset_vertex(step_size*offsets[1]); // _thread_pieces[_thread_pieces.size()-2].offset_vertex(step_size*offsets[_thread_pieces.size()-2]); // _thread_pieces[_thread_pieces.size()-1].offset_vertex(step_size*offsets[_thread_pieces.size()-1]); } // #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 2; piece_ind < (_thread_pieces.size()-2); piece_ind++) { Vector3d offset = offsets.segment<3>(3*piece_ind); _thread_pieces[piece_ind].offset_vertex(step_size*offset); } if (update_frames) { _thread_pieces.front().updateFrames_all(); } } void Thread::apply_angle_twist_offsets(vector<double>& offsets, bool skip_edge_cases, double step_size) { if (!skip_edge_cases) { exit(0); _thread_pieces[_thread_pieces.size()-2].offset_angle_twist(step_size*offsets[_thread_pieces.size()-2]); _thread_pieces[_thread_pieces.size()-1].offset_angle_twist(step_size*offsets[_thread_pieces.size()-1]); } // #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind = 1; piece_ind < _thread_pieces.size()-2; piece_ind++) { _thread_pieces[piece_ind].offset_angle_twist(step_size*offsets[piece_ind]); _thread_pieces[piece_ind].updateFrames_twistOnly(); } } /*void Thread::save_angle_twists(vector<double>& angles) { #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind=1; piece_ind < _thread_pieces.size()-2; piece_ind++) { angles[piece_ind] = _thread_pieces[piece_ind].angle_twist() - _thread_pieces[piece_ind-1].angle_twist(); } } void Thread::save_angle_twist_changes(vector<double>& start_angles, vector<double>& end_angles) { // std::cout << "\nsaved angles\n"; #pragma omp parallel for num_threads(NUM_THREADS_PARALLEL_FOR) for (int piece_ind=0; piece_ind < _thread_pieces.size()-2; piece_ind++) { _saved_last_theta_changes[piece_ind] = end_angles[piece_ind] - start_angles[piece_ind]; // std::cout << _saved_last_theta_changes[piece_ind] << std::endl; } // std::cout << "\n"; } */ void Thread::save_thread_pieces() { for (int piece_ind=0; piece_ind < _thread_pieces.size(); piece_ind++) { _thread_pieces_backup[piece_ind] = _thread_pieces[piece_ind]; } for (int i=1; i < _thread_pieces_backup.size(); i++) { _thread_pieces_backup[i].set_prev(&_thread_pieces_backup[i-1]); } for (int i=0; i < _thread_pieces_backup.size()-1; i++) { _thread_pieces_backup[i].set_next(&_thread_pieces_backup[i+1]); } } void Thread::restore_thread_pieces() { for (int piece_ind=0; piece_ind < _thread_pieces_backup.size(); piece_ind++) { _thread_pieces[piece_ind] = _thread_pieces_backup[piece_ind]; } for (int i=1; i < _thread_pieces.size(); i++) { _thread_pieces[i].set_prev(&_thread_pieces[i-1]); } for (int i=0; i < _thread_pieces.size()-1; i++) { _thread_pieces[i].set_next(&_thread_pieces[i+1]); } } void Thread::save_angle_twists() { for (int piece_ind=0; piece_ind < _thread_pieces.size(); piece_ind++) { _angle_twist_backup[piece_ind] = _thread_pieces[piece_ind].angle_twist(); } } void Thread::restore_angle_twists() { for (int piece_ind=0; piece_ind < _angle_twist_backup.size(); piece_ind++) { _thread_pieces[piece_ind].set_angle_twist(_angle_twist_backup[piece_ind]); _thread_pieces[piece_ind].update_material_frame(); } } void Thread::get_thread_data(vector<Vector3d>& points, vector<double>& twist_angles) { points.resize(_thread_pieces.size()); twist_angles.resize(_thread_pieces.size()); for (int piece_ind=0; piece_ind < _thread_pieces.size(); piece_ind++) { points[piece_ind] = _thread_pieces[piece_ind].vertex(); twist_angles[piece_ind] = _thread_pieces[piece_ind].angle_twist(); } } void Thread::get_thread_data(vector<Vector3d>& points, vector<Matrix3d>& material_frames) { points.resize(_thread_pieces.size()); material_frames.resize(_thread_pieces.size()); for (int piece_ind=0; piece_ind < _thread_pieces.size(); piece_ind++) { points[piece_ind] = _thread_pieces[piece_ind].vertex(); material_frames[piece_ind] = _thread_pieces[piece_ind].material_frame(); } } void Thread::get_thread_data(vector<Vector3d>& points, vector<double>& twist_angles, vector<Matrix3d>& material_frames) { points.resize(_thread_pieces.size()); twist_angles.resize(_thread_pieces.size()); material_frames.resize(_thread_pieces.size()); for (int piece_ind=0; piece_ind < _thread_pieces.size(); piece_ind++) { points[piece_ind] = _thread_pieces[piece_ind].vertex(); twist_angles[piece_ind] = _thread_pieces[piece_ind].angle_twist(); material_frames[piece_ind] = _thread_pieces[piece_ind].material_frame(); } } bool Thread::is_consistent() { bool toRtn = true; for (int piece_ind=0; piece_ind < _thread_pieces.size()-1; piece_ind++) { toRtn &= _thread_pieces[piece_ind].is_material_frame_consistent(); } return toRtn; } double Thread::calculate_holonomy() { /* vector<ThreadPiece> pieces_for_calc(4); pieces_for_calc[0] = ThreadPiece(_thread_pieces[0].vertex(), 0.0); pieces_for_calc[1] = ThreadPiece(_thread_pieces[1].vertex(), 0.0); //Vector3d edge_first2 = pieces_for_calc[1].vertex() - pieces_for_calc[0].vertex(); //Vector3d edge_last2 = _thread_pieces[_thread_pieces.size()-1].vertex() - _thread_pieces[_thread_pieces.size()-2].vertex(); pieces_for_calc[2] = ThreadPiece(pieces_for_calc[1].vertex()+edge_first2, 0.0); pieces_for_calc[3] = ThreadPiece(_thread_pieces[_thread_pieces.size()-1].vertex()-pieces_for_calc[2].vertex(), 0.0); for (int i=1; i < pieces_for_calc.size(); i++) { pieces_for_calc[i].set_prev(&pieces_for_calc[i-1]); } for (int i=0; i < pieces_for_calc.size()-1; i++) { pieces_for_calc[i].set_next(&pieces_for_calc[i+1]); } pieces_for_calc.front().set_bishop_frame(_thread_pieces.front().bishop_frame()); pieces_for_calc.front().set_material_frame(_thread_pieces.front().bishop_frame()); Matrix3d start_rot = pieces_for_calc.front().bishop_frame(); Vector3d start_pos = pieces_for_calc.front().vertex(); Matrix3d end_rot = _thread_pieces[_thread_pieces.size()-2].bishop_frame(); pieces_for_calc.front().initializeFrames(); //to fix tangent, set 2nd point as well pieces_for_calc.front().updateFrames_firstpiece(); //pieces_for_calc.back().set_material_frame(end_rot); //pieces_for_calc.back().updateFrames_lastpiece(); */ Vector3d edge_first2 = _thread_pieces[1].vertex() - _thread_pieces.front().vertex(); Vector3d edge_last2 = _thread_pieces[_thread_pieces.size()-1].vertex() - _thread_pieces[_thread_pieces.size()-2].vertex(); Matrix3d no_twist_bishop; Vector3d to_twist_around = edge_first2.cross(edge_last2)/(_rest_length*_rest_length + edge_first2.dot(edge_last2)); to_twist_around.normalize(); if (isnan(to_twist_around(0))) { no_twist_bishop = _thread_pieces.front().bishop_frame(); } else { //double ang_to_twist = asin(to_twist_around.norm()); double ang_to_twist = edge_first2.dot(edge_last2)/(edge_first2.norm()*edge_last2.norm()); ang_to_twist = max( min ( ang_to_twist, 1.0), -1.0); ang_to_twist = acos(ang_to_twist); no_twist_bishop = Eigen::AngleAxisd(ang_to_twist, to_twist_around.normalized())*_thread_pieces.front().bishop_frame(); } double holonomy = angle_mismatch(_thread_pieces[_thread_pieces.size()-2].bishop_frame(), no_twist_bishop); // double holonomy = angle_mismatch(_thread_pieces[_thread_pieces.size()-2].bishop_frame(), pieces_for_calc[pieces_for_calc.size()-2].bishop_frame()); return holonomy; } void Thread::set_constraints(const Vector3d& start_pos, const Matrix3d& start_rot, const Vector3d& end_pos, const Matrix3d& end_rot) { set_start_constraint(start_pos, start_rot); set_end_constraint(end_pos, end_rot); } void Thread::set_start_constraint(const Vector3d& start_pos, const Matrix3d& start_rot) { _thread_pieces.front().set_vertex(start_pos); //_start_rot = start_rot; _thread_pieces.front().set_bishop_frame(start_rot); _thread_pieces.front().set_material_frame(start_rot); //to fix tangent, set 2nd point as well Vector3d fixed_point = start_pos + start_rot.col(0)*_rest_length; _thread_pieces[1].set_vertex(fixed_point); _thread_pieces.front().updateFrames_firstpiece(); } //assumes bishop frame for end is already calculated void Thread::set_end_constraint(const Vector3d& end_pos, const Matrix3d& end_rot) { _thread_pieces.back().set_vertex(end_pos); //_end_rot = end_rot; _thread_pieces.back().set_material_frame(end_rot); //to fix tangent, set 2nd to last point as well Vector3d fixed_point = end_pos - end_rot.col(0)*_rest_length; _thread_pieces[_thread_pieces.size()-2].set_vertex(fixed_point); _thread_pieces.back().updateFrames_lastpiece(); } void Thread::set_coeffs_normalized(double bend_coeff, double twist_coeff, double grav_coeff) { double norm_factor = 1.0/sqrt(pow(bend_coeff,2) + pow(twist_coeff,2) + pow(grav_coeff,2)); _thread_pieces.front().set_bend_coeff(bend_coeff*norm_factor); _thread_pieces.front().set_twist_coeff(twist_coeff*norm_factor); _thread_pieces.front().set_grav_coeff(grav_coeff*norm_factor); } void Thread::set_coeffs_normalized(const Matrix2d& bend_matrix, double twist_coeff, double grav_coeff) { double norm_factor = 1.0/sqrt(bend_matrix.determinant() + pow(twist_coeff,2) + pow(grav_coeff,2)); _thread_pieces.front().set_bend_matrix(bend_matrix*norm_factor); _thread_pieces.front().set_twist_coeff(twist_coeff*norm_factor); _thread_pieces.front().set_grav_coeff(grav_coeff*norm_factor); } Thread& Thread::operator=(const Thread& rhs) { //_thread_pieces.resize(rhs._thread_pieces.size()); _thread_pieces.resize(rhs._thread_pieces.size()); _thread_pieces_backup.resize(rhs._thread_pieces.size()); _angle_twist_backup.resize(rhs._thread_pieces.size()); for (int piece_ind =0; piece_ind < rhs._thread_pieces.size(); piece_ind++) { //_thread_pieces.push_back(rhs._thread_pieces[piece_ind]); _thread_pieces[piece_ind] = rhs._thread_pieces[piece_ind]; } for (int i=1; i < _thread_pieces.size(); i++) { _thread_pieces[i].set_prev(&_thread_pieces[i-1]); } for (int i=0; i < _thread_pieces.size()-1; i++) { _thread_pieces[i].set_next(&_thread_pieces[i+1]); } _thread_pieces.front().set_bishop_frame(rhs.start_rot()); _thread_pieces.front().set_material_frame(rhs.start_rot()); _thread_pieces.front().initializeFrames(); //_saved_last_theta_changes.resize(_thread_pieces.size()); Matrix3d start_rot = rhs.start_rot(); Matrix3d end_rot = rhs.end_rot(); Vector3d start_pos = rhs.start_pos(); Vector3d end_pos = rhs.end_pos(); set_constraints(start_pos, start_rot, end_pos, end_rot); //project_length_constraint(); /* Matrix3d end_bishop = rhs._thread_pieces[_thread_pieces.size()-2].bishop_frame(); double end_angle = rhs._thread_pieces[_thread_pieces.size()-2].angle_twist(); Matrix3d end_rot_calculated = Eigen::AngleAxisd(end_angle, end_bishop.col(0).normalized())*end_bishop; set_end_constraint(end_pos, end_rot_calculated); */ //set_end_constraint(vertices.back(), end_rot); return *this; }
[ "sameep.tandon@gmail.com" ]
sameep.tandon@gmail.com
59eb582999cf3755ecc32984a185fff5bf16b97f
ddfe55314123068bc46c9cf8e12dec2c9ab61c53
/Space/Arabian.h
35218699a535ade156897ff0ee15016c70cfe321
[]
no_license
sysfce2/Metal-Slug-2.8489545
19786ee1611a7be2b2b967baef1f090f18a0756b
4eb7398da7c9cee9e890e7cbe7cc94403bab5ccc
refs/heads/master
2023-03-15T18:34:07.861334
2020-10-11T09:41:40
2020-10-11T09:41:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
510
h
#pragma once class ArabianState; class Arabian : public Object { public: Sprite* m_Arabian; Animation* m_Body; Sprite* m_Sight; Arabian(Vec2 Pos); ~Arabian(); bool m_isGround; float m_vY; float m_Speed; float m_ThrowCoolDown; int m_Dire; bool m_Death; ArabianState* m_State; void ChangeImage(std::wstring body, int first, int last); void Gravity(); void SetImagePos(); void Move(int Dire); void Update(float deltaTime,float Time); void Render(); void OnCollision(Object* other); };
[ "38340705+8489545@users.noreply.github.com" ]
38340705+8489545@users.noreply.github.com
5e3c5088ab2e8f6ca421c05aff03c6e15216dde3
dc25b23f8132469fd95cee14189672cebc06aa56
/vendor/mediatek/proprietary/hardware/audio/common/include/SpeechMessengerInterface.h
fe01571ed305c991ecca915c67d8bb40722c26f2
[]
no_license
nofearnohappy/alps_mm
b407d3ab2ea9fa0a36d09333a2af480b42cfe65c
9907611f8c2298fe4a45767df91276ec3118dd27
refs/heads/master
2020-04-23T08:46:58.421689
2019-03-28T21:19:33
2019-03-28T21:19:33
171,048,255
1
5
null
2020-03-08T03:49:37
2019-02-16T20:25:00
Java
UTF-8
C++
false
false
12,902
h
#ifndef ANDROID_SPEECH_MESSAGE_INTERFACE_H #define ANDROID_SPEECH_MESSAGE_INTERFACE_H #include <pthread.h> #include "AudioType.h" #include "SpeechType.h" #include "AudioUtility.h" #include "SpeechBGSPlayer.h" #include "SpeechPcm2way.h" namespace android { #define CCCI_BUF_HEADER_SIZE 16 //EEMCS MTU 3584-128 = 3456 byte #define CCCI_MAX_PAYLOAD_SIZE 860 //(3456-16)/4 = 860 /** CCCI buffer structure */ typedef struct { uint32_t magic; uint32_t message; // message[31:16] = id, message[15:0] = parameters uint32_t channel; uint32_t reserved; uint32_t payload[CCCI_MAX_PAYLOAD_SIZE]; } ccci_buff_t; /** CCCI driver & ioctl */ /** CCCI message need/no need ack type */ enum ccci_message_ack_t { MESSAGE_BYPASS_ACK = 0, MESSAGE_NEED_ACK = 1, MESSAGE_CANCELED = 8 }; /** CCCI message queue structure */ typedef struct ccci_queue_element_t { ccci_buff_t ccci_buff; ccci_message_ack_t ack_type; } ccci_queue_element_t; /** Speech parameter ack type */ enum speech_param_ack_t { NB_SPEECH_PARAM = 0, DMNR_SPEECH_PARAM, WB_SPEECH_PARAM, MAGICON_SPEECH_PARAM, HAC_SPEECH_PARAM, DYNAMIC_SPH_PARAM, NUM_SPEECH_PARAM_ACK_TYPE }; /** CCCI share buffer related infomation */ const size_t CCCI_SHARE_BUFF_HEADER_LEN = 6; const size_t CCCI_PAYLOAD_BUFF_HEADER_LEN = 10; const size_t CCCI_RAW_PCM_BUFF_HEADER_LEN = 8; enum share_buff_sync_t { CCCI_A2M_SHARE_BUFF_HEADER_SYNC = 0xA2A2, CCCI_M2A_SHARE_BUFF_HEADER_SYNC = 0x2A2A, EEMCS_M2A_SHARE_BUFF_HEADER_SYNC = 0x1234 }; enum share_buff_data_type_t { SHARE_BUFF_DATA_TYPE_PCM_FillSE = 0, SHARE_BUFF_DATA_TYPE_PCM_FillSpk, SHARE_BUFF_DATA_TYPE_PCM_GetFromMic, SHARE_BUFF_DATA_TYPE_PCM_GetfromSD, SHARE_BUFF_DATA_TYPE_CCCI_VM_TYPE, SHARE_BUFF_DATA_TYPE_CCCI_PCM_TYPE, SHARE_BUFF_DATA_TYPE_CCCI_BGS_TYPE, SHARE_BUFF_DATA_TYPE_CCCI_EM_PARAM, SHARE_BUFF_DATA_TYPE_CCCI_CTM_UL_IN, SHARE_BUFF_DATA_TYPE_CCCI_CTM_DL_IN, SHARE_BUFF_DATA_TYPE_CCCI_CTM_UL_OUT, SHARE_BUFF_DATA_TYPE_CCCI_CTM_DL_OUT, SHARE_BUFF_DATA_TYPE_CCCI_VIBSPK_PARAM, SHARE_BUFF_DATA_TYPE_CCCI_NXP_SMARTPA_PARAM = 15, SHARE_BUFF_DATA_TYPE_CCCI_MAGICON_PARAM, SHARE_BUFF_DATA_TYPE_CCCI_HAC_PARAM, SHARE_BUFF_DATA_TYPE_CCCI_RAW_PCM_TYPE, SHARE_BUFF_DATA_TYPE_CCCI_DYNAMIC_PARAM_TYPE, SHARE_BUFF_DATA_TYPE_CCCI_NW_CODEC_INFO, SHARE_BUFF_DATA_TYPE_CCCI_MAX_TYPE }; //For VT case, the CCCI message for every 20ms, UL/DL have 2 CCCI message (Put to Speaker / Get from Mic) //For BGS off ack message, the worst case maybe pending 150 ms. And for other change device control. (BGSoff,2WAY off,SPH off,...) //The total message maybe > 20 for this period. So enlarge the total CCCI message queue. //For the CCCI queue in CCCI kernel driver, the size is 60. //For the CCCI queue in Modem side, the size is 32. //Modem side would keep on optimized the BGS off ack period. const size_t CCCI_MAX_QUEUE_NUM = 60; // BG Sound use 2026 bytes // MAX => 16K PCM2WAY use 2026+6 bytes const size_t A2M_SHARED_BUFFER_BGS_DATA_SIZE = 2026; const size_t A2M_SHARED_BUFFER_BGS_DATA_BASE = 0; const size_t A2M_SHARED_BUFFER_BGS_DATA_END = A2M_SHARED_BUFFER_BGS_DATA_BASE + CCCI_SHARE_BUFF_HEADER_LEN + A2M_SHARED_BUFFER_BGS_DATA_SIZE; // PCM2WAY playback use 640 bytes // MAX => 16K PCM2WAY use 640+6 bytes const size_t A2M_SHARED_BUFFER_P2W_DL_DATA_BASE = A2M_SHARED_BUFFER_BGS_DATA_END; const size_t A2M_SHARED_BUFFER_P2W_DL_DATA_END = A2M_SHARED_BUFFER_P2W_DL_DATA_BASE + CCCI_SHARE_BUFF_HEADER_LEN + PCM2WAY_PLAY_BUFFER_WB_LEN; // Speech enhacement parameters // MAX => WB Param use 2416+6 bytes const size_t A2M_SHARED_BUFFER_SPH_PARAM_BASE = A2M_SHARED_BUFFER_P2W_DL_DATA_END; /* CCCI Message ID */ const uint32_t CCCI_MSG_A2M_BASE = 0x2F00; const uint32_t CCCI_MSG_M2A_BASE = 0xAF00; class SpeechMessengerInterface { public: virtual ~SpeechMessengerInterface() {} virtual status_t Initial() = 0; virtual status_t Deinitial() = 0; virtual bool A2MBufLock() = 0; virtual void A2MBufUnLock() = 0; virtual status_t WaitUntilModemReady() = 0; virtual ccci_buff_t InitCcciMailbox(uint16_t id, uint16_t param_16bit, uint32_t param_32bit) = 0; virtual status_t SendMessageInQueue(ccci_buff_t ccci_buff) = 0; inline uint32_t GetA2MShareBufLen() const { return mA2MShareBufLen; } inline char *GetA2MShareBufBase() const { return mA2MShareBufBase; } inline uint8_t SetShareBufHeader(uint16_t *ptr16, uint16_t sync, share_buff_data_type_t type, uint16_t length) const { ptr16[0] = sync; ptr16[1] = type; ptr16[2] = length; return CCCI_SHARE_BUFF_HEADER_LEN; // 3 * sizeof(uint16_t); } inline uint32_t GetM2AShareBufLen() const { return mM2AShareBufLen; } inline char *GetM2AShareBufBase() const { return mM2AShareBufBase; } virtual uint16_t GetM2AShareBufSyncWord(const ccci_buff_t &ccci_buff) = 0; virtual uint16_t GetM2AShareBufDataType(const ccci_buff_t &ccci_buff) = 0; virtual uint16_t GetM2AShareBufDataLength(const ccci_buff_t &ccci_buff) = 0; /** * get modem side modem function status */ virtual bool GetModemSideModemStatus(const modem_status_mask_t modem_status_mask) const = 0; /** * check whether modem side get all necessary speech enhancement parameters here */ virtual bool CheckSpeechParamAckAllArrival() = 0; /** * check whether modem is ready. (if w/o SIM && phone_2 => modem sleep) */ virtual bool CheckModemIsReady() = 0; /** * check whether modem audio is ready from reset. */ virtual bool GetMDResetFlag() = 0; /** * set raw record type. */ virtual status_t SetPcmRecordType(record_type_t type_record) = 0; protected: virtual char GetModemCurrentStatus() = 0; virtual uint16_t GetMessageID(const ccci_buff_t &ccci_buff) = 0; virtual uint16_t GetMessageParam(const ccci_buff_t &ccci_buff) = 0; virtual uint16_t GetMessageLength(const ccci_buff_t &ccci_buff) = 0; virtual uint16_t GetMessageOffset(const ccci_buff_t &ccci_buff) = 0; virtual bool CheckOffsetAndLength(const ccci_buff_t &ccci_buff) = 0; virtual ccci_message_ack_t JudgeAckOfMsg(const uint16_t message_id) = 0; virtual bool IsModemFunctionOnOffMessage(const uint16_t message_id) = 0; virtual status_t SendMessage(const ccci_buff_t &ccci_buff) = 0; virtual status_t ReadMessage(ccci_buff_t &ccci_buff) = 0; virtual void SendMsgFailErrorHandling(const ccci_buff_t &ccci_buff) = 0; virtual RingBuf GetM2AUplinkRingBuffer(const ccci_buff_t &ccci_buff) = 0; virtual status_t CreateReadingThread() = 0; virtual status_t CreateSendSphParaThread() = 0; // for message queue virtual uint32_t GetQueueCount() const = 0; virtual status_t ConsumeMessageInQueue() = 0; virtual bool MDReset_CheckMessageInQueue() = 0; virtual void MDReset_FlushMessageInQueue() = 0; virtual void ResetSpeechParamAckCount() = 0; virtual void AddSpeechParamAckCount(speech_param_ack_t type) = 0; /** * set/reset AP side modem function status */ virtual void SetModemSideModemStatus(const modem_status_mask_t modem_status_mask) = 0; virtual void ResetModemSideModemStatus(const modem_status_mask_t modem_status_mask) = 0; // lock virtual bool SpeechParamLock() = 0; virtual void SpeechParamUnLock() = 0; // share buffer base and len uint32_t mA2MShareBufLen; uint32_t mM2AShareBufLen; char *mA2MShareBufBase; char *mM2AShareBufBase; char *mA2MShareBufEnd; char *mM2AShareBufEnd; RingBuf mM2AShareBuf; }; enum ccci_message_id_t { //------------------ A2M ----------------------- MSG_A2M_SPH_DL_DIGIT_VOLUME = CCCI_MSG_A2M_BASE, MSG_A2M_SPH_UL_DIGIT_VOLUME, MSG_A2M_MUTE_SPH_UL, MSG_A2M_MUTE_SPH_DL, MSG_A2M_SIDETONE_VOLUME, MSG_A2M_SPH_DL_ENH_REF_DIGIT_VOLUME, MSG_A2M_SIDETONE_CONFIG, // Using modem SW STF or not MSG_A2M_MUTE_SPH_UL_ENH_RESULT, MSG_A2M_MUTE_SPH_UL_SOURCE, MSG_A2M_SET_SAMPLE_RATE = CCCI_MSG_A2M_BASE | 0x10, MSG_A2M_SPH_ON = CCCI_MSG_A2M_BASE | 0x20, MSG_A2M_SPH_OFF, MSG_A2M_SET_SPH_MODE, MSG_A2M_CTRL_SPH_ENH, MSG_A2M_CONFIG_SPH_ENH, MSG_A2M_SET_ACOUSTIC_LOOPBACK, MSG_A2M_PRINT_SPH_PARAM, MSG_A2M_SPH_ON_FOR_HOLD_CALL, // speech on with mute, for call hold use, no any other application can be turn on MSG_A2M_SPH_ON_FOR_DACA, MSG_A2M_SPH_ROUTER_ON, // PCM wrouter on for enhancement and other application path. MSG_A2M_PNW_ON = CCCI_MSG_A2M_BASE | 0x30, MSG_A2M_PNW_OFF, MSG_A2M_RECORD_ON, MSG_A2M_RECORD_OFF, MSG_A2M_DMNR_RECPLAY_ON, MSG_A2M_DMNR_RECPLAY_OFF, MSG_A2M_DMNR_REC_ONLY_ON, MSG_A2M_DMNR_REC_ONLY_OFF, MSG_A2M_PCM_REC_ON, MSG_A2M_PCM_REC_OFF, MSG_A2M_VM_REC_ON, MSG_A2M_VM_REC_OFF, MSG_A2M_RECORD_RAW_PCM_ON, MSG_A2M_RECORD_RAW_PCM_OFF, MSG_A2M_CTM_ON = CCCI_MSG_A2M_BASE | 0x40, MSG_A2M_CTM_OFF, MSG_A2M_CTM_DUMP_DEBUG_FILE, MSG_A2M_BGSND_ON, MSG_A2M_BGSND_OFF, MSG_A2M_BGSND_CONFIG, MSG_A2M_PNW_DL_DATA_NOTIFY = CCCI_MSG_A2M_BASE | 0x50, MSG_A2M_BGSND_DATA_NOTIFY, MSG_A2M_CTM_DATA_NOTIFY, MSG_A2M_PNW_UL_DATA_READ_ACK = CCCI_MSG_A2M_BASE | 0x60, MSG_A2M_REC_DATA_READ_ACK, MSG_A2M_CTM_DEBUG_DATA_READ_ACK, MSG_A2M_PCM_REC_DATA_READ_ACK, MSG_A2M_VM_REC_DATA_READ_ACK, MSG_A2M_DACA_DL_DATA_READ_ACK, MSG_A2M_RAW_PCM_REC_DATA_READ_ACK, MSG_A2M_EM_DATA_REQUEST_ACK = CCCI_MSG_A2M_BASE | 0x70, MSG_A2M_EM_NB, MSG_A2M_EM_DMNR, MSG_A2M_EM_WB, MSG_A2M_EM_MAGICON, MSG_A2M_NETWORK_STATUS_ACK, MSG_A2M_QUERY_RF_INFO, MSG_A2M_EM_HAC, MSG_A2M_EPOF_ACK, MSG_A2M_EM_DYNAMIC_SPH, MSG_A2M_VIBSPK_PARAMETER = CCCI_MSG_A2M_BASE | 0x80, MSG_A2M_NXP_SMARTPA_PARAMETER, MSG_A2M_NW_CODEC_INFO_READ_ACK = CCCI_MSG_A2M_BASE | 0x90, //------------------- M2A ---------------------- MSG_M2A_SPH_DL_DIGIT_VOLUME_ACK = CCCI_MSG_M2A_BASE, MSG_M2A_SPH_UL_DIGIT_VOLUME_ACK, MSG_M2A_MUTE_SPH_UL_ACK, MSG_M2A_MUTE_SPH_DL_ACK, MSG_M2A_SIDETONE_VOLUME_ACK, MSG_M2A_SPH_DL_ENH_REF_DIGIT_VOLUME_ACK, // just define, not used. MSG_M2A_SIDETONE_CONFIG_ACK, // just define, not used. MSG_M2A_SET_SAMPLE_RATE_ACK = CCCI_MSG_M2A_BASE + 0x10, MSG_M2A_SPH_ON_ACK = CCCI_MSG_M2A_BASE + 0x20, MSG_M2A_SPH_OFF_ACK, MSG_M2A_SET_SPH_MODE_ACK, MSG_M2A_CTRL_SPH_ENH_ACK, MSG_M2A_CONFIG_SPH_ENH_ACK, MSG_M2A_SET_ACOUSTIC_LOOPBACK_ACK, MSG_M2A_PRINT_SPH_COEFF_ACK, MSG_M2A_SPH_ON_FOR_HOLD_CALL_ACK, MSG_M2A_SPH_ON_FOR_DACA_ACK, MSG_M2A_SPH_ROUTER_ON_ACK, MSG_M2A_PNW_ON_ACK = CCCI_MSG_M2A_BASE + 0x30, MSG_M2A_PNW_OFF_ACK, MSG_M2A_RECORD_ON_ACK, MSG_M2A_RECORD_OFF_ACK, MSG_M2A_DMNR_RECPLAY_ON_ACK, MSG_M2A_DMNR_RECPLAY_OFF_ACK, MSG_M2A_DMNR_REC_ONLY_ON_ACK, MSG_M2A_DMNR_REC_ONLY_OFF_ACK, MSG_M2A_PCM_REC_ON_ACK, MSG_M2A_PCM_REC_OFF_ACK, MSG_M2A_VM_REC_ON_ACK, MSG_M2A_VM_REC_OFF_ACK, MSG_M2A_RECORD_RAW_PCM_ON_ACK, MSG_M2A_RECORD_RAW_PCM_OFF_ACK, MSG_M2A_CTM_ON_ACK = CCCI_MSG_M2A_BASE + 0x40, MSG_M2A_CTM_OFF_ACK, MSG_M2A_CTM_DUMP_DEBUG_FILE_ACK, MSG_M2A_BGSND_ON_ACK, MSG_M2A_BGSND_OFF_ACK, MSG_M2A_BGSND_CONFIG_ACK, MSG_M2A_PNW_DL_DATA_REQUEST = CCCI_MSG_M2A_BASE + 0x50, MSG_M2A_BGSND_DATA_REQUEST, MSG_M2A_CTM_DATA_REQUEST, MSG_M2A_PNW_UL_DATA_NOTIFY = CCCI_MSG_M2A_BASE + 0x60, MSG_M2A_REC_DATA_NOTIFY, MSG_M2A_CTM_DEBUG_DATA_NOTIFY, MSG_M2A_PCM_REC_DATA_NOTIFY, MSG_M2A_VM_REC_DATA_NOTIFY, MSG_M2A_DACA_DL_DATA_NOTIFY, MSG_M2A_RAW_PCM_REC_DATA_NOTIFY, MSG_M2A_EM_DATA_REQUEST = CCCI_MSG_M2A_BASE + 0x70, MSG_M2A_EM_NB_ACK, MSG_M2A_EM_DMNR_ACK, MSG_M2A_EM_WB_ACK, MSG_M2A_EM_MAGICON_ACK, MSG_M2A_NETWORK_STATUS_NOTIFY, MSG_M2A_QUERY_RF_INFO_ACK, MSG_M2A_EM_HAC_ACK, MSG_M2A_EPOF_NOTIFY, MSG_M2A_EM_DYNAMIC_SPH_ACK, MSG_M2A_VIBSPK_PARAMETER_ACK = CCCI_MSG_M2A_BASE + 0x80, MSG_M2A_NXP_SMARTPA_PARAMETER_ACK, MSG_M2A_NW_CODEC_INFO_NOTIFY = CCCI_MSG_M2A_BASE + 0x90, }; } // end namespace android #endif // end of ANDROID_SPEECH_MESSAGE_INTERFACE_H
[ "fetpoh@mail.ru" ]
fetpoh@mail.ru
25c4420440512347527713535c009f1f2b89a182
7b5d700e2a2fed3e2b4ad1132b6bf9cd3877730c
/include/Windows/Controllers/CommandsControllers/FNOFDCommandsTabController.h
88ff6555f4c0c51b02eedb9f14b45ec556bae054
[]
no_license
Megaxela/FRTester
642272511f884cda3a2dcdbe7eccf54b05f2602c
f2cbd4260dc59b9c2b0b1ee1f8207ce663299f8a
refs/heads/master
2021-01-22T19:30:46.127870
2017-05-03T13:55:23
2017-05-03T13:55:23
85,202,766
2
0
null
null
null
null
UTF-8
C++
false
false
1,640
h
// // Created by megaxela on 13.12.16. // #ifndef FRTESTER_FNOFDCOMMANDSTABCONTROLLER_H #define FRTESTER_FNOFDCOMMANDSTABCONTROLLER_H #include <Windows/Controllers/AbstractTabController.h> class CommandsTabController; /** * @brief Класс, контроллирующий вкладку ОФД в виджете из вкладки * ФН в разделе с командами. */ class FNOFDCommandsTabController : public AbstractTabController { public: /** * @brief Конструктор. * @param ptr Указатель на UI. * @param parent Указатель на родительский виджет. */ FNOFDCommandsTabController(Ui::MainWindow *ptr, QWidget *parent); /** * @brief Метод для получения родителя - контроллера команд. * @return Указатель на контроллер. */ CommandsTabController* commandsTabController() const; protected: /** * @brief Метод для настройки соединений. */ void setupConnections() override; /** * @brief Метод для настройки виджетов. */ void configureWidgets() override; private slots: /** * @brief Слот, вызываемый при нажатии на кнопку * получения статуса информационного обмена. */ void onGetExchangeStatus(); private: QString yesNo(int v); QString dateTime(uint8_t day, uint8_t mon, uint8_t year, uint8_t hour, uint8_t min); }; #endif //FRTESTER_FNOFDCOMMANDSTABCONTROLLER_H
[ "xelamegaxela@gmail.com" ]
xelamegaxela@gmail.com
d44fd2f95d8c02363a9be0c68d677835baaae1c0
24004e1c3b8005af26d5890091d3c207427a799e
/Win32/NXOPEN/NXOpen/Issue_IssueList.hxx
2b0fc9a6a78daf9eafd65cade2febcb4ad6024af
[]
no_license
15831944/PHStart
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
f79280bca2ec7e5f344067ead05f98b7d592ae39
refs/heads/master
2022-02-20T04:07:46.994182
2019-09-29T06:15:37
2019-09-29T06:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,190
hxx
#ifndef NXOpen_ISSUE_ISSUELIST_HXX_INCLUDED #define NXOpen_ISSUE_ISSUELIST_HXX_INCLUDED //-------------------------------------------------------------------------- // Header for C++ interface to JA API //-------------------------------------------------------------------------- // // Source File: // Issue_IssueList.ja // // Generated by: // apiwrap // // WARNING: // This file is automatically generated - do not edit by hand // #ifdef _MSC_VER #pragma once #endif #include <NXOpen/NXDeprecation.hxx> #include <vector> #include <NXOpen/NXString.hxx> #include <NXOpen/Callback.hxx> #include <NXOpen/Issue_IssueContent.hxx> #include <NXOpen/Issue_IssueList.hxx> #include <NXOpen/NXObject.hxx> #include <NXOpen/libnxopencpp_issue_exports.hxx> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif namespace NXOpen { namespace Issue { class IssueList; } namespace Issue { class IssueContent; } class NXObject; namespace Issue { class _IssueListBuilder; class IssueListImpl; /** Represents the Issue List object. <br> Created in NX8.5.0. <br> */ class NXOPENCPP_ISSUEEXPORT IssueList : public NXObject { private: IssueListImpl * m_issuelist_impl; private: friend class _IssueListBuilder; protected: IssueList(); public: ~IssueList(); /** Reloads the @link Issue::IssueContent Issue::IssueContent@endlink s <br> Created in NX8.5.0. <br> <br> License requirements : nx_issue_mgmt ("NX Issue Tracking") */ public: void ReloadIssues ( ); /** Returns all the @link Issue::IssueContent Issue::IssueContent@endlink s @return <br> Created in NX8.5.0. <br> <br> License requirements : nx_issue_mgmt ("NX Issue Tracking") */ public: std::vector<NXOpen::Issue::IssueContent *> GetIssues ( ); /** Returns whether the list exists in database @return <br> Created in NX8.5.0. <br> <br> License requirements : nx_issue_mgmt ("NX Issue Tracking") */ public: bool ExistsInDatabase ( ); /** Saves the modified @link Issue::IssueContent Issue::IssueContent@endlink s <br> Created in NX8.5.0. <br> <br> License requirements : nx_issue_mgmt ("NX Issue Tracking") */ public: void SaveChanges ( ); /** Discards the modified @link Issue::IssueContent Issue::IssueContent@endlink s <br> Created in NX8.5.0. <br> <br> License requirements : nx_issue_mgmt ("NX Issue Tracking") */ public: void DiscardChanges ( ); }; } } #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __GNUC__ #ifndef NX_NO_GCC_DEPRECATION_WARNINGS #pragma GCC diagnostic warning "-Wdeprecated-declarations" #endif #endif #undef EXPORTLIBRARY #endif
[ "1075087594@qq.com" ]
1075087594@qq.com
86b197088bbb05066eef80fe9c8422dadf9036b5
28df52f53ddbcee592dc3c149992bebff8593c6b
/c2c/Builder/BuildFileReader.cpp
a7a6a4c677eb739463157e8b4160cb95ce60abf7
[]
no_license
charsyam/c2compiler
3562840daf3f937f36ecdadd079383c53eb5745d
f20158431b40fb1b15944ae14968a561dbdee98b
refs/heads/master
2021-04-15T16:48:44.879290
2018-03-24T08:47:49
2018-03-24T09:20:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,453
cpp
/* Copyright 2013-2018 Bas van den Berg * * 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 "Builder/BuildFileReader.h" #include "Utils/BuildFile.h" #include "FileUtils/TomlReader.h" #include <string.h> #include <stdlib.h> using namespace C2; BuildFileReader::BuildFileReader(BuildFile& build_) : build(build_) { errorMsg[0] = 0; } bool BuildFileReader::parse(const std::string& filename) { TomlReader reader(filename.c_str()); if (!reader.parse()) { strcpy(errorMsg, reader.getErrorMsg()); return false; } const char* target = reader.getValue("target"); build.target = expandEnvVar(filename, target); const char* cc = reader.getValue("toolchain.cc"); build.cc = expandEnvVar(filename, cc); const char* cflags = reader.getValue("toolchain.cflags"); build.cflags = expandEnvVar(filename, cflags); const char* ldflags = reader.getValue("toolchain.ldflags"); build.ldflags = expandEnvVar(filename, ldflags); TomlReader::NodeIter iter = reader.getNodeIter("libdir"); while (!iter.done()) { // dir is required const char* dir = iter.getValue("dir"); if (!dir) { sprintf(errorMsg, "%s: error: missing dir entry in [[libdir]]", filename.c_str()); return false; } const char* expanded = expandEnvVar(filename, dir); if (expanded) build.libDirs.push_back(expanded); iter.next(); } const char* outputDir = reader.getValue("output.dir"); build.outputDir = expandEnvVar(filename, outputDir); return true; } const char* BuildFileReader::expandEnvVar(const std::string& filename, const char* raw) { if (!raw) return ""; if (raw[0] != '$') return raw; const char* expand = getenv(raw + 1); if (!expand) { printf("%s: warning: environment variable '%s' not set\n", filename.c_str(), raw + 1); return ""; } return expand; }
[ "b.van.den.berg.nl@gmail.com" ]
b.van.den.berg.nl@gmail.com
9650e33f463cd85a857c38f86e76ad10d3f78a08
42b011552d5f283dbe9f70ac9bafb1ddf1af91d5
/OpenGL-Test/camera.hpp
b8b8769ed41452e4fc99d47776b287383cdc2cdd
[]
no_license
JDhilon/OpenGL-Test
2b9fe84274d1590cbe27ade459673792bcdda25a
8dbcca49cd40a4f2d4f28957a5eb4d83b5bb504c
refs/heads/master
2020-09-21T07:26:12.894008
2020-01-10T18:19:40
2020-01-10T18:19:40
224,724,143
1
0
null
null
null
null
UTF-8
C++
false
false
1,028
hpp
#pragma once #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <GLFW/glfw3.h> #include "entity.hpp" class Entity; class Camera : public Entity { public: Camera(); Camera(glm::vec3 startPosition, glm::vec3 startUp, GLfloat startYaw, GLfloat startPitch, GLfloat startMoveSpeed, GLfloat startTurnSpeed); void keyControl(bool* keys, GLfloat deltaTime); void mouseControl(GLfloat xChange, GLfloat yChange); glm::vec3 getCameraPosition(); glm::vec3 getCameraDirection(); GLfloat GetYaw() { return yaw; } GLfloat GetPitch() { return pitch; } glm::vec3 GetFront() { return front; } glm::vec3 GetRight() { return right; } glm::vec3 GetUp() { return up; } glm::mat4 calculateViewMatrix(); ~Camera(); private: glm::vec3 position; glm::vec3 front; glm::vec3 up; glm::vec3 right; glm::vec3 worldUp; GLfloat yaw; GLfloat pitch; GLfloat moveSpeed; GLfloat turnSpeed; void update(); };
[ "jashanjotdhilon@gmail.com" ]
jashanjotdhilon@gmail.com
78578d703dec11823c4ce1d7c0b29412e5bfa3c0
5743077502c2ab293905c7533fe9774576773ebe
/src/services/rpc/handlers/Peers.cpp
161d881a015034c69c6d6c51ead9f84f3390f54d
[ "MIT" ]
permissive
hawx1993/truechain-testnet-core
3056b07dc1d39dc9277d1d2960c7c23db39bbf9c
a75edfe83562b3764fb3140144bc41943ebb995a
refs/heads/master
2021-01-24T19:08:55.033847
2018-02-28T06:31:48
2018-02-28T06:31:48
123,239,490
1
0
MIT
2018-02-28T06:21:53
2018-02-28T06:21:53
null
UTF-8
C++
false
false
1,664
cpp
//------------------------------------------------------------------------------ /* This file is part of skywelld: https://github.com/skywell/skywelld Copyright (c) 2012-2014 Skywell 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 <BeastConfig.h> #include <beast/utility/make_lock.h> #include <network/peers/UniqueNodeList.h> #include <network/overlay/Overlay.h> #include <protocol/JsonFields.h> #include <services/rpc/Context.h> #include <common/core/Job.h> #include <main/Application.h> namespace truechain { Json::Value doPeers (RPC::Context& context) { Json::Value jvResult (Json::objectValue); { auto lock = beast::make_lock(getApp().getMasterMutex()); jvResult[jss::peers] = getApp().overlay ().json (); getApp().getUNL().addClusterStatus(jvResult); } return jvResult; } } // truechain
[ "archit@protonmail.ch" ]
archit@protonmail.ch
29d994d2f1ff2e0080e331beb1ab313e7a339f92
0d2b1e0e82c5f191551438fc3318e4b9689b50c5
/Source/OpenGLDrawer/Renderer/PanoramaVideoRenderer.cpp
6e156399234274fa80d593b650dffddf41641152
[]
no_license
rickysung/PhysicsSim
47d5666ba296cd2af6521c729423099df4cf6ef3
29d2d6390afd05a6040cfac3b2f478191448d065
refs/heads/master
2021-01-20T13:26:13.425227
2017-04-01T09:17:53
2017-04-01T09:17:53
82,689,357
0
0
null
null
null
null
UTF-8
C++
false
false
9,550
cpp
/* ============================================================================== PanoramaVideoRenderer.cpp Created: 21 Aug 2016 3:07:40pm Author: Ricky ============================================================================== */ #include "PanoramaVideoRenderer.h" const char* PanoramaVideoRenderer::getVertexShader() { return "#version 330\n" "const float PI = 3.1415926536;\n" "\n" "layout (location = 0) in vec3 position;\n" "layout (location = 1) in vec3 normal;\n" "layout (location = 2) in vec4 sourceColour;\n" "layout (location = 3) in vec2 textureCoordIn;\n" "\n" "uniform mat4 modelMatrix;\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "uniform int nodeType;\n" "uniform int isUniformColour;\n" "uniform vec4 bodyColour;\n" "uniform int modelMode;\n" "uniform float modelScale;\n" "uniform int isVideoMode;\n" "\n" "out vec4 destinationColour;\n" "out vec4 normalvect;\n" "out vec2 UV;\n" "out vec2 labelUV;\n" "\n" "void main()\n" "{\n" " vec4 origin;\n" " vec4 pos;\n" " float diff = 0;\n" " float v = textureCoordIn.x;\n" " float u = textureCoordIn.y;\n" " vec3 aedposition = vec3(PI-2*PI*v, PI*0.5-PI*u, 790);\n" " destinationColour = sourceColour;\n" " if(isUniformColour == 1)\n" " destinationColour = bodyColour;\n" " normalvect = vec4(normal, 1.0);\n" " labelUV = textureCoordIn;\n" " if(isVideoMode==1)\n" " {\n" " UV = (projectionMatrix * inverse(viewMatrix) * vec4(aedposition, 1.0)).xy;\n" " gl_Position = projectionMatrix * vec4(aedposition.xy, 800, 1.0);\n" " }\n" " else\n" " {\n" " origin = viewMatrix * modelMatrix * vec4(0,0,0,1);\n" " if(nodeType==1)\n" " {\n" " if(origin.x<-PI)\n" " diff = 2*PI;\n" " else if(origin.x>PI)\n" " diff = -2*PI;\n" " origin.x += diff;\n" " pos = origin + vec4(modelScale * position, 0);\n" " }\n" " else\n" " {\n" " pos = viewMatrix * vec4(aedposition,1.0);\n" " }\n" " if(modelMode==3)\n" " {\n" " pos = origin + vec4(position * 0.12,0.0) + vec4(0,-0.1,-0.1,0);\n" " }\n" " gl_Position = projectionMatrix * pos;\n" " }\n" "}\n"; } const char* PanoramaVideoRenderer::getFragmentShader() { return "#version 330\n" "layout (location = 0) out vec4 FragColor;\n" "layout (location = 1) out vec4 idValue;\n" "in vec4 destinationColour;\n" "in vec4 normalvect;\n" "in vec2 UV;\n" "in vec2 labelUV;\n" "\n" "uniform int isVideoMode;\n" "uniform vec4 idColour;" "uniform int lineWidth;\n" "uniform int stereoScopicMode;\n" "uniform float nodeIndex;\n" "uniform int modelMode;\n" "uniform float nodeNum;\n" "\n" "uniform sampler2D video;\n" "uniform sampler2D labelTexture;\n" "\n" "void main()\n" "{\n" " vec2 uv = UV;\n" " if(isVideoMode==1)\n" " {\n" " uv.x = (uv.x/2 + 0.5);\n" " uv.y = -uv.y;\n" " uv.y = uv.y/2+0.5;\n" " switch(stereoScopicMode)\n" " {\n" " case 1:\n" " {\n " " uv.x/=2;\n" " if(uv.x>0.5)\n" " uv.x-=0.5;\n" " break;\n" " }\n" " case 2:\n" " {\n " " uv.x/=2;\n" " uv.x+=0.5;\n" " if(uv.x>1)\n" " uv.x-=0.5;\n" " break;\n" " }\n" " case 3:\n" " {\n " " uv.y/=2;\n" " break;\n" " }\n" " case 4:\n" " {\n " " uv.y/=2;\n" " uv.y+=0.5;\n" " break;\n" " }\n" " default:\n" " break;\n" " }\n" " FragColor = vec4(texture(video, uv).rgb, 1.0);\n" " }\n" " else\n" " FragColor = destinationColour;\n" " if(modelMode==3)\n" " {\n" " uv.x = labelUV.x;\n" " uv.y = (nodeNum-1 - nodeIndex + labelUV.y)/nodeNum;\n" " FragColor = vec4(destinationColour.rgb+0.5,1.0) * texture(labelTexture, uv);\n" " if(FragColor.a<0.1)\n" " discard;\n" " }\n" " idValue = idColour;\n" "}"; } Matrix PanoramaVideoRenderer::getViewMatrix(bool isInteractive) { float azi; float elv; float dis; azi = -(getListenerYaw()); elv = 0; dis = 0; Matrix t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, azi, elv, dis, 1); return t; } Matrix PanoramaVideoRenderer::getViewMatrix2() { float azi; float elv; float dis; azi = -(getListenerYaw()); elv = 0; dis = 0; if(azi>0) azi-=2*M_PI; else if(azi<0) azi+=2*M_PI; Matrix t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, azi, elv, dis, 1); return t; } Matrix PanoramaVideoRenderer::getInverseViewMatrix(bool isInteractive) { float azi; float elv; float dis; azi = getListenerYaw(); elv = 0; dis = 0; Matrix t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, azi, elv, dis, 1); return t; } Matrix PanoramaVideoRenderer::getProjectionMatrix() { float n = 0.1; float f = 2000; return Matrix(2/viewAngleHorizon, 0, 0, 0, 0, 2/viewAngleVertical, 0, 0, 0, 0, 2/(f-n), 0, 0, 0, -(f+n)/(f-n), 1); } Matrix PanoramaVideoRenderer::getInverseProjectionMatrix() { float n = 0.1; float f = 2000; return Matrix(viewAngleHorizon/2, 0, 0, 0, 0, viewAngleVertical/2, 0, 0, 0, 0, (f-n)/2, 0, 0, 0, -(f+n)/2, 1); } Matrix PanoramaVideoRenderer::getInverseTransformMatrix() { Matrix v = getInverseViewMatrix(); Matrix p = getInverseProjectionMatrix(); return p * v; } Matrix PanoramaVideoRenderer::getTransformMatrix() { Matrix v = getViewMatrix(); Matrix p = getProjectionMatrix(); return v * p; } PanoramaVideoRenderer::PanoramaVideoRenderer(OpenGLContext& glContext, int screenWidth, int screenHeight, DataModel& nodelist) : PanoramicNodeRenderer(glContext, screenWidth, screenHeight, nodelist), globeShape(glContext, 800), gridShape(glContext, 790, 6) { initializeShader(getVertexShader(), getFragmentShader()); initializeUniformVariables(); videoTexture = createUniform("video"); isVideoMode = createUniform("isVideoMode"); stereoScopicMode = createUniform("stereoScopicMode"); shaderProgram->use(); camAzimuth = 0; camElevation = 0; camDistance = 2000; viewAngleVertical = M_PI; viewAngleHorizon = 2 * M_PI; nodeSize = 0.2; Matrix t = getProjectionMatrix(); projectionMatrix->setMatrix4(t.mat, 1, false); } void PanoramaVideoRenderer::paint() { Matrix t; Matrix u(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); modelMatrix->setMatrix4(u.mat, 1, false); videoTexture->set(0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, inputTexture); if(NodeList.isShowVideo) { isVideoMode->set(1); drawShape(globeShape, NodeType::NONE, Colour(0xFF000000)); isVideoMode->set(0); } if(NodeList.isTrackNameShow) { labelTexture->set(1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, labelTextureID); drawLabels(0.5, 3); } drawAmbisonicController(0.0125f); drawChannelNodes(PANORAMAVIEW_CHANNEL_NODE_SIZE); drawObjectNodes(0.5, 3); if(NodeList.isShowGrid) { drawShape(gridShape, NodeType::NONE, Colour(0xFF000000), Colour(0x11555555)); viewMatrix->setMatrix4(getViewMatrix2().mat, 1, false); drawShape(gridShape, NodeType::NONE, Colour(0xFF000000), Colour(0x11555555)); } } void PanoramaVideoRenderer::draw() { Matrix t; Matrix u(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); float nnum; shaderProgram->use(); glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); OpenGLHelpers::clear (Colour(BACKGROUND_MAIN));// Enable depth test glViewport(0, 0, width, height); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); t = getProjectionMatrix(); projectionMatrix->setMatrix4(t.mat, 1, false); t = getViewMatrix(); for(nnum = 1.0f ; nnum<NodeList.getSize() ; nnum*=2.0f); nodeNum->set(nnum); viewMatrix->setMatrix4(t.mat, 1, false); stereoScopicMode->set(static_cast<int>(NodeList.StereoScopicMode)); paint(); selectNode(); glBindFramebuffer(GL_FRAMEBUFFER, 0); }
[ "ricky@gooddaylab.com" ]
ricky@gooddaylab.com
521a298f957b778df9999a8a1caa689fda3df79f
cc65bff1cce1b6ba38e83585bb9fcb9b0dadfa13
/include/tools/Uuid.h
ca204768fb13689f8333af3f9e673306e3659bb8
[]
no_license
wusidn/Engine
fcd7aa486c93dd3ab1583b9d7cd0b7c5f1faa77b
88b82c3d7e47986d9e1f4eb8c8eef36222f8b1ea
refs/heads/master
2021-01-10T01:18:21.817135
2016-11-18T02:14:04
2016-11-18T02:14:04
49,418,290
0
0
null
null
null
null
UTF-8
C++
false
false
708
h
#pragma once #ifndef __UUID_H__ #define __UUID_H__ #include "Object.h" #include <iostream> #include <string> using namespace std; namespace engine { using namespace core; namespace tools { class Uuid : public Object { public: CREATEFUNC(Uuid); static Uuid & create(const Uuid & _uuid); const string toString(void) const; friend ostream & operator<<(ostream & _out, const Uuid & _uuid); protected: Uuid(); virtual const bool init(void); virtual const bool init(const Uuid & _uuid); private: unsigned short _data[16]; }; } } #endif //__UUID_H__
[ "wusidn@163.com" ]
wusidn@163.com
bf62a708c6541a05568b5e2cc876443cbdacdaad
abba89332f40e792335121fe92d65ece4c8632b6
/lpsolve.h
a9ed1bbacad6b09564eee4fd53b2539de2e56348
[]
no_license
rubenjgarcia/nodesolve
82ba2c5c73b477627eccb48903c3f1310d7c0a47
03482b50129db1e057ef8d20b1a8a761b60ab179
refs/heads/master
2021-01-10T04:29:20.059423
2016-02-19T20:17:18
2016-02-19T20:17:18
52,112,486
1
1
null
null
null
null
UTF-8
C++
false
false
4,099
h
#include <node.h> #include "nan.h" #include "lp_lib.h" using namespace v8; NAN_METHOD(version); NAN_METHOD(makeLP); NAN_METHOD(readLP); Nan::Persistent<Function> constructor; class LPSolve : public node::ObjectWrap { public: static void Init(Handle<Object> exports); private: LPSolve(); ~LPSolve(); static NAN_METHOD(New); static NAN_METHOD(name); static NAN_METHOD(addRowMode); static NAN_METHOD(obj); static NAN_METHOD(objFn); static NAN_METHOD(objFnEx); static NAN_METHOD(objFnStr); static NAN_METHOD(maxim); static NAN_METHOD(binary); static NAN_METHOD(intVar); static NAN_METHOD(resize); static NAN_METHOD(rows); static NAN_METHOD(columns); static NAN_METHOD(rh); static NAN_METHOD(rhRange); static NAN_METHOD(rhVec); static NAN_METHOD(rhVecStr); static NAN_METHOD(constraint); static NAN_METHOD(constraintEx); static NAN_METHOD(constraintStr); static NAN_METHOD(bounds); static NAN_METHOD(upBound); static NAN_METHOD(lowBound); static NAN_METHOD(breakAtFirst); static NAN_METHOD(verbose); static NAN_METHOD(timeout); static NAN_METHOD(solve); static NAN_METHOD(solveSync); static NAN_METHOD(variables); static NAN_METHOD(writeLP); static NAN_METHOD(deleteLP); public: lprec* lp = NULL; }; /* TODO add_column, add_columnex, str_add_column add_lag_con, str_add_lag_con add_SOS column_in_lp copy_lp default_basis del_column del_constraint dualize_lp free_lp get_anti_degen get_basis get_basiscrash get_bb_depthlimit get_bb_floorfirst get_bb_rule get_bounds_tighter get_break_at_value get_col_name, get_origcol_name get_column, get_columnex get_constr_type get_constr_value get_constraints, get_ptr_constraints get_epsb get_epsd get_epsel get_epsint get_epsperturb get_epspivot get_improve get_infinite get_lambda, get_ptr_lambda, get_lambda, get_ptr_lambda get_lp_index get_Lrows get_mat get_max_level, get_max_level get_maxpivot get_mip_gap get_nameindex get_negrange get_nonzeros get_Norig_columns get_Norig_rows get_obj_bound get_objective get_orig_index get_pivoting get_presolve get_presolveloops get_primal_solution, get_ptr_primal_solution, get_var_primalresult get_print_sol get_row, get_rowex get_row_name, get_origrow_name get_scalelimit get_scaling get_sensitivity_obj, get_ptr_sensitivity_obj, get_sensitivity_objex, get_ptr_sensitivity_objex get_sensitivity_rhs, get_ptr_sensitivity_rhs, get_dual_solution, get_ptr_dual_solution, get_var_dualresult get_simplextype get_solutioncount get_solutionlimit get_status get_statustext get_total_iter get_total_nodes get_var_branch get_var_priority, get_var_priority get_variables, get_ptr_variables get_working_objective guess_basis has_BFP has_XLI is_anti_degen is_constr_type is_debug is_feasible is_unbounded is_infinite is_integerscaling is_lag_trace is_nativeBFP is_nativeXLI is_negative is_obj_in_basis is_piv_mode is_piv_rule is_presolve is_scalemode is_scaletype is_semicont is_SOS_var is_trace is_use_names lag_solve print_constraints print_debugdump print_duals print_lp print_objective print_scales print_solution print_str print_tableau put_abortfunc put_bb_branchfunc put_bb_nodefunc put_logfunc put_msgfunc read_basis read_mps, read_freemps, read_MPS, read_freeMPS read_params read_XLI reset_basis reset_params set_anti_degen, get_anti_degen set_basis set_basiscrash set_basisvar set_bb_depthlimit set_bb_floorfirst set_bb_rule set_BFP set_XLI set_bounds_tighter set_break_at_value set_column, set_columnex set_col_name set_constr_type set_debug set_epsb set_epsd set_epsel set_epsint set_epsperturb set_epspivot set_epslevel set_unbounded set_improve set_infinite set_lag_trace set_mat set_maxpivot set_mip_gap set_negrange set_obj_bound set_obj_in_basis set_outputstream, set_outputfile set_pivoting set_preferdual set_presolve set_print_sol set_row, set_rowex set_row_name set_scalelimit set_scaling set_semicont set_sense set_simplextype set_solutionlimit set_trace set_use_names set_var_branch set_var_weights time_elapsed unscale write_basis write_mps, write_freemps, write_MPS, write_freeMPS, MPS_writefileex write_params write_XLI */
[ "rubenjgarciab@gmail.com" ]
rubenjgarciab@gmail.com
260c2488dcd434aadbc9838150c4b73e0b81488b
3cf90d8b9f9a62549162f82586f677041f4afa88
/src/h/Solver_Sparse.h
f73b266c47b09c282a2210e2cd36e6a0b9ae8433
[]
no_license
Automobile-Crash-Lab/stappp
ee19a92d55f8ee04ef0d5039b0844edb58abcb24
ef0bcd27d43437769639d0a2daae4a2dfa454372
refs/heads/master
2021-09-09T08:22:24.594024
2018-03-14T11:10:20
2018-03-14T11:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
h
// // Solver_Sparse.h // stap++ // // Created by six on 2017/12/21. // #ifndef Solver_Sparse_h #define Solver_Sparse_h //#include "SparseMatrix.h" class Solver_Sparse{ public: int n; int*ia,*ja; double *a; double *x; bool fabed; //pardiso needed int nnz; int mtype; /* Real symmetric matrix */ int nrhs; /* Number of right hand sides. */ /* Internal solver memory pointer pt, */ /* 32-bit: int pt[64]; 64-bit: long int pt[64] */ /* or void *pt[64] should be OK on both architectures */ void *pt[64]; /* Pardiso control parameters. */ int iparm[64]; double dparm[64]; int maxfct, mnum, phase, error, msglvl, solver; /* Number of processors. */ int num_procs; /* Auxiliary variables. */ double ddum; /* Double dummy */ int idum; /* Integer dummy. */ //pardiso needed Solver_Sparse(); Solver_Sparse(int,int*,int*,double*); void LDLT(); void BackSubstitution(double* Force); void release(); void solve(double* b); }; #endif /* Solver_Sparse_h */
[ "feiyuxiaothu@gmail.com" ]
feiyuxiaothu@gmail.com
b67f14eac09bbf10b5d7bb58bcfae107a6cd3de8
8b6e2adf0b7fe9a43ca6f8d38d1b13f6e2d16a65
/src/cookie.cc
b7de167e9e2630a14be775ba5c7e8826a5d9dcca
[ "MIT" ]
permissive
aesophor/wmderland
c71532a42e048cace97ef315b074b3b97e936d09
14d72b9c6a3f61dc6fd9c7c0d6dc3e13e9f45ad1
refs/heads/master
2023-06-27T06:42:13.207556
2023-03-19T05:26:02
2023-03-19T05:26:02
158,102,771
235
23
MIT
2021-07-18T11:59:36
2018-11-18T16:20:26
C++
UTF-8
C++
false
false
2,613
cc
// Copyright (c) 2018-2019 Marco Wang <m.aesophor@gmail.com> #include "cookie.h" extern "C" { #include <sys/stat.h> #include <sys/types.h> } #include <sstream> #include <vector> #include "client.h" #include "util.h" #include "log.h" using std::endl; using std::ifstream; using std::ofstream; using std::pair; using std::string; using std::stringstream; using std::unordered_map; using std::vector; namespace wmderland { const char Cookie::kDelimiter_ = ' '; Cookie::Cookie(Display* dpy, Properties* prop, string filename) : dpy_(dpy), prop_(prop), filename_(sys_utils::ToAbsPath(filename)) { // mkdir ~/.cache/wmderland string cookie_dirname = filename_.substr(0, filename_.find_last_of('/')); mode_t cookie_dir_mode = 0755; mkdir(cookie_dirname.c_str(), cookie_dir_mode); WM_LOG(INFO, "Cookie directory: " << cookie_dirname); // Load cookie from file. ifstream fin(filename_); fin >> *this; } Client::Area Cookie::Get(Window window) const { auto it = client_area_map_.find(GetCookieKey(window)); if (it != client_area_map_.end()) { return it->second; } return Client::Area(); } void Cookie::Put(Window window, const Client::Area& area) { client_area_map_[GetCookieKey(window)] = area; // Write cookie to file. ofstream fout(filename_); fout << *this; } string Cookie::GetCookieKey(Window window) const { pair<string, string> hint = wm_utils::GetXClassHint(window); string net_wm_name = wm_utils::GetNetWmName(window); return hint.first + ',' + hint.second + ',' + net_wm_name; } ofstream& operator<<(ofstream& ofs, const Cookie& cookie) { for (auto& area : cookie.client_area_map_) { // Write x, y, width, height, res_class,res_name,net_wm_name to cookie. ofs << area.second.x << Cookie::kDelimiter_ << area.second.y << Cookie::kDelimiter_ << area.second.w << Cookie::kDelimiter_ << area.second.h << Cookie::kDelimiter_ << area.first << endl; } return ofs; } ifstream& operator>>(ifstream& ifs, Cookie& cookie) { string line; while (std::getline(ifs, line)) { string_utils::Strip(line); if (!line.empty()) { vector<string> tokens = string_utils::Split(line, Cookie::kDelimiter_, 4); // The first 4 item is x, y, width, height of a window. Client::Area area; stringstream(tokens[0]) >> area.x; stringstream(tokens[1]) >> area.y; stringstream(tokens[2]) >> area.w; stringstream(tokens[3]) >> area.h; // The rest will be res_class, res_name and _NET_WM_NAME. cookie.client_area_map_[tokens[4]] = area; } } return ifs; } } // namespace wmderland
[ "m.aesophor@gmail.com" ]
m.aesophor@gmail.com
7853622501a760ff1e2af7479cc7ac45acc88c06
1c3b6408476488ddc24623ed03d04e901cb1fb84
/Data Structures/Sparse Table/Sparse Table.cpp
aac5616b27568106dffbe22830dcf8c72f344506
[]
no_license
Sukarnapaul1893/Code-for-Popular-Topics-of-Contest-Programming
cb5c0c82b40b3fd6fe771de28dc040d9241d751f
0522a7203b5a3b49ba852f47e9cf832830964a82
refs/heads/master
2023-07-11T00:27:13.459969
2023-07-01T08:23:07
2023-07-01T08:23:07
162,993,504
0
1
null
2023-07-01T08:23:08
2018-12-24T13:30:15
C++
UTF-8
C++
false
false
1,005
cpp
#include<bits/stdc++.h> using namespace std; const int MAXN = 105000; const int MAXLOG = 20; int n; int logs[MAXN]; void computeLogs(){ logs[1] = 0; for(int i=2;i<=n;i++){ logs[i] = logs[i/2]+1; } } int a[MAXN]; int table[MAXLOG][MAXN]; void buildSparseTable(){ computeLogs(); for(int i=0;i<=logs[n];i++){ int curlen = 1<<i; for(int j=0;j+curlen<=n;j++){ if(curlen==1){ table[i][j]=a[j]; } else{ table[i][j]=min(table[i-1][j],table[i-1][j+curlen/2]); } } } } int getMin(int l, int r){ int p = logs[r-l+1]; int pLen=1<<p; return min(table[p][l], table[p][r-pLen+1]); } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin>>n; for(int i=0;i<n;i++)cin>>a[i]; buildSparseTable(); int q; cin>>q; for(int i=0;i<q;i++){ int l,r; cin>>l>>r; cout<<getMin(l,r)<<"\n"; } }
[ "noreply@github.com" ]
Sukarnapaul1893.noreply@github.com