hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0fd26e8b7fd8ca3719d400e91e25eea84e4ccc21
| 328,888
|
cc
|
C++
|
Protocol/eraftio/raft_cmdpb.pb.cc
|
bokket/eraft
|
3a2f9a0cae671cfdaf929719d1e34b113dc063e2
|
[
"MIT"
] | 58
|
2021-05-20T12:56:54.000Z
|
2022-03-28T03:45:25.000Z
|
Protocol/eraftio/raft_cmdpb.pb.cc
|
bokket/eraft
|
3a2f9a0cae671cfdaf929719d1e34b113dc063e2
|
[
"MIT"
] | 1
|
2022-01-25T04:40:20.000Z
|
2022-01-28T05:43:30.000Z
|
Protocol/eraftio/raft_cmdpb.pb.cc
|
bokket/eraft
|
3a2f9a0cae671cfdaf929719d1e34b113dc063e2
|
[
"MIT"
] | 15
|
2021-05-20T12:56:57.000Z
|
2022-03-14T20:35:58.000Z
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: raft_cmdpb.proto
#include "raft_cmdpb.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_errorpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<6> scc_info_Error_errorpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_metapb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Peer_metapb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_metapb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_Region_metapb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_metapb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_RegionEpoch_metapb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_AdminRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_AdminResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CompactLogRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CompactLogResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PutRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PutResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Request_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Response_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SnapRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SnapResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SplitRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SplitResponse_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_raft_5fcmdpb_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto;
namespace raft_cmdpb {
class GetRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GetRequest> _instance;
} _GetRequest_default_instance_;
class GetResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GetResponse> _instance;
} _GetResponse_default_instance_;
class PutRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<PutRequest> _instance;
} _PutRequest_default_instance_;
class PutResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<PutResponse> _instance;
} _PutResponse_default_instance_;
class DeleteRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<DeleteRequest> _instance;
} _DeleteRequest_default_instance_;
class DeleteResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<DeleteResponse> _instance;
} _DeleteResponse_default_instance_;
class SnapRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SnapRequest> _instance;
} _SnapRequest_default_instance_;
class SnapResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SnapResponse> _instance;
} _SnapResponse_default_instance_;
class RequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Request> _instance;
} _Request_default_instance_;
class ResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Response> _instance;
} _Response_default_instance_;
class ChangePeerRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ChangePeerRequest> _instance;
} _ChangePeerRequest_default_instance_;
class ChangePeerResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ChangePeerResponse> _instance;
} _ChangePeerResponse_default_instance_;
class SplitRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SplitRequest> _instance;
} _SplitRequest_default_instance_;
class SplitResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<SplitResponse> _instance;
} _SplitResponse_default_instance_;
class CompactLogRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CompactLogRequest> _instance;
} _CompactLogRequest_default_instance_;
class CompactLogResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CompactLogResponse> _instance;
} _CompactLogResponse_default_instance_;
class TransferLeaderRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TransferLeaderRequest> _instance;
} _TransferLeaderRequest_default_instance_;
class TransferLeaderResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TransferLeaderResponse> _instance;
} _TransferLeaderResponse_default_instance_;
class AdminRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<AdminRequest> _instance;
} _AdminRequest_default_instance_;
class AdminResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<AdminResponse> _instance;
} _AdminResponse_default_instance_;
class RaftRequestHeaderDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<RaftRequestHeader> _instance;
} _RaftRequestHeader_default_instance_;
class RaftResponseHeaderDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<RaftResponseHeader> _instance;
} _RaftResponseHeader_default_instance_;
class RaftCmdRequestDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<RaftCmdRequest> _instance;
} _RaftCmdRequest_default_instance_;
class RaftCmdResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<RaftCmdResponse> _instance;
} _RaftCmdResponse_default_instance_;
} // namespace raft_cmdpb
static void InitDefaultsscc_info_AdminRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_AdminRequest_default_instance_;
new (ptr) ::raft_cmdpb::AdminRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::AdminRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_AdminRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsscc_info_AdminRequest_raft_5fcmdpb_2eproto}, {
&scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto.base,
&scc_info_CompactLogRequest_raft_5fcmdpb_2eproto.base,
&scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto.base,
&scc_info_SplitRequest_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_AdminResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_AdminResponse_default_instance_;
new (ptr) ::raft_cmdpb::AdminResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::AdminResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_AdminResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsscc_info_AdminResponse_raft_5fcmdpb_2eproto}, {
&scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto.base,
&scc_info_CompactLogResponse_raft_5fcmdpb_2eproto.base,
&scc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto.base,
&scc_info_SplitResponse_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_ChangePeerRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_ChangePeerRequest_default_instance_;
new (ptr) ::raft_cmdpb::ChangePeerRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::ChangePeerRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_ChangePeerRequest_raft_5fcmdpb_2eproto}, {
&scc_info_Peer_metapb_2eproto.base,}};
static void InitDefaultsscc_info_ChangePeerResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_ChangePeerResponse_default_instance_;
new (ptr) ::raft_cmdpb::ChangePeerResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::ChangePeerResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_ChangePeerResponse_raft_5fcmdpb_2eproto}, {
&scc_info_Region_metapb_2eproto.base,}};
static void InitDefaultsscc_info_CompactLogRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_CompactLogRequest_default_instance_;
new (ptr) ::raft_cmdpb::CompactLogRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::CompactLogRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CompactLogRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_CompactLogRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_CompactLogResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_CompactLogResponse_default_instance_;
new (ptr) ::raft_cmdpb::CompactLogResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::CompactLogResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CompactLogResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_CompactLogResponse_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_DeleteRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_DeleteRequest_default_instance_;
new (ptr) ::raft_cmdpb::DeleteRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::DeleteRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_DeleteRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_DeleteResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_DeleteResponse_default_instance_;
new (ptr) ::raft_cmdpb::DeleteResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::DeleteResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_DeleteResponse_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_GetRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_GetRequest_default_instance_;
new (ptr) ::raft_cmdpb::GetRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::GetRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_GetRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_GetResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_GetResponse_default_instance_;
new (ptr) ::raft_cmdpb::GetResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::GetResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_GetResponse_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_PutRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_PutRequest_default_instance_;
new (ptr) ::raft_cmdpb::PutRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::PutRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PutRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_PutRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_PutResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_PutResponse_default_instance_;
new (ptr) ::raft_cmdpb::PutResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::PutResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PutResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_PutResponse_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_RaftCmdRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_RaftCmdRequest_default_instance_;
new (ptr) ::raft_cmdpb::RaftCmdRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::RaftCmdRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_RaftCmdRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsscc_info_RaftCmdRequest_raft_5fcmdpb_2eproto}, {
&scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto.base,
&scc_info_Request_raft_5fcmdpb_2eproto.base,
&scc_info_AdminRequest_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_RaftCmdResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_RaftCmdResponse_default_instance_;
new (ptr) ::raft_cmdpb::RaftCmdResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::RaftCmdResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_RaftCmdResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsscc_info_RaftCmdResponse_raft_5fcmdpb_2eproto}, {
&scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto.base,
&scc_info_Response_raft_5fcmdpb_2eproto.base,
&scc_info_AdminResponse_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_RaftRequestHeader_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_RaftRequestHeader_default_instance_;
new (ptr) ::raft_cmdpb::RaftRequestHeader();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::RaftRequestHeader::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsscc_info_RaftRequestHeader_raft_5fcmdpb_2eproto}, {
&scc_info_Peer_metapb_2eproto.base,
&scc_info_RegionEpoch_metapb_2eproto.base,}};
static void InitDefaultsscc_info_RaftResponseHeader_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_RaftResponseHeader_default_instance_;
new (ptr) ::raft_cmdpb::RaftResponseHeader();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::RaftResponseHeader::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_RaftResponseHeader_raft_5fcmdpb_2eproto}, {
&scc_info_Error_errorpb_2eproto.base,}};
static void InitDefaultsscc_info_Request_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_Request_default_instance_;
new (ptr) ::raft_cmdpb::Request();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::Request::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Request_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsscc_info_Request_raft_5fcmdpb_2eproto}, {
&scc_info_GetRequest_raft_5fcmdpb_2eproto.base,
&scc_info_PutRequest_raft_5fcmdpb_2eproto.base,
&scc_info_DeleteRequest_raft_5fcmdpb_2eproto.base,
&scc_info_SnapRequest_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_Response_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_Response_default_instance_;
new (ptr) ::raft_cmdpb::Response();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::Response::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Response_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsscc_info_Response_raft_5fcmdpb_2eproto}, {
&scc_info_GetResponse_raft_5fcmdpb_2eproto.base,
&scc_info_PutResponse_raft_5fcmdpb_2eproto.base,
&scc_info_DeleteResponse_raft_5fcmdpb_2eproto.base,
&scc_info_SnapResponse_raft_5fcmdpb_2eproto.base,}};
static void InitDefaultsscc_info_SnapRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_SnapRequest_default_instance_;
new (ptr) ::raft_cmdpb::SnapRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::SnapRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SnapRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_SnapRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_SnapResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_SnapResponse_default_instance_;
new (ptr) ::raft_cmdpb::SnapResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::SnapResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SnapResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_SnapResponse_raft_5fcmdpb_2eproto}, {
&scc_info_Region_metapb_2eproto.base,}};
static void InitDefaultsscc_info_SplitRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_SplitRequest_default_instance_;
new (ptr) ::raft_cmdpb::SplitRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::SplitRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_SplitRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_SplitRequest_raft_5fcmdpb_2eproto}, {}};
static void InitDefaultsscc_info_SplitResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_SplitResponse_default_instance_;
new (ptr) ::raft_cmdpb::SplitResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::SplitResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_SplitResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_SplitResponse_raft_5fcmdpb_2eproto}, {
&scc_info_Region_metapb_2eproto.base,}};
static void InitDefaultsscc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_TransferLeaderRequest_default_instance_;
new (ptr) ::raft_cmdpb::TransferLeaderRequest();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::TransferLeaderRequest::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto}, {
&scc_info_Peer_metapb_2eproto.base,}};
static void InitDefaultsscc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::raft_cmdpb::_TransferLeaderResponse_default_instance_;
new (ptr) ::raft_cmdpb::TransferLeaderResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::raft_cmdpb::TransferLeaderResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_raft_5fcmdpb_2eproto[24];
static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_raft_5fcmdpb_2eproto[2];
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_raft_5fcmdpb_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_raft_5fcmdpb_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::GetRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::GetRequest, cf_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::GetRequest, key_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::GetResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::GetResponse, value_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::PutRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::PutRequest, cf_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::PutRequest, key_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::PutRequest, value_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::PutResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::DeleteRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::DeleteRequest, cf_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::DeleteRequest, key_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::DeleteResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SnapRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SnapResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SnapResponse, region_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, cmd_type_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, get_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, put_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, delete__),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Request, snap_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, cmd_type_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, get_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, put_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, delete__),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::Response, snap_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::ChangePeerRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::ChangePeerRequest, change_type_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::ChangePeerRequest, peer_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::ChangePeerResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::ChangePeerResponse, region_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitRequest, split_key_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitRequest, new_region_id_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitRequest, new_peer_ids_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::SplitResponse, regions_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::CompactLogRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::CompactLogRequest, compact_index_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::CompactLogRequest, compact_term_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::CompactLogResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::TransferLeaderRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::TransferLeaderRequest, peer_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::TransferLeaderResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, cmd_type_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, change_peer_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, compact_log_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, transfer_leader_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminRequest, split_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, cmd_type_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, change_peer_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, compact_log_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, transfer_leader_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::AdminResponse, split_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftRequestHeader, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftRequestHeader, region_id_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftRequestHeader, peer_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftRequestHeader, region_epoch_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftRequestHeader, term_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftResponseHeader, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftResponseHeader, error_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftResponseHeader, uuid_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftResponseHeader, current_term_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdRequest, header_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdRequest, requests_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdRequest, admin_request_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdResponse, header_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdResponse, responses_),
PROTOBUF_FIELD_OFFSET(::raft_cmdpb::RaftCmdResponse, admin_response_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::raft_cmdpb::GetRequest)},
{ 7, -1, sizeof(::raft_cmdpb::GetResponse)},
{ 13, -1, sizeof(::raft_cmdpb::PutRequest)},
{ 21, -1, sizeof(::raft_cmdpb::PutResponse)},
{ 26, -1, sizeof(::raft_cmdpb::DeleteRequest)},
{ 33, -1, sizeof(::raft_cmdpb::DeleteResponse)},
{ 38, -1, sizeof(::raft_cmdpb::SnapRequest)},
{ 43, -1, sizeof(::raft_cmdpb::SnapResponse)},
{ 49, -1, sizeof(::raft_cmdpb::Request)},
{ 59, -1, sizeof(::raft_cmdpb::Response)},
{ 69, -1, sizeof(::raft_cmdpb::ChangePeerRequest)},
{ 76, -1, sizeof(::raft_cmdpb::ChangePeerResponse)},
{ 82, -1, sizeof(::raft_cmdpb::SplitRequest)},
{ 90, -1, sizeof(::raft_cmdpb::SplitResponse)},
{ 96, -1, sizeof(::raft_cmdpb::CompactLogRequest)},
{ 103, -1, sizeof(::raft_cmdpb::CompactLogResponse)},
{ 108, -1, sizeof(::raft_cmdpb::TransferLeaderRequest)},
{ 114, -1, sizeof(::raft_cmdpb::TransferLeaderResponse)},
{ 119, -1, sizeof(::raft_cmdpb::AdminRequest)},
{ 129, -1, sizeof(::raft_cmdpb::AdminResponse)},
{ 139, -1, sizeof(::raft_cmdpb::RaftRequestHeader)},
{ 148, -1, sizeof(::raft_cmdpb::RaftResponseHeader)},
{ 156, -1, sizeof(::raft_cmdpb::RaftCmdRequest)},
{ 164, -1, sizeof(::raft_cmdpb::RaftCmdResponse)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_GetRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_GetResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_PutRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_PutResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_DeleteRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_DeleteResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_SnapRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_SnapResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_Request_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_Response_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_ChangePeerRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_ChangePeerResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_SplitRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_SplitResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_CompactLogRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_CompactLogResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_TransferLeaderRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_TransferLeaderResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_AdminRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_AdminResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_RaftRequestHeader_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_RaftResponseHeader_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_RaftCmdRequest_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::raft_cmdpb::_RaftCmdResponse_default_instance_),
};
const char descriptor_table_protodef_raft_5fcmdpb_2eproto[] =
"\n\020raft_cmdpb.proto\022\nraft_cmdpb\032\014metapb.p"
"roto\032\rerrorpb.proto\032\reraftpb.proto\"%\n\nGe"
"tRequest\022\n\n\002cf\030\001 \001(\t\022\013\n\003key\030\002 \001(\014\"\034\n\013Get"
"Response\022\r\n\005value\030\001 \001(\014\"4\n\nPutRequest\022\n\n"
"\002cf\030\001 \001(\t\022\013\n\003key\030\002 \001(\014\022\r\n\005value\030\003 \001(\014\"\r\n"
"\013PutResponse\"(\n\rDeleteRequest\022\n\n\002cf\030\001 \001("
"\t\022\013\n\003key\030\002 \001(\014\"\020\n\016DeleteResponse\"\r\n\013Snap"
"Request\".\n\014SnapResponse\022\036\n\006region\030\001 \001(\0132"
"\016.metapb.Region\"\314\001\n\007Request\022%\n\010cmd_type\030"
"\001 \001(\0162\023.raft_cmdpb.CmdType\022#\n\003get\030\002 \001(\0132"
"\026.raft_cmdpb.GetRequest\022#\n\003put\030\004 \001(\0132\026.r"
"aft_cmdpb.PutRequest\022)\n\006delete\030\005 \001(\0132\031.r"
"aft_cmdpb.DeleteRequest\022%\n\004snap\030\006 \001(\0132\027."
"raft_cmdpb.SnapRequest\"\321\001\n\010Response\022%\n\010c"
"md_type\030\001 \001(\0162\023.raft_cmdpb.CmdType\022$\n\003ge"
"t\030\002 \001(\0132\027.raft_cmdpb.GetResponse\022$\n\003put\030"
"\004 \001(\0132\027.raft_cmdpb.PutResponse\022*\n\006delete"
"\030\005 \001(\0132\032.raft_cmdpb.DeleteResponse\022&\n\004sn"
"ap\030\006 \001(\0132\030.raft_cmdpb.SnapResponse\"]\n\021Ch"
"angePeerRequest\022,\n\013change_type\030\001 \001(\0162\027.e"
"raftpb.ConfChangeType\022\032\n\004peer\030\002 \001(\0132\014.me"
"tapb.Peer\"4\n\022ChangePeerResponse\022\036\n\006regio"
"n\030\001 \001(\0132\016.metapb.Region\"N\n\014SplitRequest\022"
"\021\n\tsplit_key\030\001 \001(\014\022\025\n\rnew_region_id\030\002 \001("
"\004\022\024\n\014new_peer_ids\030\003 \003(\004\"0\n\rSplitResponse"
"\022\037\n\007regions\030\001 \003(\0132\016.metapb.Region\"@\n\021Com"
"pactLogRequest\022\025\n\rcompact_index\030\001 \001(\004\022\024\n"
"\014compact_term\030\002 \001(\004\"\024\n\022CompactLogRespons"
"e\"3\n\025TransferLeaderRequest\022\032\n\004peer\030\001 \001(\013"
"2\014.metapb.Peer\"\030\n\026TransferLeaderResponse"
"\"\207\002\n\014AdminRequest\022*\n\010cmd_type\030\001 \001(\0162\030.ra"
"ft_cmdpb.AdminCmdType\0222\n\013change_peer\030\002 \001"
"(\0132\035.raft_cmdpb.ChangePeerRequest\0222\n\013com"
"pact_log\030\004 \001(\0132\035.raft_cmdpb.CompactLogRe"
"quest\022:\n\017transfer_leader\030\005 \001(\0132!.raft_cm"
"dpb.TransferLeaderRequest\022\'\n\005split\030\n \001(\013"
"2\030.raft_cmdpb.SplitRequest\"\214\002\n\rAdminResp"
"onse\022*\n\010cmd_type\030\001 \001(\0162\030.raft_cmdpb.Admi"
"nCmdType\0223\n\013change_peer\030\002 \001(\0132\036.raft_cmd"
"pb.ChangePeerResponse\0223\n\013compact_log\030\004 \001"
"(\0132\036.raft_cmdpb.CompactLogResponse\022;\n\017tr"
"ansfer_leader\030\005 \001(\0132\".raft_cmdpb.Transfe"
"rLeaderResponse\022(\n\005split\030\n \001(\0132\031.raft_cm"
"dpb.SplitResponse\"{\n\021RaftRequestHeader\022\021"
"\n\tregion_id\030\001 \001(\004\022\032\n\004peer\030\002 \001(\0132\014.metapb"
".Peer\022)\n\014region_epoch\030\004 \001(\0132\023.metapb.Reg"
"ionEpoch\022\014\n\004term\030\005 \001(\004\"W\n\022RaftResponseHe"
"ader\022\035\n\005error\030\001 \001(\0132\016.errorpb.Error\022\014\n\004u"
"uid\030\002 \001(\014\022\024\n\014current_term\030\003 \001(\004\"\227\001\n\016Raft"
"CmdRequest\022-\n\006header\030\001 \001(\0132\035.raft_cmdpb."
"RaftRequestHeader\022%\n\010requests\030\002 \003(\0132\023.ra"
"ft_cmdpb.Request\022/\n\radmin_request\030\003 \001(\0132"
"\030.raft_cmdpb.AdminRequest\"\235\001\n\017RaftCmdRes"
"ponse\022.\n\006header\030\001 \001(\0132\036.raft_cmdpb.RaftR"
"esponseHeader\022\'\n\tresponses\030\002 \003(\0132\024.raft_"
"cmdpb.Response\0221\n\016admin_response\030\003 \001(\0132\031"
".raft_cmdpb.AdminResponse*>\n\007CmdType\022\013\n\007"
"Invalid\020\000\022\007\n\003Get\020\001\022\007\n\003Put\020\003\022\n\n\006Delete\020\004\022"
"\010\n\004Snap\020\005*_\n\014AdminCmdType\022\020\n\014InvalidAdmi"
"n\020\000\022\016\n\nChangePeer\020\001\022\016\n\nCompactLog\020\003\022\022\n\016T"
"ransferLeader\020\004\022\t\n\005Split\020\nb\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_raft_5fcmdpb_2eproto_deps[3] = {
&::descriptor_table_eraftpb_2eproto,
&::descriptor_table_errorpb_2eproto,
&::descriptor_table_metapb_2eproto,
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_raft_5fcmdpb_2eproto_sccs[24] = {
&scc_info_AdminRequest_raft_5fcmdpb_2eproto.base,
&scc_info_AdminResponse_raft_5fcmdpb_2eproto.base,
&scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto.base,
&scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto.base,
&scc_info_CompactLogRequest_raft_5fcmdpb_2eproto.base,
&scc_info_CompactLogResponse_raft_5fcmdpb_2eproto.base,
&scc_info_DeleteRequest_raft_5fcmdpb_2eproto.base,
&scc_info_DeleteResponse_raft_5fcmdpb_2eproto.base,
&scc_info_GetRequest_raft_5fcmdpb_2eproto.base,
&scc_info_GetResponse_raft_5fcmdpb_2eproto.base,
&scc_info_PutRequest_raft_5fcmdpb_2eproto.base,
&scc_info_PutResponse_raft_5fcmdpb_2eproto.base,
&scc_info_RaftCmdRequest_raft_5fcmdpb_2eproto.base,
&scc_info_RaftCmdResponse_raft_5fcmdpb_2eproto.base,
&scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto.base,
&scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto.base,
&scc_info_Request_raft_5fcmdpb_2eproto.base,
&scc_info_Response_raft_5fcmdpb_2eproto.base,
&scc_info_SnapRequest_raft_5fcmdpb_2eproto.base,
&scc_info_SnapResponse_raft_5fcmdpb_2eproto.base,
&scc_info_SplitRequest_raft_5fcmdpb_2eproto.base,
&scc_info_SplitResponse_raft_5fcmdpb_2eproto.base,
&scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto.base,
&scc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_raft_5fcmdpb_2eproto_once;
static bool descriptor_table_raft_5fcmdpb_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_raft_5fcmdpb_2eproto = {
&descriptor_table_raft_5fcmdpb_2eproto_initialized, descriptor_table_protodef_raft_5fcmdpb_2eproto, "raft_cmdpb.proto", 2434,
&descriptor_table_raft_5fcmdpb_2eproto_once, descriptor_table_raft_5fcmdpb_2eproto_sccs, descriptor_table_raft_5fcmdpb_2eproto_deps, 24, 3,
schemas, file_default_instances, TableStruct_raft_5fcmdpb_2eproto::offsets,
file_level_metadata_raft_5fcmdpb_2eproto, 24, file_level_enum_descriptors_raft_5fcmdpb_2eproto, file_level_service_descriptors_raft_5fcmdpb_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_raft_5fcmdpb_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_raft_5fcmdpb_2eproto), true);
namespace raft_cmdpb {
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CmdType_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_raft_5fcmdpb_2eproto);
return file_level_enum_descriptors_raft_5fcmdpb_2eproto[0];
}
bool CmdType_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 3:
case 4:
case 5:
return true;
default:
return false;
}
}
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* AdminCmdType_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_raft_5fcmdpb_2eproto);
return file_level_enum_descriptors_raft_5fcmdpb_2eproto[1];
}
bool AdminCmdType_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 3:
case 4:
case 10:
return true;
default:
return false;
}
}
// ===================================================================
void GetRequest::InitAsDefaultInstance() {
}
class GetRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GetRequest::kCfFieldNumber;
const int GetRequest::kKeyFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GetRequest::GetRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.GetRequest)
}
GetRequest::GetRequest(const GetRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.GetRequest)
}
void GetRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_GetRequest_raft_5fcmdpb_2eproto.base);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
GetRequest::~GetRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.GetRequest)
SharedDtor();
}
void GetRequest::SharedDtor() {
cf_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void GetRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const GetRequest& GetRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GetRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void GetRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.GetRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cf_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* GetRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// string cf = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_cf(), ptr, ctx, "raft_cmdpb.GetRequest.cf");
CHK_(ptr);
} else goto handle_unusual;
continue;
// bytes key = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_key(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool GetRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.GetRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string cf = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_cf()));
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"raft_cmdpb.GetRequest.cf"));
} else {
goto handle_unusual;
}
break;
}
// bytes key = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_key()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.GetRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.GetRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void GetRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.GetRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.GetRequest.cf");
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->cf(), output);
}
// bytes key = 2;
if (this->key().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->key(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.GetRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* GetRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.GetRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.GetRequest.cf");
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
1, this->cf(), target);
}
// bytes key = 2;
if (this->key().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
2, this->key(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.GetRequest)
return target;
}
size_t GetRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.GetRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->cf());
}
// bytes key = 2;
if (this->key().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->key());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void GetRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.GetRequest)
GOOGLE_DCHECK_NE(&from, this);
const GetRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GetRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.GetRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.GetRequest)
MergeFrom(*source);
}
}
void GetRequest::MergeFrom(const GetRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.GetRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
}
void GetRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.GetRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GetRequest::CopyFrom(const GetRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.GetRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GetRequest::IsInitialized() const {
return true;
}
void GetRequest::Swap(GetRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void GetRequest::InternalSwap(GetRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
cf_.Swap(&other->cf_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
key_.Swap(&other->key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::PROTOBUF_NAMESPACE_ID::Metadata GetRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void GetResponse::InitAsDefaultInstance() {
}
class GetResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GetResponse::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GetResponse::GetResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.GetResponse)
}
GetResponse::GetResponse(const GetResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.GetResponse)
}
void GetResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_GetResponse_raft_5fcmdpb_2eproto.base);
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
GetResponse::~GetResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.GetResponse)
SharedDtor();
}
void GetResponse::SharedDtor() {
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void GetResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const GetResponse& GetResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GetResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void GetResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.GetResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* GetResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// bytes value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_value(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool GetResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.GetResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes value = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.GetResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.GetResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void GetResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.GetResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->value(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.GetResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* GetResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.GetResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
1, this->value(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.GetResponse)
return target;
}
size_t GetResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.GetResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bytes value = 1;
if (this->value().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->value());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void GetResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.GetResponse)
GOOGLE_DCHECK_NE(&from, this);
const GetResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GetResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.GetResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.GetResponse)
MergeFrom(*source);
}
}
void GetResponse::MergeFrom(const GetResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.GetResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.value().size() > 0) {
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
}
void GetResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.GetResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GetResponse::CopyFrom(const GetResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.GetResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GetResponse::IsInitialized() const {
return true;
}
void GetResponse::Swap(GetResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void GetResponse::InternalSwap(GetResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::PROTOBUF_NAMESPACE_ID::Metadata GetResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void PutRequest::InitAsDefaultInstance() {
}
class PutRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int PutRequest::kCfFieldNumber;
const int PutRequest::kKeyFieldNumber;
const int PutRequest::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PutRequest::PutRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.PutRequest)
}
PutRequest::PutRequest(const PutRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.value().size() > 0) {
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.PutRequest)
}
void PutRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_PutRequest_raft_5fcmdpb_2eproto.base);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
PutRequest::~PutRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.PutRequest)
SharedDtor();
}
void PutRequest::SharedDtor() {
cf_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void PutRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const PutRequest& PutRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_PutRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void PutRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.PutRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cf_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* PutRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// string cf = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_cf(), ptr, ctx, "raft_cmdpb.PutRequest.cf");
CHK_(ptr);
} else goto handle_unusual;
continue;
// bytes key = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_key(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// bytes value = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_value(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool PutRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.PutRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string cf = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_cf()));
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"raft_cmdpb.PutRequest.cf"));
} else {
goto handle_unusual;
}
break;
}
// bytes key = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_key()));
} else {
goto handle_unusual;
}
break;
}
// bytes value = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.PutRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.PutRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void PutRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.PutRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.PutRequest.cf");
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->cf(), output);
}
// bytes key = 2;
if (this->key().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->key(), output);
}
// bytes value = 3;
if (this->value().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
3, this->value(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.PutRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* PutRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.PutRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.PutRequest.cf");
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
1, this->cf(), target);
}
// bytes key = 2;
if (this->key().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
2, this->key(), target);
}
// bytes value = 3;
if (this->value().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
3, this->value(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.PutRequest)
return target;
}
size_t PutRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.PutRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->cf());
}
// bytes key = 2;
if (this->key().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->key());
}
// bytes value = 3;
if (this->value().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->value());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void PutRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.PutRequest)
GOOGLE_DCHECK_NE(&from, this);
const PutRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<PutRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.PutRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.PutRequest)
MergeFrom(*source);
}
}
void PutRequest::MergeFrom(const PutRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.PutRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
if (from.value().size() > 0) {
value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
}
}
void PutRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.PutRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PutRequest::CopyFrom(const PutRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.PutRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PutRequest::IsInitialized() const {
return true;
}
void PutRequest::Swap(PutRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void PutRequest::InternalSwap(PutRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
cf_.Swap(&other->cf_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
key_.Swap(&other->key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::PROTOBUF_NAMESPACE_ID::Metadata PutRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void PutResponse::InitAsDefaultInstance() {
}
class PutResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PutResponse::PutResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.PutResponse)
}
PutResponse::PutResponse(const PutResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.PutResponse)
}
void PutResponse::SharedCtor() {
}
PutResponse::~PutResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.PutResponse)
SharedDtor();
}
void PutResponse::SharedDtor() {
}
void PutResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const PutResponse& PutResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_PutResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void PutResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.PutResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* PutResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool PutResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.PutResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.PutResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.PutResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void PutResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.PutResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.PutResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* PutResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.PutResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.PutResponse)
return target;
}
size_t PutResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.PutResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void PutResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.PutResponse)
GOOGLE_DCHECK_NE(&from, this);
const PutResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<PutResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.PutResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.PutResponse)
MergeFrom(*source);
}
}
void PutResponse::MergeFrom(const PutResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.PutResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void PutResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.PutResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PutResponse::CopyFrom(const PutResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.PutResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PutResponse::IsInitialized() const {
return true;
}
void PutResponse::Swap(PutResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void PutResponse::InternalSwap(PutResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata PutResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void DeleteRequest::InitAsDefaultInstance() {
}
class DeleteRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DeleteRequest::kCfFieldNumber;
const int DeleteRequest::kKeyFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DeleteRequest::DeleteRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.DeleteRequest)
}
DeleteRequest::DeleteRequest(const DeleteRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.DeleteRequest)
}
void DeleteRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_DeleteRequest_raft_5fcmdpb_2eproto.base);
cf_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
DeleteRequest::~DeleteRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.DeleteRequest)
SharedDtor();
}
void DeleteRequest::SharedDtor() {
cf_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void DeleteRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const DeleteRequest& DeleteRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DeleteRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void DeleteRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.DeleteRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cf_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
key_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* DeleteRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// string cf = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_cf(), ptr, ctx, "raft_cmdpb.DeleteRequest.cf");
CHK_(ptr);
} else goto handle_unusual;
continue;
// bytes key = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_key(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DeleteRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.DeleteRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string cf = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_cf()));
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"raft_cmdpb.DeleteRequest.cf"));
} else {
goto handle_unusual;
}
break;
}
// bytes key = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_key()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.DeleteRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.DeleteRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DeleteRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.DeleteRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.DeleteRequest.cf");
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->cf(), output);
}
// bytes key = 2;
if (this->key().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->key(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.DeleteRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* DeleteRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.DeleteRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->cf().data(), static_cast<int>(this->cf().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"raft_cmdpb.DeleteRequest.cf");
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
1, this->cf(), target);
}
// bytes key = 2;
if (this->key().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
2, this->key(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.DeleteRequest)
return target;
}
size_t DeleteRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.DeleteRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string cf = 1;
if (this->cf().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->cf());
}
// bytes key = 2;
if (this->key().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->key());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void DeleteRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.DeleteRequest)
GOOGLE_DCHECK_NE(&from, this);
const DeleteRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<DeleteRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.DeleteRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.DeleteRequest)
MergeFrom(*source);
}
}
void DeleteRequest::MergeFrom(const DeleteRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.DeleteRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.cf().size() > 0) {
cf_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.cf_);
}
if (from.key().size() > 0) {
key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.key_);
}
}
void DeleteRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.DeleteRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DeleteRequest::CopyFrom(const DeleteRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.DeleteRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DeleteRequest::IsInitialized() const {
return true;
}
void DeleteRequest::Swap(DeleteRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void DeleteRequest::InternalSwap(DeleteRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
cf_.Swap(&other->cf_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
key_.Swap(&other->key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::PROTOBUF_NAMESPACE_ID::Metadata DeleteRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void DeleteResponse::InitAsDefaultInstance() {
}
class DeleteResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DeleteResponse::DeleteResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.DeleteResponse)
}
DeleteResponse::DeleteResponse(const DeleteResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.DeleteResponse)
}
void DeleteResponse::SharedCtor() {
}
DeleteResponse::~DeleteResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.DeleteResponse)
SharedDtor();
}
void DeleteResponse::SharedDtor() {
}
void DeleteResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const DeleteResponse& DeleteResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DeleteResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void DeleteResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.DeleteResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* DeleteResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DeleteResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.DeleteResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.DeleteResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.DeleteResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DeleteResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.DeleteResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.DeleteResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* DeleteResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.DeleteResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.DeleteResponse)
return target;
}
size_t DeleteResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.DeleteResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void DeleteResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.DeleteResponse)
GOOGLE_DCHECK_NE(&from, this);
const DeleteResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<DeleteResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.DeleteResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.DeleteResponse)
MergeFrom(*source);
}
}
void DeleteResponse::MergeFrom(const DeleteResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.DeleteResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void DeleteResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.DeleteResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DeleteResponse::CopyFrom(const DeleteResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.DeleteResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DeleteResponse::IsInitialized() const {
return true;
}
void DeleteResponse::Swap(DeleteResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void DeleteResponse::InternalSwap(DeleteResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata DeleteResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void SnapRequest::InitAsDefaultInstance() {
}
class SnapRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SnapRequest::SnapRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.SnapRequest)
}
SnapRequest::SnapRequest(const SnapRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.SnapRequest)
}
void SnapRequest::SharedCtor() {
}
SnapRequest::~SnapRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.SnapRequest)
SharedDtor();
}
void SnapRequest::SharedDtor() {
}
void SnapRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const SnapRequest& SnapRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SnapRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void SnapRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.SnapRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* SnapRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SnapRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.SnapRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.SnapRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.SnapRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SnapRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.SnapRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.SnapRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* SnapRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.SnapRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.SnapRequest)
return target;
}
size_t SnapRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.SnapRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void SnapRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.SnapRequest)
GOOGLE_DCHECK_NE(&from, this);
const SnapRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SnapRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.SnapRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.SnapRequest)
MergeFrom(*source);
}
}
void SnapRequest::MergeFrom(const SnapRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.SnapRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void SnapRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.SnapRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SnapRequest::CopyFrom(const SnapRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.SnapRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SnapRequest::IsInitialized() const {
return true;
}
void SnapRequest::Swap(SnapRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void SnapRequest::InternalSwap(SnapRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SnapRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void SnapResponse::InitAsDefaultInstance() {
::raft_cmdpb::_SnapResponse_default_instance_._instance.get_mutable()->region_ = const_cast< ::metapb::Region*>(
::metapb::Region::internal_default_instance());
}
class SnapResponse::HasBitSetters {
public:
static const ::metapb::Region& region(const SnapResponse* msg);
};
const ::metapb::Region&
SnapResponse::HasBitSetters::region(const SnapResponse* msg) {
return *msg->region_;
}
void SnapResponse::clear_region() {
if (GetArenaNoVirtual() == nullptr && region_ != nullptr) {
delete region_;
}
region_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SnapResponse::kRegionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SnapResponse::SnapResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.SnapResponse)
}
SnapResponse::SnapResponse(const SnapResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_region()) {
region_ = new ::metapb::Region(*from.region_);
} else {
region_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.SnapResponse)
}
void SnapResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SnapResponse_raft_5fcmdpb_2eproto.base);
region_ = nullptr;
}
SnapResponse::~SnapResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.SnapResponse)
SharedDtor();
}
void SnapResponse::SharedDtor() {
if (this != internal_default_instance()) delete region_;
}
void SnapResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const SnapResponse& SnapResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SnapResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void SnapResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.SnapResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && region_ != nullptr) {
delete region_;
}
region_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* SnapResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .metapb.Region region = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_region(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SnapResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.SnapResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .metapb.Region region = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_region()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.SnapResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.SnapResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SnapResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.SnapResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::region(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.SnapResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* SnapResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.SnapResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::region(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.SnapResponse)
return target;
}
size_t SnapResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.SnapResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*region_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void SnapResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.SnapResponse)
GOOGLE_DCHECK_NE(&from, this);
const SnapResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SnapResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.SnapResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.SnapResponse)
MergeFrom(*source);
}
}
void SnapResponse::MergeFrom(const SnapResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.SnapResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_region()) {
mutable_region()->::metapb::Region::MergeFrom(from.region());
}
}
void SnapResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.SnapResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SnapResponse::CopyFrom(const SnapResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.SnapResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SnapResponse::IsInitialized() const {
return true;
}
void SnapResponse::Swap(SnapResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void SnapResponse::InternalSwap(SnapResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(region_, other->region_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SnapResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void Request::InitAsDefaultInstance() {
::raft_cmdpb::_Request_default_instance_._instance.get_mutable()->get_ = const_cast< ::raft_cmdpb::GetRequest*>(
::raft_cmdpb::GetRequest::internal_default_instance());
::raft_cmdpb::_Request_default_instance_._instance.get_mutable()->put_ = const_cast< ::raft_cmdpb::PutRequest*>(
::raft_cmdpb::PutRequest::internal_default_instance());
::raft_cmdpb::_Request_default_instance_._instance.get_mutable()->delete__ = const_cast< ::raft_cmdpb::DeleteRequest*>(
::raft_cmdpb::DeleteRequest::internal_default_instance());
::raft_cmdpb::_Request_default_instance_._instance.get_mutable()->snap_ = const_cast< ::raft_cmdpb::SnapRequest*>(
::raft_cmdpb::SnapRequest::internal_default_instance());
}
class Request::HasBitSetters {
public:
static const ::raft_cmdpb::GetRequest& get(const Request* msg);
static const ::raft_cmdpb::PutRequest& put(const Request* msg);
static const ::raft_cmdpb::DeleteRequest& delete_(const Request* msg);
static const ::raft_cmdpb::SnapRequest& snap(const Request* msg);
};
const ::raft_cmdpb::GetRequest&
Request::HasBitSetters::get(const Request* msg) {
return *msg->get_;
}
const ::raft_cmdpb::PutRequest&
Request::HasBitSetters::put(const Request* msg) {
return *msg->put_;
}
const ::raft_cmdpb::DeleteRequest&
Request::HasBitSetters::delete_(const Request* msg) {
return *msg->delete__;
}
const ::raft_cmdpb::SnapRequest&
Request::HasBitSetters::snap(const Request* msg) {
return *msg->snap_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Request::kCmdTypeFieldNumber;
const int Request::kGetFieldNumber;
const int Request::kPutFieldNumber;
const int Request::kDeleteFieldNumber;
const int Request::kSnapFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Request::Request()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.Request)
}
Request::Request(const Request& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_get()) {
get_ = new ::raft_cmdpb::GetRequest(*from.get_);
} else {
get_ = nullptr;
}
if (from.has_put()) {
put_ = new ::raft_cmdpb::PutRequest(*from.put_);
} else {
put_ = nullptr;
}
if (from.has_delete_()) {
delete__ = new ::raft_cmdpb::DeleteRequest(*from.delete__);
} else {
delete__ = nullptr;
}
if (from.has_snap()) {
snap_ = new ::raft_cmdpb::SnapRequest(*from.snap_);
} else {
snap_ = nullptr;
}
cmd_type_ = from.cmd_type_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.Request)
}
void Request::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Request_raft_5fcmdpb_2eproto.base);
::memset(&get_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&cmd_type_) -
reinterpret_cast<char*>(&get_)) + sizeof(cmd_type_));
}
Request::~Request() {
// @@protoc_insertion_point(destructor:raft_cmdpb.Request)
SharedDtor();
}
void Request::SharedDtor() {
if (this != internal_default_instance()) delete get_;
if (this != internal_default_instance()) delete put_;
if (this != internal_default_instance()) delete delete__;
if (this != internal_default_instance()) delete snap_;
}
void Request::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Request& Request::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Request_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void Request::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.Request)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && get_ != nullptr) {
delete get_;
}
get_ = nullptr;
if (GetArenaNoVirtual() == nullptr && put_ != nullptr) {
delete put_;
}
put_ = nullptr;
if (GetArenaNoVirtual() == nullptr && delete__ != nullptr) {
delete delete__;
}
delete__ = nullptr;
if (GetArenaNoVirtual() == nullptr && snap_ != nullptr) {
delete snap_;
}
snap_ = nullptr;
cmd_type_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Request::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.CmdType cmd_type = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_cmd_type(static_cast<::raft_cmdpb::CmdType>(val));
} else goto handle_unusual;
continue;
// .raft_cmdpb.GetRequest get = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_get(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.PutRequest put = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ctx->ParseMessage(mutable_put(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.DeleteRequest delete = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
ptr = ctx->ParseMessage(mutable_delete_(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.SnapRequest snap = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) {
ptr = ctx->ParseMessage(mutable_snap(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Request::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.Request)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.CmdType cmd_type = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_cmd_type(static_cast< ::raft_cmdpb::CmdType >(value));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.GetRequest get = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_get()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.PutRequest put = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_put()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.DeleteRequest delete = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_delete_()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.SnapRequest snap = 6;
case 6: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_snap()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.Request)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.Request)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Request::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.Request)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
1, this->cmd_type(), output);
}
// .raft_cmdpb.GetRequest get = 2;
if (this->has_get()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::get(this), output);
}
// .raft_cmdpb.PutRequest put = 4;
if (this->has_put()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::put(this), output);
}
// .raft_cmdpb.DeleteRequest delete = 5;
if (this->has_delete_()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::delete_(this), output);
}
// .raft_cmdpb.SnapRequest snap = 6;
if (this->has_snap()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
6, HasBitSetters::snap(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.Request)
}
::PROTOBUF_NAMESPACE_ID::uint8* Request::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.Request)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->cmd_type(), target);
}
// .raft_cmdpb.GetRequest get = 2;
if (this->has_get()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::get(this), target);
}
// .raft_cmdpb.PutRequest put = 4;
if (this->has_put()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::put(this), target);
}
// .raft_cmdpb.DeleteRequest delete = 5;
if (this->has_delete_()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::delete_(this), target);
}
// .raft_cmdpb.SnapRequest snap = 6;
if (this->has_snap()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
6, HasBitSetters::snap(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.Request)
return target;
}
size_t Request::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.Request)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .raft_cmdpb.GetRequest get = 2;
if (this->has_get()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*get_);
}
// .raft_cmdpb.PutRequest put = 4;
if (this->has_put()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*put_);
}
// .raft_cmdpb.DeleteRequest delete = 5;
if (this->has_delete_()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*delete__);
}
// .raft_cmdpb.SnapRequest snap = 6;
if (this->has_snap()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*snap_);
}
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->cmd_type());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Request::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.Request)
GOOGLE_DCHECK_NE(&from, this);
const Request* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Request>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.Request)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.Request)
MergeFrom(*source);
}
}
void Request::MergeFrom(const Request& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.Request)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_get()) {
mutable_get()->::raft_cmdpb::GetRequest::MergeFrom(from.get());
}
if (from.has_put()) {
mutable_put()->::raft_cmdpb::PutRequest::MergeFrom(from.put());
}
if (from.has_delete_()) {
mutable_delete_()->::raft_cmdpb::DeleteRequest::MergeFrom(from.delete_());
}
if (from.has_snap()) {
mutable_snap()->::raft_cmdpb::SnapRequest::MergeFrom(from.snap());
}
if (from.cmd_type() != 0) {
set_cmd_type(from.cmd_type());
}
}
void Request::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.Request)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Request::CopyFrom(const Request& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.Request)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Request::IsInitialized() const {
return true;
}
void Request::Swap(Request* other) {
if (other == this) return;
InternalSwap(other);
}
void Request::InternalSwap(Request* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(get_, other->get_);
swap(put_, other->put_);
swap(delete__, other->delete__);
swap(snap_, other->snap_);
swap(cmd_type_, other->cmd_type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Request::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void Response::InitAsDefaultInstance() {
::raft_cmdpb::_Response_default_instance_._instance.get_mutable()->get_ = const_cast< ::raft_cmdpb::GetResponse*>(
::raft_cmdpb::GetResponse::internal_default_instance());
::raft_cmdpb::_Response_default_instance_._instance.get_mutable()->put_ = const_cast< ::raft_cmdpb::PutResponse*>(
::raft_cmdpb::PutResponse::internal_default_instance());
::raft_cmdpb::_Response_default_instance_._instance.get_mutable()->delete__ = const_cast< ::raft_cmdpb::DeleteResponse*>(
::raft_cmdpb::DeleteResponse::internal_default_instance());
::raft_cmdpb::_Response_default_instance_._instance.get_mutable()->snap_ = const_cast< ::raft_cmdpb::SnapResponse*>(
::raft_cmdpb::SnapResponse::internal_default_instance());
}
class Response::HasBitSetters {
public:
static const ::raft_cmdpb::GetResponse& get(const Response* msg);
static const ::raft_cmdpb::PutResponse& put(const Response* msg);
static const ::raft_cmdpb::DeleteResponse& delete_(const Response* msg);
static const ::raft_cmdpb::SnapResponse& snap(const Response* msg);
};
const ::raft_cmdpb::GetResponse&
Response::HasBitSetters::get(const Response* msg) {
return *msg->get_;
}
const ::raft_cmdpb::PutResponse&
Response::HasBitSetters::put(const Response* msg) {
return *msg->put_;
}
const ::raft_cmdpb::DeleteResponse&
Response::HasBitSetters::delete_(const Response* msg) {
return *msg->delete__;
}
const ::raft_cmdpb::SnapResponse&
Response::HasBitSetters::snap(const Response* msg) {
return *msg->snap_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Response::kCmdTypeFieldNumber;
const int Response::kGetFieldNumber;
const int Response::kPutFieldNumber;
const int Response::kDeleteFieldNumber;
const int Response::kSnapFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Response::Response()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.Response)
}
Response::Response(const Response& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_get()) {
get_ = new ::raft_cmdpb::GetResponse(*from.get_);
} else {
get_ = nullptr;
}
if (from.has_put()) {
put_ = new ::raft_cmdpb::PutResponse(*from.put_);
} else {
put_ = nullptr;
}
if (from.has_delete_()) {
delete__ = new ::raft_cmdpb::DeleteResponse(*from.delete__);
} else {
delete__ = nullptr;
}
if (from.has_snap()) {
snap_ = new ::raft_cmdpb::SnapResponse(*from.snap_);
} else {
snap_ = nullptr;
}
cmd_type_ = from.cmd_type_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.Response)
}
void Response::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Response_raft_5fcmdpb_2eproto.base);
::memset(&get_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&cmd_type_) -
reinterpret_cast<char*>(&get_)) + sizeof(cmd_type_));
}
Response::~Response() {
// @@protoc_insertion_point(destructor:raft_cmdpb.Response)
SharedDtor();
}
void Response::SharedDtor() {
if (this != internal_default_instance()) delete get_;
if (this != internal_default_instance()) delete put_;
if (this != internal_default_instance()) delete delete__;
if (this != internal_default_instance()) delete snap_;
}
void Response::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Response& Response::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Response_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void Response::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.Response)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && get_ != nullptr) {
delete get_;
}
get_ = nullptr;
if (GetArenaNoVirtual() == nullptr && put_ != nullptr) {
delete put_;
}
put_ = nullptr;
if (GetArenaNoVirtual() == nullptr && delete__ != nullptr) {
delete delete__;
}
delete__ = nullptr;
if (GetArenaNoVirtual() == nullptr && snap_ != nullptr) {
delete snap_;
}
snap_ = nullptr;
cmd_type_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Response::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.CmdType cmd_type = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_cmd_type(static_cast<::raft_cmdpb::CmdType>(val));
} else goto handle_unusual;
continue;
// .raft_cmdpb.GetResponse get = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_get(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.PutResponse put = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ctx->ParseMessage(mutable_put(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.DeleteResponse delete = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
ptr = ctx->ParseMessage(mutable_delete_(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.SnapResponse snap = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) {
ptr = ctx->ParseMessage(mutable_snap(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Response::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.Response)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.CmdType cmd_type = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_cmd_type(static_cast< ::raft_cmdpb::CmdType >(value));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.GetResponse get = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_get()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.PutResponse put = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_put()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.DeleteResponse delete = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_delete_()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.SnapResponse snap = 6;
case 6: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (50 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_snap()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.Response)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.Response)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Response::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.Response)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
1, this->cmd_type(), output);
}
// .raft_cmdpb.GetResponse get = 2;
if (this->has_get()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::get(this), output);
}
// .raft_cmdpb.PutResponse put = 4;
if (this->has_put()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::put(this), output);
}
// .raft_cmdpb.DeleteResponse delete = 5;
if (this->has_delete_()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::delete_(this), output);
}
// .raft_cmdpb.SnapResponse snap = 6;
if (this->has_snap()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
6, HasBitSetters::snap(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.Response)
}
::PROTOBUF_NAMESPACE_ID::uint8* Response::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.Response)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->cmd_type(), target);
}
// .raft_cmdpb.GetResponse get = 2;
if (this->has_get()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::get(this), target);
}
// .raft_cmdpb.PutResponse put = 4;
if (this->has_put()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::put(this), target);
}
// .raft_cmdpb.DeleteResponse delete = 5;
if (this->has_delete_()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::delete_(this), target);
}
// .raft_cmdpb.SnapResponse snap = 6;
if (this->has_snap()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
6, HasBitSetters::snap(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.Response)
return target;
}
size_t Response::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.Response)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .raft_cmdpb.GetResponse get = 2;
if (this->has_get()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*get_);
}
// .raft_cmdpb.PutResponse put = 4;
if (this->has_put()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*put_);
}
// .raft_cmdpb.DeleteResponse delete = 5;
if (this->has_delete_()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*delete__);
}
// .raft_cmdpb.SnapResponse snap = 6;
if (this->has_snap()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*snap_);
}
// .raft_cmdpb.CmdType cmd_type = 1;
if (this->cmd_type() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->cmd_type());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Response::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.Response)
GOOGLE_DCHECK_NE(&from, this);
const Response* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Response>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.Response)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.Response)
MergeFrom(*source);
}
}
void Response::MergeFrom(const Response& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.Response)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_get()) {
mutable_get()->::raft_cmdpb::GetResponse::MergeFrom(from.get());
}
if (from.has_put()) {
mutable_put()->::raft_cmdpb::PutResponse::MergeFrom(from.put());
}
if (from.has_delete_()) {
mutable_delete_()->::raft_cmdpb::DeleteResponse::MergeFrom(from.delete_());
}
if (from.has_snap()) {
mutable_snap()->::raft_cmdpb::SnapResponse::MergeFrom(from.snap());
}
if (from.cmd_type() != 0) {
set_cmd_type(from.cmd_type());
}
}
void Response::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.Response)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Response::CopyFrom(const Response& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.Response)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Response::IsInitialized() const {
return true;
}
void Response::Swap(Response* other) {
if (other == this) return;
InternalSwap(other);
}
void Response::InternalSwap(Response* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(get_, other->get_);
swap(put_, other->put_);
swap(delete__, other->delete__);
swap(snap_, other->snap_);
swap(cmd_type_, other->cmd_type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Response::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void ChangePeerRequest::InitAsDefaultInstance() {
::raft_cmdpb::_ChangePeerRequest_default_instance_._instance.get_mutable()->peer_ = const_cast< ::metapb::Peer*>(
::metapb::Peer::internal_default_instance());
}
class ChangePeerRequest::HasBitSetters {
public:
static const ::metapb::Peer& peer(const ChangePeerRequest* msg);
};
const ::metapb::Peer&
ChangePeerRequest::HasBitSetters::peer(const ChangePeerRequest* msg) {
return *msg->peer_;
}
void ChangePeerRequest::clear_peer() {
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ChangePeerRequest::kChangeTypeFieldNumber;
const int ChangePeerRequest::kPeerFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ChangePeerRequest::ChangePeerRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.ChangePeerRequest)
}
ChangePeerRequest::ChangePeerRequest(const ChangePeerRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_peer()) {
peer_ = new ::metapb::Peer(*from.peer_);
} else {
peer_ = nullptr;
}
change_type_ = from.change_type_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.ChangePeerRequest)
}
void ChangePeerRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto.base);
::memset(&peer_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&change_type_) -
reinterpret_cast<char*>(&peer_)) + sizeof(change_type_));
}
ChangePeerRequest::~ChangePeerRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.ChangePeerRequest)
SharedDtor();
}
void ChangePeerRequest::SharedDtor() {
if (this != internal_default_instance()) delete peer_;
}
void ChangePeerRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ChangePeerRequest& ChangePeerRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ChangePeerRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void ChangePeerRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.ChangePeerRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
change_type_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ChangePeerRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .eraftpb.ConfChangeType change_type = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_change_type(static_cast<::eraftpb::ConfChangeType>(val));
} else goto handle_unusual;
continue;
// .metapb.Peer peer = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_peer(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ChangePeerRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.ChangePeerRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .eraftpb.ConfChangeType change_type = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_change_type(static_cast< ::eraftpb::ConfChangeType >(value));
} else {
goto handle_unusual;
}
break;
}
// .metapb.Peer peer = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_peer()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.ChangePeerRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.ChangePeerRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ChangePeerRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.ChangePeerRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .eraftpb.ConfChangeType change_type = 1;
if (this->change_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
1, this->change_type(), output);
}
// .metapb.Peer peer = 2;
if (this->has_peer()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::peer(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.ChangePeerRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* ChangePeerRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.ChangePeerRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .eraftpb.ConfChangeType change_type = 1;
if (this->change_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->change_type(), target);
}
// .metapb.Peer peer = 2;
if (this->has_peer()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::peer(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.ChangePeerRequest)
return target;
}
size_t ChangePeerRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.ChangePeerRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .metapb.Peer peer = 2;
if (this->has_peer()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*peer_);
}
// .eraftpb.ConfChangeType change_type = 1;
if (this->change_type() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->change_type());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ChangePeerRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.ChangePeerRequest)
GOOGLE_DCHECK_NE(&from, this);
const ChangePeerRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ChangePeerRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.ChangePeerRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.ChangePeerRequest)
MergeFrom(*source);
}
}
void ChangePeerRequest::MergeFrom(const ChangePeerRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.ChangePeerRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_peer()) {
mutable_peer()->::metapb::Peer::MergeFrom(from.peer());
}
if (from.change_type() != 0) {
set_change_type(from.change_type());
}
}
void ChangePeerRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.ChangePeerRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ChangePeerRequest::CopyFrom(const ChangePeerRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.ChangePeerRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ChangePeerRequest::IsInitialized() const {
return true;
}
void ChangePeerRequest::Swap(ChangePeerRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void ChangePeerRequest::InternalSwap(ChangePeerRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(peer_, other->peer_);
swap(change_type_, other->change_type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata ChangePeerRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void ChangePeerResponse::InitAsDefaultInstance() {
::raft_cmdpb::_ChangePeerResponse_default_instance_._instance.get_mutable()->region_ = const_cast< ::metapb::Region*>(
::metapb::Region::internal_default_instance());
}
class ChangePeerResponse::HasBitSetters {
public:
static const ::metapb::Region& region(const ChangePeerResponse* msg);
};
const ::metapb::Region&
ChangePeerResponse::HasBitSetters::region(const ChangePeerResponse* msg) {
return *msg->region_;
}
void ChangePeerResponse::clear_region() {
if (GetArenaNoVirtual() == nullptr && region_ != nullptr) {
delete region_;
}
region_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ChangePeerResponse::kRegionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ChangePeerResponse::ChangePeerResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.ChangePeerResponse)
}
ChangePeerResponse::ChangePeerResponse(const ChangePeerResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_region()) {
region_ = new ::metapb::Region(*from.region_);
} else {
region_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.ChangePeerResponse)
}
void ChangePeerResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto.base);
region_ = nullptr;
}
ChangePeerResponse::~ChangePeerResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.ChangePeerResponse)
SharedDtor();
}
void ChangePeerResponse::SharedDtor() {
if (this != internal_default_instance()) delete region_;
}
void ChangePeerResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ChangePeerResponse& ChangePeerResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ChangePeerResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void ChangePeerResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.ChangePeerResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && region_ != nullptr) {
delete region_;
}
region_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ChangePeerResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .metapb.Region region = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_region(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ChangePeerResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.ChangePeerResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .metapb.Region region = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_region()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.ChangePeerResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.ChangePeerResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ChangePeerResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.ChangePeerResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::region(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.ChangePeerResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* ChangePeerResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.ChangePeerResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::region(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.ChangePeerResponse)
return target;
}
size_t ChangePeerResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.ChangePeerResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .metapb.Region region = 1;
if (this->has_region()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*region_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ChangePeerResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.ChangePeerResponse)
GOOGLE_DCHECK_NE(&from, this);
const ChangePeerResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ChangePeerResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.ChangePeerResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.ChangePeerResponse)
MergeFrom(*source);
}
}
void ChangePeerResponse::MergeFrom(const ChangePeerResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.ChangePeerResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_region()) {
mutable_region()->::metapb::Region::MergeFrom(from.region());
}
}
void ChangePeerResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.ChangePeerResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ChangePeerResponse::CopyFrom(const ChangePeerResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.ChangePeerResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ChangePeerResponse::IsInitialized() const {
return true;
}
void ChangePeerResponse::Swap(ChangePeerResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void ChangePeerResponse::InternalSwap(ChangePeerResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(region_, other->region_);
}
::PROTOBUF_NAMESPACE_ID::Metadata ChangePeerResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void SplitRequest::InitAsDefaultInstance() {
}
class SplitRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SplitRequest::kSplitKeyFieldNumber;
const int SplitRequest::kNewRegionIdFieldNumber;
const int SplitRequest::kNewPeerIdsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SplitRequest::SplitRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.SplitRequest)
}
SplitRequest::SplitRequest(const SplitRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
new_peer_ids_(from.new_peer_ids_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
split_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.split_key().size() > 0) {
split_key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.split_key_);
}
new_region_id_ = from.new_region_id_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.SplitRequest)
}
void SplitRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SplitRequest_raft_5fcmdpb_2eproto.base);
split_key_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
new_region_id_ = PROTOBUF_ULONGLONG(0);
}
SplitRequest::~SplitRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.SplitRequest)
SharedDtor();
}
void SplitRequest::SharedDtor() {
split_key_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void SplitRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const SplitRequest& SplitRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SplitRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void SplitRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.SplitRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
new_peer_ids_.Clear();
split_key_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
new_region_id_ = PROTOBUF_ULONGLONG(0);
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* SplitRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// bytes split_key = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_split_key(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint64 new_region_id = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
new_region_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated uint64 new_peer_ids = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt64Parser(mutable_new_peer_ids(), ptr, ctx);
CHK_(ptr);
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) {
add_new_peer_ids(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SplitRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.SplitRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes split_key = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_split_key()));
} else {
goto handle_unusual;
}
break;
}
// uint64 new_region_id = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, &new_region_id_)));
} else {
goto handle_unusual;
}
break;
}
// repeated uint64 new_peer_ids = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, this->mutable_new_peer_ids())));
} else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
1, 26u, input, this->mutable_new_peer_ids())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.SplitRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.SplitRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SplitRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.SplitRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes split_key = 1;
if (this->split_key().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->split_key(), output);
}
// uint64 new_region_id = 2;
if (this->new_region_id() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(2, this->new_region_id(), output);
}
// repeated uint64 new_peer_ids = 3;
if (this->new_peer_ids_size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(3, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_new_peer_ids_cached_byte_size_.load(
std::memory_order_relaxed));
}
for (int i = 0, n = this->new_peer_ids_size(); i < n; i++) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64NoTag(
this->new_peer_ids(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.SplitRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* SplitRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.SplitRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes split_key = 1;
if (this->split_key().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
1, this->split_key(), target);
}
// uint64 new_region_id = 2;
if (this->new_region_id() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(2, this->new_region_id(), target);
}
// repeated uint64 new_peer_ids = 3;
if (this->new_peer_ids_size() > 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray(
3,
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray(
_new_peer_ids_cached_byte_size_.load(std::memory_order_relaxed),
target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
WriteUInt64NoTagToArray(this->new_peer_ids_, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.SplitRequest)
return target;
}
size_t SplitRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.SplitRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated uint64 new_peer_ids = 3;
{
size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
UInt64Size(this->new_peer_ids_);
if (data_size > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size));
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size);
_new_peer_ids_cached_byte_size_.store(cached_size,
std::memory_order_relaxed);
total_size += data_size;
}
// bytes split_key = 1;
if (this->split_key().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->split_key());
}
// uint64 new_region_id = 2;
if (this->new_region_id() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->new_region_id());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void SplitRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.SplitRequest)
GOOGLE_DCHECK_NE(&from, this);
const SplitRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SplitRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.SplitRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.SplitRequest)
MergeFrom(*source);
}
}
void SplitRequest::MergeFrom(const SplitRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.SplitRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
new_peer_ids_.MergeFrom(from.new_peer_ids_);
if (from.split_key().size() > 0) {
split_key_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.split_key_);
}
if (from.new_region_id() != 0) {
set_new_region_id(from.new_region_id());
}
}
void SplitRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.SplitRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SplitRequest::CopyFrom(const SplitRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.SplitRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SplitRequest::IsInitialized() const {
return true;
}
void SplitRequest::Swap(SplitRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void SplitRequest::InternalSwap(SplitRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
new_peer_ids_.InternalSwap(&other->new_peer_ids_);
split_key_.Swap(&other->split_key_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(new_region_id_, other->new_region_id_);
}
::PROTOBUF_NAMESPACE_ID::Metadata SplitRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void SplitResponse::InitAsDefaultInstance() {
}
class SplitResponse::HasBitSetters {
public:
};
void SplitResponse::clear_regions() {
regions_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SplitResponse::kRegionsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SplitResponse::SplitResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.SplitResponse)
}
SplitResponse::SplitResponse(const SplitResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
regions_(from.regions_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.SplitResponse)
}
void SplitResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_SplitResponse_raft_5fcmdpb_2eproto.base);
}
SplitResponse::~SplitResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.SplitResponse)
SharedDtor();
}
void SplitResponse::SharedDtor() {
}
void SplitResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const SplitResponse& SplitResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_SplitResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void SplitResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.SplitResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
regions_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* SplitResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated .metapb.Region regions = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(add_regions(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 10);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SplitResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.SplitResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .metapb.Region regions = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, add_regions()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.SplitResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.SplitResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SplitResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.SplitResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .metapb.Region regions = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->regions_size()); i < n; i++) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->regions(static_cast<int>(i)),
output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.SplitResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* SplitResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.SplitResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .metapb.Region regions = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->regions_size()); i < n; i++) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->regions(static_cast<int>(i)), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.SplitResponse)
return target;
}
size_t SplitResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.SplitResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .metapb.Region regions = 1;
{
unsigned int count = static_cast<unsigned int>(this->regions_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
this->regions(static_cast<int>(i)));
}
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void SplitResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.SplitResponse)
GOOGLE_DCHECK_NE(&from, this);
const SplitResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<SplitResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.SplitResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.SplitResponse)
MergeFrom(*source);
}
}
void SplitResponse::MergeFrom(const SplitResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.SplitResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
regions_.MergeFrom(from.regions_);
}
void SplitResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.SplitResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SplitResponse::CopyFrom(const SplitResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.SplitResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SplitResponse::IsInitialized() const {
return true;
}
void SplitResponse::Swap(SplitResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void SplitResponse::InternalSwap(SplitResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(®ions_)->InternalSwap(CastToBase(&other->regions_));
}
::PROTOBUF_NAMESPACE_ID::Metadata SplitResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void CompactLogRequest::InitAsDefaultInstance() {
}
class CompactLogRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CompactLogRequest::kCompactIndexFieldNumber;
const int CompactLogRequest::kCompactTermFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CompactLogRequest::CompactLogRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.CompactLogRequest)
}
CompactLogRequest::CompactLogRequest(const CompactLogRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&compact_index_, &from.compact_index_,
static_cast<size_t>(reinterpret_cast<char*>(&compact_term_) -
reinterpret_cast<char*>(&compact_index_)) + sizeof(compact_term_));
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.CompactLogRequest)
}
void CompactLogRequest::SharedCtor() {
::memset(&compact_index_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&compact_term_) -
reinterpret_cast<char*>(&compact_index_)) + sizeof(compact_term_));
}
CompactLogRequest::~CompactLogRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.CompactLogRequest)
SharedDtor();
}
void CompactLogRequest::SharedDtor() {
}
void CompactLogRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CompactLogRequest& CompactLogRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CompactLogRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void CompactLogRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.CompactLogRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&compact_index_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&compact_term_) -
reinterpret_cast<char*>(&compact_index_)) + sizeof(compact_term_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* CompactLogRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// uint64 compact_index = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
compact_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint64 compact_term = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
compact_term_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CompactLogRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.CompactLogRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint64 compact_index = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, &compact_index_)));
} else {
goto handle_unusual;
}
break;
}
// uint64 compact_term = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, &compact_term_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.CompactLogRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.CompactLogRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CompactLogRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.CompactLogRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 compact_index = 1;
if (this->compact_index() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(1, this->compact_index(), output);
}
// uint64 compact_term = 2;
if (this->compact_term() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(2, this->compact_term(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.CompactLogRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* CompactLogRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.CompactLogRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 compact_index = 1;
if (this->compact_index() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->compact_index(), target);
}
// uint64 compact_term = 2;
if (this->compact_term() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(2, this->compact_term(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.CompactLogRequest)
return target;
}
size_t CompactLogRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.CompactLogRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// uint64 compact_index = 1;
if (this->compact_index() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->compact_index());
}
// uint64 compact_term = 2;
if (this->compact_term() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->compact_term());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CompactLogRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.CompactLogRequest)
GOOGLE_DCHECK_NE(&from, this);
const CompactLogRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CompactLogRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.CompactLogRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.CompactLogRequest)
MergeFrom(*source);
}
}
void CompactLogRequest::MergeFrom(const CompactLogRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.CompactLogRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.compact_index() != 0) {
set_compact_index(from.compact_index());
}
if (from.compact_term() != 0) {
set_compact_term(from.compact_term());
}
}
void CompactLogRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.CompactLogRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CompactLogRequest::CopyFrom(const CompactLogRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.CompactLogRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CompactLogRequest::IsInitialized() const {
return true;
}
void CompactLogRequest::Swap(CompactLogRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void CompactLogRequest::InternalSwap(CompactLogRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(compact_index_, other->compact_index_);
swap(compact_term_, other->compact_term_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CompactLogRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void CompactLogResponse::InitAsDefaultInstance() {
}
class CompactLogResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CompactLogResponse::CompactLogResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.CompactLogResponse)
}
CompactLogResponse::CompactLogResponse(const CompactLogResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.CompactLogResponse)
}
void CompactLogResponse::SharedCtor() {
}
CompactLogResponse::~CompactLogResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.CompactLogResponse)
SharedDtor();
}
void CompactLogResponse::SharedDtor() {
}
void CompactLogResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CompactLogResponse& CompactLogResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CompactLogResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void CompactLogResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.CompactLogResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* CompactLogResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CompactLogResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.CompactLogResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.CompactLogResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.CompactLogResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CompactLogResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.CompactLogResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.CompactLogResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* CompactLogResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.CompactLogResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.CompactLogResponse)
return target;
}
size_t CompactLogResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.CompactLogResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CompactLogResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.CompactLogResponse)
GOOGLE_DCHECK_NE(&from, this);
const CompactLogResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CompactLogResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.CompactLogResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.CompactLogResponse)
MergeFrom(*source);
}
}
void CompactLogResponse::MergeFrom(const CompactLogResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.CompactLogResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void CompactLogResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.CompactLogResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CompactLogResponse::CopyFrom(const CompactLogResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.CompactLogResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CompactLogResponse::IsInitialized() const {
return true;
}
void CompactLogResponse::Swap(CompactLogResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void CompactLogResponse::InternalSwap(CompactLogResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CompactLogResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void TransferLeaderRequest::InitAsDefaultInstance() {
::raft_cmdpb::_TransferLeaderRequest_default_instance_._instance.get_mutable()->peer_ = const_cast< ::metapb::Peer*>(
::metapb::Peer::internal_default_instance());
}
class TransferLeaderRequest::HasBitSetters {
public:
static const ::metapb::Peer& peer(const TransferLeaderRequest* msg);
};
const ::metapb::Peer&
TransferLeaderRequest::HasBitSetters::peer(const TransferLeaderRequest* msg) {
return *msg->peer_;
}
void TransferLeaderRequest::clear_peer() {
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TransferLeaderRequest::kPeerFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TransferLeaderRequest::TransferLeaderRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.TransferLeaderRequest)
}
TransferLeaderRequest::TransferLeaderRequest(const TransferLeaderRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_peer()) {
peer_ = new ::metapb::Peer(*from.peer_);
} else {
peer_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.TransferLeaderRequest)
}
void TransferLeaderRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto.base);
peer_ = nullptr;
}
TransferLeaderRequest::~TransferLeaderRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.TransferLeaderRequest)
SharedDtor();
}
void TransferLeaderRequest::SharedDtor() {
if (this != internal_default_instance()) delete peer_;
}
void TransferLeaderRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TransferLeaderRequest& TransferLeaderRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TransferLeaderRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void TransferLeaderRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.TransferLeaderRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TransferLeaderRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .metapb.Peer peer = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_peer(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TransferLeaderRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.TransferLeaderRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .metapb.Peer peer = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_peer()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.TransferLeaderRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.TransferLeaderRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TransferLeaderRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.TransferLeaderRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Peer peer = 1;
if (this->has_peer()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::peer(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.TransferLeaderRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* TransferLeaderRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.TransferLeaderRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .metapb.Peer peer = 1;
if (this->has_peer()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::peer(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.TransferLeaderRequest)
return target;
}
size_t TransferLeaderRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.TransferLeaderRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .metapb.Peer peer = 1;
if (this->has_peer()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*peer_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TransferLeaderRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.TransferLeaderRequest)
GOOGLE_DCHECK_NE(&from, this);
const TransferLeaderRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TransferLeaderRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.TransferLeaderRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.TransferLeaderRequest)
MergeFrom(*source);
}
}
void TransferLeaderRequest::MergeFrom(const TransferLeaderRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.TransferLeaderRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_peer()) {
mutable_peer()->::metapb::Peer::MergeFrom(from.peer());
}
}
void TransferLeaderRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.TransferLeaderRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TransferLeaderRequest::CopyFrom(const TransferLeaderRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.TransferLeaderRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TransferLeaderRequest::IsInitialized() const {
return true;
}
void TransferLeaderRequest::Swap(TransferLeaderRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void TransferLeaderRequest::InternalSwap(TransferLeaderRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(peer_, other->peer_);
}
::PROTOBUF_NAMESPACE_ID::Metadata TransferLeaderRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void TransferLeaderResponse::InitAsDefaultInstance() {
}
class TransferLeaderResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TransferLeaderResponse::TransferLeaderResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.TransferLeaderResponse)
}
TransferLeaderResponse::TransferLeaderResponse(const TransferLeaderResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.TransferLeaderResponse)
}
void TransferLeaderResponse::SharedCtor() {
}
TransferLeaderResponse::~TransferLeaderResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.TransferLeaderResponse)
SharedDtor();
}
void TransferLeaderResponse::SharedDtor() {
}
void TransferLeaderResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TransferLeaderResponse& TransferLeaderResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TransferLeaderResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void TransferLeaderResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.TransferLeaderResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TransferLeaderResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TransferLeaderResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.TransferLeaderResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.TransferLeaderResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.TransferLeaderResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TransferLeaderResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.TransferLeaderResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.TransferLeaderResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* TransferLeaderResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.TransferLeaderResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.TransferLeaderResponse)
return target;
}
size_t TransferLeaderResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.TransferLeaderResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TransferLeaderResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.TransferLeaderResponse)
GOOGLE_DCHECK_NE(&from, this);
const TransferLeaderResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TransferLeaderResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.TransferLeaderResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.TransferLeaderResponse)
MergeFrom(*source);
}
}
void TransferLeaderResponse::MergeFrom(const TransferLeaderResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.TransferLeaderResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void TransferLeaderResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.TransferLeaderResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TransferLeaderResponse::CopyFrom(const TransferLeaderResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.TransferLeaderResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TransferLeaderResponse::IsInitialized() const {
return true;
}
void TransferLeaderResponse::Swap(TransferLeaderResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void TransferLeaderResponse::InternalSwap(TransferLeaderResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata TransferLeaderResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void AdminRequest::InitAsDefaultInstance() {
::raft_cmdpb::_AdminRequest_default_instance_._instance.get_mutable()->change_peer_ = const_cast< ::raft_cmdpb::ChangePeerRequest*>(
::raft_cmdpb::ChangePeerRequest::internal_default_instance());
::raft_cmdpb::_AdminRequest_default_instance_._instance.get_mutable()->compact_log_ = const_cast< ::raft_cmdpb::CompactLogRequest*>(
::raft_cmdpb::CompactLogRequest::internal_default_instance());
::raft_cmdpb::_AdminRequest_default_instance_._instance.get_mutable()->transfer_leader_ = const_cast< ::raft_cmdpb::TransferLeaderRequest*>(
::raft_cmdpb::TransferLeaderRequest::internal_default_instance());
::raft_cmdpb::_AdminRequest_default_instance_._instance.get_mutable()->split_ = const_cast< ::raft_cmdpb::SplitRequest*>(
::raft_cmdpb::SplitRequest::internal_default_instance());
}
class AdminRequest::HasBitSetters {
public:
static const ::raft_cmdpb::ChangePeerRequest& change_peer(const AdminRequest* msg);
static const ::raft_cmdpb::CompactLogRequest& compact_log(const AdminRequest* msg);
static const ::raft_cmdpb::TransferLeaderRequest& transfer_leader(const AdminRequest* msg);
static const ::raft_cmdpb::SplitRequest& split(const AdminRequest* msg);
};
const ::raft_cmdpb::ChangePeerRequest&
AdminRequest::HasBitSetters::change_peer(const AdminRequest* msg) {
return *msg->change_peer_;
}
const ::raft_cmdpb::CompactLogRequest&
AdminRequest::HasBitSetters::compact_log(const AdminRequest* msg) {
return *msg->compact_log_;
}
const ::raft_cmdpb::TransferLeaderRequest&
AdminRequest::HasBitSetters::transfer_leader(const AdminRequest* msg) {
return *msg->transfer_leader_;
}
const ::raft_cmdpb::SplitRequest&
AdminRequest::HasBitSetters::split(const AdminRequest* msg) {
return *msg->split_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AdminRequest::kCmdTypeFieldNumber;
const int AdminRequest::kChangePeerFieldNumber;
const int AdminRequest::kCompactLogFieldNumber;
const int AdminRequest::kTransferLeaderFieldNumber;
const int AdminRequest::kSplitFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AdminRequest::AdminRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.AdminRequest)
}
AdminRequest::AdminRequest(const AdminRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_change_peer()) {
change_peer_ = new ::raft_cmdpb::ChangePeerRequest(*from.change_peer_);
} else {
change_peer_ = nullptr;
}
if (from.has_compact_log()) {
compact_log_ = new ::raft_cmdpb::CompactLogRequest(*from.compact_log_);
} else {
compact_log_ = nullptr;
}
if (from.has_transfer_leader()) {
transfer_leader_ = new ::raft_cmdpb::TransferLeaderRequest(*from.transfer_leader_);
} else {
transfer_leader_ = nullptr;
}
if (from.has_split()) {
split_ = new ::raft_cmdpb::SplitRequest(*from.split_);
} else {
split_ = nullptr;
}
cmd_type_ = from.cmd_type_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.AdminRequest)
}
void AdminRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_AdminRequest_raft_5fcmdpb_2eproto.base);
::memset(&change_peer_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&cmd_type_) -
reinterpret_cast<char*>(&change_peer_)) + sizeof(cmd_type_));
}
AdminRequest::~AdminRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.AdminRequest)
SharedDtor();
}
void AdminRequest::SharedDtor() {
if (this != internal_default_instance()) delete change_peer_;
if (this != internal_default_instance()) delete compact_log_;
if (this != internal_default_instance()) delete transfer_leader_;
if (this != internal_default_instance()) delete split_;
}
void AdminRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const AdminRequest& AdminRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_AdminRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void AdminRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.AdminRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && change_peer_ != nullptr) {
delete change_peer_;
}
change_peer_ = nullptr;
if (GetArenaNoVirtual() == nullptr && compact_log_ != nullptr) {
delete compact_log_;
}
compact_log_ = nullptr;
if (GetArenaNoVirtual() == nullptr && transfer_leader_ != nullptr) {
delete transfer_leader_;
}
transfer_leader_ = nullptr;
if (GetArenaNoVirtual() == nullptr && split_ != nullptr) {
delete split_;
}
split_ = nullptr;
cmd_type_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* AdminRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.AdminCmdType cmd_type = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_cmd_type(static_cast<::raft_cmdpb::AdminCmdType>(val));
} else goto handle_unusual;
continue;
// .raft_cmdpb.ChangePeerRequest change_peer = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_change_peer(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.CompactLogRequest compact_log = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ctx->ParseMessage(mutable_compact_log(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.TransferLeaderRequest transfer_leader = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
ptr = ctx->ParseMessage(mutable_transfer_leader(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.SplitRequest split = 10;
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) {
ptr = ctx->ParseMessage(mutable_split(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool AdminRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.AdminRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.AdminCmdType cmd_type = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_cmd_type(static_cast< ::raft_cmdpb::AdminCmdType >(value));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.ChangePeerRequest change_peer = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_change_peer()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.CompactLogRequest compact_log = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_compact_log()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.TransferLeaderRequest transfer_leader = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_transfer_leader()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.SplitRequest split = 10;
case 10: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (82 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_split()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.AdminRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.AdminRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void AdminRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.AdminRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
1, this->cmd_type(), output);
}
// .raft_cmdpb.ChangePeerRequest change_peer = 2;
if (this->has_change_peer()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::change_peer(this), output);
}
// .raft_cmdpb.CompactLogRequest compact_log = 4;
if (this->has_compact_log()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::compact_log(this), output);
}
// .raft_cmdpb.TransferLeaderRequest transfer_leader = 5;
if (this->has_transfer_leader()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::transfer_leader(this), output);
}
// .raft_cmdpb.SplitRequest split = 10;
if (this->has_split()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
10, HasBitSetters::split(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.AdminRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* AdminRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.AdminRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->cmd_type(), target);
}
// .raft_cmdpb.ChangePeerRequest change_peer = 2;
if (this->has_change_peer()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::change_peer(this), target);
}
// .raft_cmdpb.CompactLogRequest compact_log = 4;
if (this->has_compact_log()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::compact_log(this), target);
}
// .raft_cmdpb.TransferLeaderRequest transfer_leader = 5;
if (this->has_transfer_leader()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::transfer_leader(this), target);
}
// .raft_cmdpb.SplitRequest split = 10;
if (this->has_split()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
10, HasBitSetters::split(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.AdminRequest)
return target;
}
size_t AdminRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.AdminRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .raft_cmdpb.ChangePeerRequest change_peer = 2;
if (this->has_change_peer()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*change_peer_);
}
// .raft_cmdpb.CompactLogRequest compact_log = 4;
if (this->has_compact_log()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*compact_log_);
}
// .raft_cmdpb.TransferLeaderRequest transfer_leader = 5;
if (this->has_transfer_leader()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*transfer_leader_);
}
// .raft_cmdpb.SplitRequest split = 10;
if (this->has_split()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*split_);
}
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->cmd_type());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void AdminRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.AdminRequest)
GOOGLE_DCHECK_NE(&from, this);
const AdminRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<AdminRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.AdminRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.AdminRequest)
MergeFrom(*source);
}
}
void AdminRequest::MergeFrom(const AdminRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.AdminRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_change_peer()) {
mutable_change_peer()->::raft_cmdpb::ChangePeerRequest::MergeFrom(from.change_peer());
}
if (from.has_compact_log()) {
mutable_compact_log()->::raft_cmdpb::CompactLogRequest::MergeFrom(from.compact_log());
}
if (from.has_transfer_leader()) {
mutable_transfer_leader()->::raft_cmdpb::TransferLeaderRequest::MergeFrom(from.transfer_leader());
}
if (from.has_split()) {
mutable_split()->::raft_cmdpb::SplitRequest::MergeFrom(from.split());
}
if (from.cmd_type() != 0) {
set_cmd_type(from.cmd_type());
}
}
void AdminRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.AdminRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AdminRequest::CopyFrom(const AdminRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.AdminRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AdminRequest::IsInitialized() const {
return true;
}
void AdminRequest::Swap(AdminRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void AdminRequest::InternalSwap(AdminRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(change_peer_, other->change_peer_);
swap(compact_log_, other->compact_log_);
swap(transfer_leader_, other->transfer_leader_);
swap(split_, other->split_);
swap(cmd_type_, other->cmd_type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata AdminRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void AdminResponse::InitAsDefaultInstance() {
::raft_cmdpb::_AdminResponse_default_instance_._instance.get_mutable()->change_peer_ = const_cast< ::raft_cmdpb::ChangePeerResponse*>(
::raft_cmdpb::ChangePeerResponse::internal_default_instance());
::raft_cmdpb::_AdminResponse_default_instance_._instance.get_mutable()->compact_log_ = const_cast< ::raft_cmdpb::CompactLogResponse*>(
::raft_cmdpb::CompactLogResponse::internal_default_instance());
::raft_cmdpb::_AdminResponse_default_instance_._instance.get_mutable()->transfer_leader_ = const_cast< ::raft_cmdpb::TransferLeaderResponse*>(
::raft_cmdpb::TransferLeaderResponse::internal_default_instance());
::raft_cmdpb::_AdminResponse_default_instance_._instance.get_mutable()->split_ = const_cast< ::raft_cmdpb::SplitResponse*>(
::raft_cmdpb::SplitResponse::internal_default_instance());
}
class AdminResponse::HasBitSetters {
public:
static const ::raft_cmdpb::ChangePeerResponse& change_peer(const AdminResponse* msg);
static const ::raft_cmdpb::CompactLogResponse& compact_log(const AdminResponse* msg);
static const ::raft_cmdpb::TransferLeaderResponse& transfer_leader(const AdminResponse* msg);
static const ::raft_cmdpb::SplitResponse& split(const AdminResponse* msg);
};
const ::raft_cmdpb::ChangePeerResponse&
AdminResponse::HasBitSetters::change_peer(const AdminResponse* msg) {
return *msg->change_peer_;
}
const ::raft_cmdpb::CompactLogResponse&
AdminResponse::HasBitSetters::compact_log(const AdminResponse* msg) {
return *msg->compact_log_;
}
const ::raft_cmdpb::TransferLeaderResponse&
AdminResponse::HasBitSetters::transfer_leader(const AdminResponse* msg) {
return *msg->transfer_leader_;
}
const ::raft_cmdpb::SplitResponse&
AdminResponse::HasBitSetters::split(const AdminResponse* msg) {
return *msg->split_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AdminResponse::kCmdTypeFieldNumber;
const int AdminResponse::kChangePeerFieldNumber;
const int AdminResponse::kCompactLogFieldNumber;
const int AdminResponse::kTransferLeaderFieldNumber;
const int AdminResponse::kSplitFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AdminResponse::AdminResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.AdminResponse)
}
AdminResponse::AdminResponse(const AdminResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_change_peer()) {
change_peer_ = new ::raft_cmdpb::ChangePeerResponse(*from.change_peer_);
} else {
change_peer_ = nullptr;
}
if (from.has_compact_log()) {
compact_log_ = new ::raft_cmdpb::CompactLogResponse(*from.compact_log_);
} else {
compact_log_ = nullptr;
}
if (from.has_transfer_leader()) {
transfer_leader_ = new ::raft_cmdpb::TransferLeaderResponse(*from.transfer_leader_);
} else {
transfer_leader_ = nullptr;
}
if (from.has_split()) {
split_ = new ::raft_cmdpb::SplitResponse(*from.split_);
} else {
split_ = nullptr;
}
cmd_type_ = from.cmd_type_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.AdminResponse)
}
void AdminResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_AdminResponse_raft_5fcmdpb_2eproto.base);
::memset(&change_peer_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&cmd_type_) -
reinterpret_cast<char*>(&change_peer_)) + sizeof(cmd_type_));
}
AdminResponse::~AdminResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.AdminResponse)
SharedDtor();
}
void AdminResponse::SharedDtor() {
if (this != internal_default_instance()) delete change_peer_;
if (this != internal_default_instance()) delete compact_log_;
if (this != internal_default_instance()) delete transfer_leader_;
if (this != internal_default_instance()) delete split_;
}
void AdminResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const AdminResponse& AdminResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_AdminResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void AdminResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.AdminResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && change_peer_ != nullptr) {
delete change_peer_;
}
change_peer_ = nullptr;
if (GetArenaNoVirtual() == nullptr && compact_log_ != nullptr) {
delete compact_log_;
}
compact_log_ = nullptr;
if (GetArenaNoVirtual() == nullptr && transfer_leader_ != nullptr) {
delete transfer_leader_;
}
transfer_leader_ = nullptr;
if (GetArenaNoVirtual() == nullptr && split_ != nullptr) {
delete split_;
}
split_ = nullptr;
cmd_type_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* AdminResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.AdminCmdType cmd_type = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_cmd_type(static_cast<::raft_cmdpb::AdminCmdType>(val));
} else goto handle_unusual;
continue;
// .raft_cmdpb.ChangePeerResponse change_peer = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_change_peer(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.CompactLogResponse compact_log = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ctx->ParseMessage(mutable_compact_log(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.TransferLeaderResponse transfer_leader = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
ptr = ctx->ParseMessage(mutable_transfer_leader(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .raft_cmdpb.SplitResponse split = 10;
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) {
ptr = ctx->ParseMessage(mutable_split(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool AdminResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.AdminResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.AdminCmdType cmd_type = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_cmd_type(static_cast< ::raft_cmdpb::AdminCmdType >(value));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.ChangePeerResponse change_peer = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_change_peer()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.CompactLogResponse compact_log = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_compact_log()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.TransferLeaderResponse transfer_leader = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (42 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_transfer_leader()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.SplitResponse split = 10;
case 10: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (82 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_split()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.AdminResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.AdminResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void AdminResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.AdminResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
1, this->cmd_type(), output);
}
// .raft_cmdpb.ChangePeerResponse change_peer = 2;
if (this->has_change_peer()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::change_peer(this), output);
}
// .raft_cmdpb.CompactLogResponse compact_log = 4;
if (this->has_compact_log()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::compact_log(this), output);
}
// .raft_cmdpb.TransferLeaderResponse transfer_leader = 5;
if (this->has_transfer_leader()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::transfer_leader(this), output);
}
// .raft_cmdpb.SplitResponse split = 10;
if (this->has_split()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
10, HasBitSetters::split(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.AdminResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* AdminResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.AdminResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->cmd_type(), target);
}
// .raft_cmdpb.ChangePeerResponse change_peer = 2;
if (this->has_change_peer()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::change_peer(this), target);
}
// .raft_cmdpb.CompactLogResponse compact_log = 4;
if (this->has_compact_log()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::compact_log(this), target);
}
// .raft_cmdpb.TransferLeaderResponse transfer_leader = 5;
if (this->has_transfer_leader()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::transfer_leader(this), target);
}
// .raft_cmdpb.SplitResponse split = 10;
if (this->has_split()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
10, HasBitSetters::split(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.AdminResponse)
return target;
}
size_t AdminResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.AdminResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .raft_cmdpb.ChangePeerResponse change_peer = 2;
if (this->has_change_peer()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*change_peer_);
}
// .raft_cmdpb.CompactLogResponse compact_log = 4;
if (this->has_compact_log()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*compact_log_);
}
// .raft_cmdpb.TransferLeaderResponse transfer_leader = 5;
if (this->has_transfer_leader()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*transfer_leader_);
}
// .raft_cmdpb.SplitResponse split = 10;
if (this->has_split()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*split_);
}
// .raft_cmdpb.AdminCmdType cmd_type = 1;
if (this->cmd_type() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->cmd_type());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void AdminResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.AdminResponse)
GOOGLE_DCHECK_NE(&from, this);
const AdminResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<AdminResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.AdminResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.AdminResponse)
MergeFrom(*source);
}
}
void AdminResponse::MergeFrom(const AdminResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.AdminResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_change_peer()) {
mutable_change_peer()->::raft_cmdpb::ChangePeerResponse::MergeFrom(from.change_peer());
}
if (from.has_compact_log()) {
mutable_compact_log()->::raft_cmdpb::CompactLogResponse::MergeFrom(from.compact_log());
}
if (from.has_transfer_leader()) {
mutable_transfer_leader()->::raft_cmdpb::TransferLeaderResponse::MergeFrom(from.transfer_leader());
}
if (from.has_split()) {
mutable_split()->::raft_cmdpb::SplitResponse::MergeFrom(from.split());
}
if (from.cmd_type() != 0) {
set_cmd_type(from.cmd_type());
}
}
void AdminResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.AdminResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AdminResponse::CopyFrom(const AdminResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.AdminResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AdminResponse::IsInitialized() const {
return true;
}
void AdminResponse::Swap(AdminResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void AdminResponse::InternalSwap(AdminResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(change_peer_, other->change_peer_);
swap(compact_log_, other->compact_log_);
swap(transfer_leader_, other->transfer_leader_);
swap(split_, other->split_);
swap(cmd_type_, other->cmd_type_);
}
::PROTOBUF_NAMESPACE_ID::Metadata AdminResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void RaftRequestHeader::InitAsDefaultInstance() {
::raft_cmdpb::_RaftRequestHeader_default_instance_._instance.get_mutable()->peer_ = const_cast< ::metapb::Peer*>(
::metapb::Peer::internal_default_instance());
::raft_cmdpb::_RaftRequestHeader_default_instance_._instance.get_mutable()->region_epoch_ = const_cast< ::metapb::RegionEpoch*>(
::metapb::RegionEpoch::internal_default_instance());
}
class RaftRequestHeader::HasBitSetters {
public:
static const ::metapb::Peer& peer(const RaftRequestHeader* msg);
static const ::metapb::RegionEpoch& region_epoch(const RaftRequestHeader* msg);
};
const ::metapb::Peer&
RaftRequestHeader::HasBitSetters::peer(const RaftRequestHeader* msg) {
return *msg->peer_;
}
const ::metapb::RegionEpoch&
RaftRequestHeader::HasBitSetters::region_epoch(const RaftRequestHeader* msg) {
return *msg->region_epoch_;
}
void RaftRequestHeader::clear_peer() {
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
}
void RaftRequestHeader::clear_region_epoch() {
if (GetArenaNoVirtual() == nullptr && region_epoch_ != nullptr) {
delete region_epoch_;
}
region_epoch_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RaftRequestHeader::kRegionIdFieldNumber;
const int RaftRequestHeader::kPeerFieldNumber;
const int RaftRequestHeader::kRegionEpochFieldNumber;
const int RaftRequestHeader::kTermFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RaftRequestHeader::RaftRequestHeader()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.RaftRequestHeader)
}
RaftRequestHeader::RaftRequestHeader(const RaftRequestHeader& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_peer()) {
peer_ = new ::metapb::Peer(*from.peer_);
} else {
peer_ = nullptr;
}
if (from.has_region_epoch()) {
region_epoch_ = new ::metapb::RegionEpoch(*from.region_epoch_);
} else {
region_epoch_ = nullptr;
}
::memcpy(®ion_id_, &from.region_id_,
static_cast<size_t>(reinterpret_cast<char*>(&term_) -
reinterpret_cast<char*>(®ion_id_)) + sizeof(term_));
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.RaftRequestHeader)
}
void RaftRequestHeader::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto.base);
::memset(&peer_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&term_) -
reinterpret_cast<char*>(&peer_)) + sizeof(term_));
}
RaftRequestHeader::~RaftRequestHeader() {
// @@protoc_insertion_point(destructor:raft_cmdpb.RaftRequestHeader)
SharedDtor();
}
void RaftRequestHeader::SharedDtor() {
if (this != internal_default_instance()) delete peer_;
if (this != internal_default_instance()) delete region_epoch_;
}
void RaftRequestHeader::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RaftRequestHeader& RaftRequestHeader::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_RaftRequestHeader_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void RaftRequestHeader::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.RaftRequestHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && peer_ != nullptr) {
delete peer_;
}
peer_ = nullptr;
if (GetArenaNoVirtual() == nullptr && region_epoch_ != nullptr) {
delete region_epoch_;
}
region_epoch_ = nullptr;
::memset(®ion_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&term_) -
reinterpret_cast<char*>(®ion_id_)) + sizeof(term_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RaftRequestHeader::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// uint64 region_id = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
region_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .metapb.Peer peer = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(mutable_peer(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .metapb.RegionEpoch region_epoch = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ctx->ParseMessage(mutable_region_epoch(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint64 term = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
term_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RaftRequestHeader::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.RaftRequestHeader)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint64 region_id = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, ®ion_id_)));
} else {
goto handle_unusual;
}
break;
}
// .metapb.Peer peer = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_peer()));
} else {
goto handle_unusual;
}
break;
}
// .metapb.RegionEpoch region_epoch = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (34 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_region_epoch()));
} else {
goto handle_unusual;
}
break;
}
// uint64 term = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, &term_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.RaftRequestHeader)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.RaftRequestHeader)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RaftRequestHeader::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.RaftRequestHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 region_id = 1;
if (this->region_id() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(1, this->region_id(), output);
}
// .metapb.Peer peer = 2;
if (this->has_peer()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::peer(this), output);
}
// .metapb.RegionEpoch region_epoch = 4;
if (this->has_region_epoch()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::region_epoch(this), output);
}
// uint64 term = 5;
if (this->term() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(5, this->term(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.RaftRequestHeader)
}
::PROTOBUF_NAMESPACE_ID::uint8* RaftRequestHeader::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.RaftRequestHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 region_id = 1;
if (this->region_id() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->region_id(), target);
}
// .metapb.Peer peer = 2;
if (this->has_peer()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::peer(this), target);
}
// .metapb.RegionEpoch region_epoch = 4;
if (this->has_region_epoch()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::region_epoch(this), target);
}
// uint64 term = 5;
if (this->term() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(5, this->term(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.RaftRequestHeader)
return target;
}
size_t RaftRequestHeader::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.RaftRequestHeader)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .metapb.Peer peer = 2;
if (this->has_peer()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*peer_);
}
// .metapb.RegionEpoch region_epoch = 4;
if (this->has_region_epoch()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*region_epoch_);
}
// uint64 region_id = 1;
if (this->region_id() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->region_id());
}
// uint64 term = 5;
if (this->term() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->term());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RaftRequestHeader::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.RaftRequestHeader)
GOOGLE_DCHECK_NE(&from, this);
const RaftRequestHeader* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<RaftRequestHeader>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.RaftRequestHeader)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.RaftRequestHeader)
MergeFrom(*source);
}
}
void RaftRequestHeader::MergeFrom(const RaftRequestHeader& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.RaftRequestHeader)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_peer()) {
mutable_peer()->::metapb::Peer::MergeFrom(from.peer());
}
if (from.has_region_epoch()) {
mutable_region_epoch()->::metapb::RegionEpoch::MergeFrom(from.region_epoch());
}
if (from.region_id() != 0) {
set_region_id(from.region_id());
}
if (from.term() != 0) {
set_term(from.term());
}
}
void RaftRequestHeader::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.RaftRequestHeader)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RaftRequestHeader::CopyFrom(const RaftRequestHeader& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.RaftRequestHeader)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RaftRequestHeader::IsInitialized() const {
return true;
}
void RaftRequestHeader::Swap(RaftRequestHeader* other) {
if (other == this) return;
InternalSwap(other);
}
void RaftRequestHeader::InternalSwap(RaftRequestHeader* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(peer_, other->peer_);
swap(region_epoch_, other->region_epoch_);
swap(region_id_, other->region_id_);
swap(term_, other->term_);
}
::PROTOBUF_NAMESPACE_ID::Metadata RaftRequestHeader::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void RaftResponseHeader::InitAsDefaultInstance() {
::raft_cmdpb::_RaftResponseHeader_default_instance_._instance.get_mutable()->error_ = const_cast< ::errorpb::Error*>(
::errorpb::Error::internal_default_instance());
}
class RaftResponseHeader::HasBitSetters {
public:
static const ::errorpb::Error& error(const RaftResponseHeader* msg);
};
const ::errorpb::Error&
RaftResponseHeader::HasBitSetters::error(const RaftResponseHeader* msg) {
return *msg->error_;
}
void RaftResponseHeader::clear_error() {
if (GetArenaNoVirtual() == nullptr && error_ != nullptr) {
delete error_;
}
error_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RaftResponseHeader::kErrorFieldNumber;
const int RaftResponseHeader::kUuidFieldNumber;
const int RaftResponseHeader::kCurrentTermFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RaftResponseHeader::RaftResponseHeader()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.RaftResponseHeader)
}
RaftResponseHeader::RaftResponseHeader(const RaftResponseHeader& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
uuid_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from.uuid().size() > 0) {
uuid_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.uuid_);
}
if (from.has_error()) {
error_ = new ::errorpb::Error(*from.error_);
} else {
error_ = nullptr;
}
current_term_ = from.current_term_;
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.RaftResponseHeader)
}
void RaftResponseHeader::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto.base);
uuid_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&error_, 0, static_cast<size_t>(
reinterpret_cast<char*>(¤t_term_) -
reinterpret_cast<char*>(&error_)) + sizeof(current_term_));
}
RaftResponseHeader::~RaftResponseHeader() {
// @@protoc_insertion_point(destructor:raft_cmdpb.RaftResponseHeader)
SharedDtor();
}
void RaftResponseHeader::SharedDtor() {
uuid_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete error_;
}
void RaftResponseHeader::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RaftResponseHeader& RaftResponseHeader::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_RaftResponseHeader_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void RaftResponseHeader::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.RaftResponseHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
uuid_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == nullptr && error_ != nullptr) {
delete error_;
}
error_ = nullptr;
current_term_ = PROTOBUF_ULONGLONG(0);
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RaftResponseHeader::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .errorpb.Error error = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_error(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// bytes uuid = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(mutable_uuid(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint64 current_term = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
current_term_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RaftResponseHeader::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.RaftResponseHeader)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .errorpb.Error error = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_error()));
} else {
goto handle_unusual;
}
break;
}
// bytes uuid = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadBytes(
input, this->mutable_uuid()));
} else {
goto handle_unusual;
}
break;
}
// uint64 current_term = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (24 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64>(
input, ¤t_term_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.RaftResponseHeader)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.RaftResponseHeader)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RaftResponseHeader::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.RaftResponseHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .errorpb.Error error = 1;
if (this->has_error()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::error(this), output);
}
// bytes uuid = 2;
if (this->uuid().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->uuid(), output);
}
// uint64 current_term = 3;
if (this->current_term() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64(3, this->current_term(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.RaftResponseHeader)
}
::PROTOBUF_NAMESPACE_ID::uint8* RaftResponseHeader::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.RaftResponseHeader)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .errorpb.Error error = 1;
if (this->has_error()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::error(this), target);
}
// bytes uuid = 2;
if (this->uuid().size() > 0) {
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBytesToArray(
2, this->uuid(), target);
}
// uint64 current_term = 3;
if (this->current_term() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(3, this->current_term(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.RaftResponseHeader)
return target;
}
size_t RaftResponseHeader::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.RaftResponseHeader)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bytes uuid = 2;
if (this->uuid().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
this->uuid());
}
// .errorpb.Error error = 1;
if (this->has_error()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*error_);
}
// uint64 current_term = 3;
if (this->current_term() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->current_term());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RaftResponseHeader::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.RaftResponseHeader)
GOOGLE_DCHECK_NE(&from, this);
const RaftResponseHeader* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<RaftResponseHeader>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.RaftResponseHeader)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.RaftResponseHeader)
MergeFrom(*source);
}
}
void RaftResponseHeader::MergeFrom(const RaftResponseHeader& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.RaftResponseHeader)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.uuid().size() > 0) {
uuid_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.uuid_);
}
if (from.has_error()) {
mutable_error()->::errorpb::Error::MergeFrom(from.error());
}
if (from.current_term() != 0) {
set_current_term(from.current_term());
}
}
void RaftResponseHeader::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.RaftResponseHeader)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RaftResponseHeader::CopyFrom(const RaftResponseHeader& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.RaftResponseHeader)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RaftResponseHeader::IsInitialized() const {
return true;
}
void RaftResponseHeader::Swap(RaftResponseHeader* other) {
if (other == this) return;
InternalSwap(other);
}
void RaftResponseHeader::InternalSwap(RaftResponseHeader* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
uuid_.Swap(&other->uuid_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(error_, other->error_);
swap(current_term_, other->current_term_);
}
::PROTOBUF_NAMESPACE_ID::Metadata RaftResponseHeader::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void RaftCmdRequest::InitAsDefaultInstance() {
::raft_cmdpb::_RaftCmdRequest_default_instance_._instance.get_mutable()->header_ = const_cast< ::raft_cmdpb::RaftRequestHeader*>(
::raft_cmdpb::RaftRequestHeader::internal_default_instance());
::raft_cmdpb::_RaftCmdRequest_default_instance_._instance.get_mutable()->admin_request_ = const_cast< ::raft_cmdpb::AdminRequest*>(
::raft_cmdpb::AdminRequest::internal_default_instance());
}
class RaftCmdRequest::HasBitSetters {
public:
static const ::raft_cmdpb::RaftRequestHeader& header(const RaftCmdRequest* msg);
static const ::raft_cmdpb::AdminRequest& admin_request(const RaftCmdRequest* msg);
};
const ::raft_cmdpb::RaftRequestHeader&
RaftCmdRequest::HasBitSetters::header(const RaftCmdRequest* msg) {
return *msg->header_;
}
const ::raft_cmdpb::AdminRequest&
RaftCmdRequest::HasBitSetters::admin_request(const RaftCmdRequest* msg) {
return *msg->admin_request_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RaftCmdRequest::kHeaderFieldNumber;
const int RaftCmdRequest::kRequestsFieldNumber;
const int RaftCmdRequest::kAdminRequestFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RaftCmdRequest::RaftCmdRequest()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.RaftCmdRequest)
}
RaftCmdRequest::RaftCmdRequest(const RaftCmdRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
requests_(from.requests_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_header()) {
header_ = new ::raft_cmdpb::RaftRequestHeader(*from.header_);
} else {
header_ = nullptr;
}
if (from.has_admin_request()) {
admin_request_ = new ::raft_cmdpb::AdminRequest(*from.admin_request_);
} else {
admin_request_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.RaftCmdRequest)
}
void RaftCmdRequest::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_RaftCmdRequest_raft_5fcmdpb_2eproto.base);
::memset(&header_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&admin_request_) -
reinterpret_cast<char*>(&header_)) + sizeof(admin_request_));
}
RaftCmdRequest::~RaftCmdRequest() {
// @@protoc_insertion_point(destructor:raft_cmdpb.RaftCmdRequest)
SharedDtor();
}
void RaftCmdRequest::SharedDtor() {
if (this != internal_default_instance()) delete header_;
if (this != internal_default_instance()) delete admin_request_;
}
void RaftCmdRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RaftCmdRequest& RaftCmdRequest::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_RaftCmdRequest_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void RaftCmdRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.RaftCmdRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
requests_.Clear();
if (GetArenaNoVirtual() == nullptr && header_ != nullptr) {
delete header_;
}
header_ = nullptr;
if (GetArenaNoVirtual() == nullptr && admin_request_ != nullptr) {
delete admin_request_;
}
admin_request_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RaftCmdRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.RaftRequestHeader header = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_header(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated .raft_cmdpb.Request requests = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(add_requests(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18);
} else goto handle_unusual;
continue;
// .raft_cmdpb.AdminRequest admin_request = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ctx->ParseMessage(mutable_admin_request(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RaftCmdRequest::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.RaftCmdRequest)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.RaftRequestHeader header = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_header()));
} else {
goto handle_unusual;
}
break;
}
// repeated .raft_cmdpb.Request requests = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, add_requests()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.AdminRequest admin_request = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_admin_request()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.RaftCmdRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.RaftCmdRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RaftCmdRequest::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.RaftCmdRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.RaftRequestHeader header = 1;
if (this->has_header()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::header(this), output);
}
// repeated .raft_cmdpb.Request requests = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->requests_size()); i < n; i++) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->requests(static_cast<int>(i)),
output);
}
// .raft_cmdpb.AdminRequest admin_request = 3;
if (this->has_admin_request()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::admin_request(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.RaftCmdRequest)
}
::PROTOBUF_NAMESPACE_ID::uint8* RaftCmdRequest::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.RaftCmdRequest)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.RaftRequestHeader header = 1;
if (this->has_header()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::header(this), target);
}
// repeated .raft_cmdpb.Request requests = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->requests_size()); i < n; i++) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->requests(static_cast<int>(i)), target);
}
// .raft_cmdpb.AdminRequest admin_request = 3;
if (this->has_admin_request()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::admin_request(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.RaftCmdRequest)
return target;
}
size_t RaftCmdRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.RaftCmdRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .raft_cmdpb.Request requests = 2;
{
unsigned int count = static_cast<unsigned int>(this->requests_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
this->requests(static_cast<int>(i)));
}
}
// .raft_cmdpb.RaftRequestHeader header = 1;
if (this->has_header()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*header_);
}
// .raft_cmdpb.AdminRequest admin_request = 3;
if (this->has_admin_request()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*admin_request_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RaftCmdRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.RaftCmdRequest)
GOOGLE_DCHECK_NE(&from, this);
const RaftCmdRequest* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<RaftCmdRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.RaftCmdRequest)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.RaftCmdRequest)
MergeFrom(*source);
}
}
void RaftCmdRequest::MergeFrom(const RaftCmdRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.RaftCmdRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
requests_.MergeFrom(from.requests_);
if (from.has_header()) {
mutable_header()->::raft_cmdpb::RaftRequestHeader::MergeFrom(from.header());
}
if (from.has_admin_request()) {
mutable_admin_request()->::raft_cmdpb::AdminRequest::MergeFrom(from.admin_request());
}
}
void RaftCmdRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.RaftCmdRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RaftCmdRequest::CopyFrom(const RaftCmdRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.RaftCmdRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RaftCmdRequest::IsInitialized() const {
return true;
}
void RaftCmdRequest::Swap(RaftCmdRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void RaftCmdRequest::InternalSwap(RaftCmdRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&requests_)->InternalSwap(CastToBase(&other->requests_));
swap(header_, other->header_);
swap(admin_request_, other->admin_request_);
}
::PROTOBUF_NAMESPACE_ID::Metadata RaftCmdRequest::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void RaftCmdResponse::InitAsDefaultInstance() {
::raft_cmdpb::_RaftCmdResponse_default_instance_._instance.get_mutable()->header_ = const_cast< ::raft_cmdpb::RaftResponseHeader*>(
::raft_cmdpb::RaftResponseHeader::internal_default_instance());
::raft_cmdpb::_RaftCmdResponse_default_instance_._instance.get_mutable()->admin_response_ = const_cast< ::raft_cmdpb::AdminResponse*>(
::raft_cmdpb::AdminResponse::internal_default_instance());
}
class RaftCmdResponse::HasBitSetters {
public:
static const ::raft_cmdpb::RaftResponseHeader& header(const RaftCmdResponse* msg);
static const ::raft_cmdpb::AdminResponse& admin_response(const RaftCmdResponse* msg);
};
const ::raft_cmdpb::RaftResponseHeader&
RaftCmdResponse::HasBitSetters::header(const RaftCmdResponse* msg) {
return *msg->header_;
}
const ::raft_cmdpb::AdminResponse&
RaftCmdResponse::HasBitSetters::admin_response(const RaftCmdResponse* msg) {
return *msg->admin_response_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RaftCmdResponse::kHeaderFieldNumber;
const int RaftCmdResponse::kResponsesFieldNumber;
const int RaftCmdResponse::kAdminResponseFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RaftCmdResponse::RaftCmdResponse()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:raft_cmdpb.RaftCmdResponse)
}
RaftCmdResponse::RaftCmdResponse(const RaftCmdResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
responses_(from.responses_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_header()) {
header_ = new ::raft_cmdpb::RaftResponseHeader(*from.header_);
} else {
header_ = nullptr;
}
if (from.has_admin_response()) {
admin_response_ = new ::raft_cmdpb::AdminResponse(*from.admin_response_);
} else {
admin_response_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:raft_cmdpb.RaftCmdResponse)
}
void RaftCmdResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_RaftCmdResponse_raft_5fcmdpb_2eproto.base);
::memset(&header_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&admin_response_) -
reinterpret_cast<char*>(&header_)) + sizeof(admin_response_));
}
RaftCmdResponse::~RaftCmdResponse() {
// @@protoc_insertion_point(destructor:raft_cmdpb.RaftCmdResponse)
SharedDtor();
}
void RaftCmdResponse::SharedDtor() {
if (this != internal_default_instance()) delete header_;
if (this != internal_default_instance()) delete admin_response_;
}
void RaftCmdResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RaftCmdResponse& RaftCmdResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_RaftCmdResponse_raft_5fcmdpb_2eproto.base);
return *internal_default_instance();
}
void RaftCmdResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:raft_cmdpb.RaftCmdResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
responses_.Clear();
if (GetArenaNoVirtual() == nullptr && header_ != nullptr) {
delete header_;
}
header_ = nullptr;
if (GetArenaNoVirtual() == nullptr && admin_response_ != nullptr) {
delete admin_response_;
}
admin_response_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RaftCmdResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .raft_cmdpb.RaftResponseHeader header = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(mutable_header(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated .raft_cmdpb.Response responses = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(add_responses(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 18);
} else goto handle_unusual;
continue;
// .raft_cmdpb.AdminResponse admin_response = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ctx->ParseMessage(mutable_admin_response(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RaftCmdResponse::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:raft_cmdpb.RaftCmdResponse)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .raft_cmdpb.RaftResponseHeader header = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_header()));
} else {
goto handle_unusual;
}
break;
}
// repeated .raft_cmdpb.Response responses = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, add_responses()));
} else {
goto handle_unusual;
}
break;
}
// .raft_cmdpb.AdminResponse admin_response = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage(
input, mutable_admin_response()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:raft_cmdpb.RaftCmdResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:raft_cmdpb.RaftCmdResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RaftCmdResponse::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:raft_cmdpb.RaftCmdResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.RaftResponseHeader header = 1;
if (this->has_header()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::header(this), output);
}
// repeated .raft_cmdpb.Response responses = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->responses_size()); i < n; i++) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->responses(static_cast<int>(i)),
output);
}
// .raft_cmdpb.AdminResponse admin_response = 3;
if (this->has_admin_response()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::admin_response(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:raft_cmdpb.RaftCmdResponse)
}
::PROTOBUF_NAMESPACE_ID::uint8* RaftCmdResponse::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:raft_cmdpb.RaftCmdResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .raft_cmdpb.RaftResponseHeader header = 1;
if (this->has_header()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::header(this), target);
}
// repeated .raft_cmdpb.Response responses = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->responses_size()); i < n; i++) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->responses(static_cast<int>(i)), target);
}
// .raft_cmdpb.AdminResponse admin_response = 3;
if (this->has_admin_response()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::admin_response(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:raft_cmdpb.RaftCmdResponse)
return target;
}
size_t RaftCmdResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:raft_cmdpb.RaftCmdResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .raft_cmdpb.Response responses = 2;
{
unsigned int count = static_cast<unsigned int>(this->responses_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
this->responses(static_cast<int>(i)));
}
}
// .raft_cmdpb.RaftResponseHeader header = 1;
if (this->has_header()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*header_);
}
// .raft_cmdpb.AdminResponse admin_response = 3;
if (this->has_admin_response()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*admin_response_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RaftCmdResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:raft_cmdpb.RaftCmdResponse)
GOOGLE_DCHECK_NE(&from, this);
const RaftCmdResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<RaftCmdResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:raft_cmdpb.RaftCmdResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:raft_cmdpb.RaftCmdResponse)
MergeFrom(*source);
}
}
void RaftCmdResponse::MergeFrom(const RaftCmdResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:raft_cmdpb.RaftCmdResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
responses_.MergeFrom(from.responses_);
if (from.has_header()) {
mutable_header()->::raft_cmdpb::RaftResponseHeader::MergeFrom(from.header());
}
if (from.has_admin_response()) {
mutable_admin_response()->::raft_cmdpb::AdminResponse::MergeFrom(from.admin_response());
}
}
void RaftCmdResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:raft_cmdpb.RaftCmdResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RaftCmdResponse::CopyFrom(const RaftCmdResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:raft_cmdpb.RaftCmdResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RaftCmdResponse::IsInitialized() const {
return true;
}
void RaftCmdResponse::Swap(RaftCmdResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void RaftCmdResponse::InternalSwap(RaftCmdResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&responses_)->InternalSwap(CastToBase(&other->responses_));
swap(header_, other->header_);
swap(admin_response_, other->admin_response_);
}
::PROTOBUF_NAMESPACE_ID::Metadata RaftCmdResponse::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace raft_cmdpb
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::raft_cmdpb::GetRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::GetRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::GetRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::GetResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::GetResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::GetResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::PutRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::PutRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::PutRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::PutResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::PutResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::PutResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::DeleteRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::DeleteRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::DeleteRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::DeleteResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::DeleteResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::DeleteResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::SnapRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::SnapRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::SnapRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::SnapResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::SnapResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::SnapResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::Request* Arena::CreateMaybeMessage< ::raft_cmdpb::Request >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::Request >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::Response* Arena::CreateMaybeMessage< ::raft_cmdpb::Response >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::Response >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::ChangePeerRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::ChangePeerRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::ChangePeerRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::ChangePeerResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::ChangePeerResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::ChangePeerResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::SplitRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::SplitRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::SplitRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::SplitResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::SplitResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::SplitResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::CompactLogRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::CompactLogRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::CompactLogRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::CompactLogResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::CompactLogResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::CompactLogResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::TransferLeaderRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::TransferLeaderRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::TransferLeaderRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::TransferLeaderResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::TransferLeaderResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::TransferLeaderResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::AdminRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::AdminRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::AdminRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::AdminResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::AdminResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::AdminResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::RaftRequestHeader* Arena::CreateMaybeMessage< ::raft_cmdpb::RaftRequestHeader >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::RaftRequestHeader >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::RaftResponseHeader* Arena::CreateMaybeMessage< ::raft_cmdpb::RaftResponseHeader >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::RaftResponseHeader >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::RaftCmdRequest* Arena::CreateMaybeMessage< ::raft_cmdpb::RaftCmdRequest >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::RaftCmdRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::raft_cmdpb::RaftCmdResponse* Arena::CreateMaybeMessage< ::raft_cmdpb::RaftCmdResponse >(Arena* arena) {
return Arena::CreateInternal< ::raft_cmdpb::RaftCmdResponse >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 36.41364
| 161
| 0.722444
|
bokket
|
0fd46a373bcc874fb64657ae036bffd45da01831
| 1,364
|
cpp
|
C++
|
Sources/Internal/UI/DataBinding/Private/UIDataSourceComponent.cpp
|
Digan1988/dava.engine
|
70b1e10b2bf001e96ecf51f7ea58da7b55791e93
|
[
"BSD-3-Clause"
] | 1
|
2019-12-21T20:17:25.000Z
|
2019-12-21T20:17:25.000Z
|
Sources/Internal/UI/DataBinding/Private/UIDataSourceComponent.cpp
|
Digan1988/dava.engine
|
70b1e10b2bf001e96ecf51f7ea58da7b55791e93
|
[
"BSD-3-Clause"
] | null | null | null |
Sources/Internal/UI/DataBinding/Private/UIDataSourceComponent.cpp
|
Digan1988/dava.engine
|
70b1e10b2bf001e96ecf51f7ea58da7b55791e93
|
[
"BSD-3-Clause"
] | 1
|
2020-03-14T04:31:21.000Z
|
2020-03-14T04:31:21.000Z
|
#include "UI/DataBinding/UIDataSourceComponent.h"
#include "Engine/Engine.h"
#include "Entity/ComponentManager.h"
#include "Reflection/ReflectionRegistrator.h"
#include "Utils/StringUtils.h"
namespace DAVA
{
DAVA_VIRTUAL_REFLECTION_IMPL(UIDataSourceComponent)
{
ReflectionRegistrator<UIDataSourceComponent>::Begin()
.ConstructorByPointer()
.DestructorByPointer([](UIDataSourceComponent* o) { o->Release(); })
.Field("dataFile", &UIDataSourceComponent::GetDataFile, &UIDataSourceComponent::SetDataFile)
.End();
}
IMPLEMENT_UI_COMPONENT(UIDataSourceComponent);
UIDataSourceComponent::UIDataSourceComponent(const UIDataSourceComponent& c)
: dataFile(c.dataFile)
, data(c.data)
{
isDirty = true;
}
UIDataSourceComponent* UIDataSourceComponent::Clone() const
{
return new UIDataSourceComponent(*this);
}
const Reflection& UIDataSourceComponent::GetData() const
{
return data;
}
void UIDataSourceComponent::SetData(const Reflection& data_)
{
data = data_;
isDirty = true;
}
const FilePath& UIDataSourceComponent::GetDataFile() const
{
return dataFile;
}
void UIDataSourceComponent::SetDataFile(const FilePath& path)
{
dataFile = path;
isDirty = true;
}
bool UIDataSourceComponent::IsDirty() const
{
return isDirty;
}
void UIDataSourceComponent::SetDirty(bool dirty_)
{
isDirty = dirty_;
}
}
| 20.984615
| 96
| 0.750733
|
Digan1988
|
0fd52d0472d2d8b9d2dcf27487a7335ec2a643d8
| 2,421
|
cpp
|
C++
|
source/react3d/bridge/delta3d/BoneBridgeDelta3D.cpp
|
Danathus/react3d
|
742139496fe6864f4fbac195c846e692ffc8be40
|
[
"MIT"
] | 9
|
2018-05-23T10:49:06.000Z
|
2022-03-02T02:00:59.000Z
|
source/react3d/bridge/delta3d/BoneBridgeDelta3D.cpp
|
Danathus/react3d
|
742139496fe6864f4fbac195c846e692ffc8be40
|
[
"MIT"
] | 4
|
2015-09-07T07:50:13.000Z
|
2015-09-07T08:25:36.000Z
|
source/react3d/bridge/delta3d/BoneBridgeDelta3D.cpp
|
Danathus/react3d
|
742139496fe6864f4fbac195c846e692ffc8be40
|
[
"MIT"
] | null | null | null |
#include <ragdoll/bridge/delta3d/BoneBridgeDelta3D.h>
#include <cassert>
#include <ode/ode.h>
#include <dtCore/object.h>
#include <dtCore/odebodywrap.h>
#include <dtCore/transform.h>
#include <ragdoll/bridge/osg/Math.h>
#include <ragdoll/core/kernel/Skeleton.h>
#include <ragdoll/core/kernel/Bone.h>
////////////////////////////////////////////////////////////////////////////////
BoneBridgeDelta3D::BoneBridgeDelta3D()
: mDimensions(0.0f, 0.0f, 0.0f)
, mpObject(NULL)
{
}
void BoneBridgeDelta3D::Configure(dtCore::Object* object, const Vec3f& dimensions)
{
SetDimensions(dimensions);
SetObject(object);
}
void BoneBridgeDelta3D::InitializePhysics(const Vec3f &dimensions)
{
mpObject->SetCollisionBox();
// set the mass for objects
{
dMass mass;
dMassSetBox(&mass, 1.0,
dimensions[X], dimensions[Y], dimensions[Z]);
mpObject->SetMass(&mass);
}
// enable this body
mpObject->EnableDynamics(true);
// apply some damping
{
dtCore::ODEBodyWrap* odeWrapper = mpObject->GetBodyWrapper();
odeWrapper->SetAutoDisableLinearThreshold( 1.0f); // 1.0f
odeWrapper->SetAutoDisableAngularThreshold(1.0f); // 1.0f
odeWrapper->SetAutoDisableSteps(0); // disable consideration of number of steps
odeWrapper->SetAutoDisableTime(0.5f); // wait for half a second before disabling
odeWrapper->SetLinearDamping( 0.01f); // 0.01f
odeWrapper->SetAngularDamping(0.001f); // 0.001f
}
}
void BoneBridgeDelta3D::SetWorldTransform(const Matrix4x4f& matrix)
{
if (mpObject.get())
{
dtCore::Transform position;
position.Set(ConvertKerneltoOSG(matrix));
mpObject->SetTransform(position);
// also reset the speed to zero...
{
const osg::Vec3 linear_vel(0.0, 0.0, 0.0);
dBodySetLinearVel(mpObject->GetBodyID(), linear_vel.x(), linear_vel.y(), linear_vel.z());
}
}
}
Matrix4x4f BoneBridgeDelta3D::GetWorldTransform() const
{
Matrix4x4f matrix = Matrix4x4f::Identity();
if (mpObject.get())
{
// query our position/orientation in world space
osg::Matrix matrixOSG;
{
dtCore::Transform position;
mpObject->GetTransform(position);
position.Get(matrixOSG);
}
matrix = ConvertOSGtoKernel(matrixOSG);
}
return matrix;
}
////////////////////////////////////////////////////////////////////////////////
| 25.484211
| 98
| 0.629079
|
Danathus
|
0fd59994094448befe84182a8d1dc3601422e536
| 4,759
|
cpp
|
C++
|
source/TestList.cpp
|
SVincent/programmiersprachen-aufgabenblatt-4
|
2a83da4062a21e0277298c7ef39885406beb4b3f
|
[
"MIT"
] | null | null | null |
source/TestList.cpp
|
SVincent/programmiersprachen-aufgabenblatt-4
|
2a83da4062a21e0277298c7ef39885406beb4b3f
|
[
"MIT"
] | null | null | null |
source/TestList.cpp
|
SVincent/programmiersprachen-aufgabenblatt-4
|
2a83da4062a21e0277298c7ef39885406beb4b3f
|
[
"MIT"
] | null | null | null |
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "List.hpp"
//Task 4.2
TEST_CASE ("test for size of list", "Task 4.2") {
List<int> list;
REQUIRE (list.size()== 0);
}
TEST_CASE ("test for empty list", "Task 4.2") {
List<int> list;
REQUIRE (list.empty()== true);
}
//Task 4.3
TEST_CASE ("test for push_front", "Task 4.3") {
List<int> list;
list.push_front(42);
REQUIRE (42 == list.front());
REQUIRE (list.size() == 1);
}
TEST_CASE ("test for push_back", "Task 4.3") {
List<int> list;
list.push_back(42);
REQUIRE (42 == list.back());
REQUIRE (list.size() == 1);
}
TEST_CASE ("test for pop_front", "Task 4.3") {
List<int> list;
list.push_front(42);
list.push_back(43);
REQUIRE (42 == list.front());
REQUIRE (list.size() == 2);
list.pop_front();
REQUIRE (43 == list.front());
list.pop_front();
REQUIRE (list.empty());
}
TEST_CASE ("test for pop_back", "Task 4.3") {
List<int> list;
list.push_front(42);
list.push_back(43);
REQUIRE (43 == list.back());
REQUIRE (list.size() == 2);
list.pop_back();
REQUIRE (42 == list.back());
list.pop_back();
REQUIRE (list.empty());
}
//Task 4.4
TEST_CASE ("test for clean()", "Task 4.4") {
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
list.clear();
REQUIRE (list.empty());
}
/* //Task 4.5
TEST_CASE ("test for iterator constructors", "Task 4.5") {
List<int> list;
ListIterator<int> li1();
REQUIRE (li1 == nullptr);
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
ListIterator<int> li2(list.begin());
REQUIRE (li2 == list.begin());
}
TEST_CASE ("test for iterator operators", "Task 4.5") {
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
ListIterator<int> li(list.begin());
//operators
REQUIRE (*li == 3);
//pre-increment and post-increment in iterators should be the same?
li++;
REQUIRE (*li == 2);
//li++5;
REQUIRE (*li == 1);
REQUIRE (*li != 3);
//REQUIRE (li2->next == nullptr);
} */
//Task 4.6
TEST_CASE ("test for begin(), end() on empty list", "Task 4.6") {
List<int> list;
auto b = list.begin();
auto e = list.end();
REQUIRE (b == e);
}
TEST_CASE ("test for begin(), end() on list with one element", "Task 4.6") {
List<int> list;
list.push_front(42);
REQUIRE(42 == *list.begin());
}
//Task 4.7
TEST_CASE ("test for list comparison, different size" , "Task 4.7") {
List<int> list1;
List<int> list2;
list1.push_front(42);
REQUIRE (list1 != list2);
}
TEST_CASE ("test for list comparison, same size" , "Task 4.7") {
List<int> list1;
List<int> list2;
list1.push_front(42);
list2.push_front(42);
REQUIRE(list1 == list2);
list1.push_front(42);
list2.push_front(43);
REQUIRE (list1 != list2);
}
//Task 4.8
TEST_CASE ("test for copy constructor", "Task 4.8") {
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2{list};
REQUIRE (list == list2);
}
//Task 4.9
TEST_CASE ("test for insert()", "Task 4.9") {
List<int> list;
list.push_back(1);
list.push_back(2);
list.push_back(3);
list.push_back(4);
ListIterator<int> li(list.begin());
list.insert(li, 0);
REQUIRE (list.front() == 0);
list.clear();
list.insert(li, 5);
REQUIRE (list.front() == 5);
}
//Task 4.10
TEST_CASE ("test for reverse()", "Task 4.10") {
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2 = reverse(list);
list.reverse();
REQUIRE (list.front() == 1);
REQUIRE (list == list2);
list.reverse();
REQUIRE (list.front() == 4);
REQUIRE (list != list2);
}
//Task 4.11
TEST_CASE ("test for std::copy to vector", "Task 4.11") {
List<int> list;
list.push_back(1);
list.push_back(2);
list.push_back(3);
list.push_back(4);
//vector needs to have a size before using it, unless you want errors again
std::vector<int> vector(list.size());
std::copy(list.begin(), list.end(), vector.begin());
REQUIRE (1 == *vector.begin());
}
//Task 4.13
TEST_CASE ("test for move constructor", "Task 4.13") {
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2 = std::move(list);
REQUIRE (0 == list.size());
REQUIRE (list.empty());
REQUIRE (4 == list2.size());
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
| 23.101942
| 79
| 0.588149
|
SVincent
|
0fd8b50c6ddac1464600f397c4a8f9e089291481
| 540
|
hpp
|
C++
|
src/iislua/iislua_req.hpp
|
shibayan/iislua
|
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
|
[
"Apache-2.0"
] | 16
|
2015-10-09T08:03:24.000Z
|
2022-03-30T08:54:10.000Z
|
src/iislua/iislua_req.hpp
|
shibayan/iislua
|
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
|
[
"Apache-2.0"
] | 6
|
2015-09-18T08:12:42.000Z
|
2020-04-05T07:00:14.000Z
|
src/iislua/iislua_req.hpp
|
shibayan/iislua
|
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
|
[
"Apache-2.0"
] | 7
|
2017-09-12T09:53:20.000Z
|
2022-02-28T23:50:03.000Z
|
#pragma once
IISLUA_API int iislua_req_get_headers(lua_State* L);
IISLUA_API int iislua_req_get_method(lua_State* L);
IISLUA_API int iislua_req_get_post_args(lua_State* L);
IISLUA_API int iislua_req_get_remote_addr(lua_State* L);
IISLUA_API int iislua_req_get_url(lua_State* L);
IISLUA_API int iislua_req_get_url_args(lua_State* L);
IISLUA_API int iislua_req_http_version(lua_State* L);
IISLUA_API int iislua_req_set_header(lua_State* L);
IISLUA_API int iislua_req_set_method(lua_State* L);
IISLUA_API int iislua_req_set_url(lua_State* L);
| 45
| 56
| 0.846296
|
shibayan
|
0fd90ade3fc7c494f29a1908efa2c79da2555a5f
| 3,372
|
hpp
|
C++
|
src/rideables/PriorityQueue.hpp
|
urcs-sync/Montage
|
6dc330da21ec20735a58579b23183a1bd8eeee66
|
[
"MIT"
] | 9
|
2020-10-04T22:03:31.000Z
|
2021-10-08T01:52:57.000Z
|
src/rideables/PriorityQueue.hpp
|
urcs-sync/Montage
|
6dc330da21ec20735a58579b23183a1bd8eeee66
|
[
"MIT"
] | 18
|
2020-10-20T02:39:12.000Z
|
2021-08-30T00:23:32.000Z
|
src/rideables/PriorityQueue.hpp
|
urcs-sync/Montage
|
6dc330da21ec20735a58579b23183a1bd8eeee66
|
[
"MIT"
] | 9
|
2020-10-04T22:06:11.000Z
|
2021-02-19T17:23:17.000Z
|
#ifndef PRIORITY_QUEUE
#define PRIORITY_QUEUE
#include <iostream>
#include <atomic>
#include <algorithm>
#include <memory>
#include "HarnessUtils.hpp"
#include "ConcurrentPrimitives.hpp"
#include "RCUTracker.hpp"
#include "CustomTypes.hpp"
#include "Recoverable.hpp"
#include "HeapQueue.hpp"
//Wentao: TODO to fix later
template<typename K, typename V>
class PriorityQueue : public HeapQueue<K,V>, public Recoverable{
public:
class Payload : public pds::PBlk{
GENERATE_FIELD(K, key, Payload);
GENERATE_FIELD(V, val, Payload);
GENERATE_FIELD(uint64_t, sn, Payload);
public:
Payload(){}
Payload(K k, V v):m_key(k), m_val(v), m_sn(0){}
Payload(const Payload& oth): pds::PBlk(oth), m_key(oth.m_key), m_val(oth.m_val), m_sn(oth.m_sn){}
void persist(){}
};
private:
struct Node{
PriorityQueue* ds;
K key;
Node* next;
Payload* payload;
Node():key(0), next(nullptr), payload(nullptr){};
Node(PriorityQueue* ds_, K k, V val):
ds(ds_), key(k), next(nullptr), payload(ds->pnew<Payload>(k, val)){};
V get_val(){
assert(payload != nullptr && "payload shouldn't be null");
return (V)payload->get_val(ds);
}
void set_sn(uint64_t s){
assert(payload != nullptr && "payload shouldn't be null");
payload->set_sn(ds,s);
}
~Node(){
ds->pdelete(payload);
}
};
public:
std::atomic<uint64_t> global_sn;
private:
std::mutex mtx;
Node* head;
public:
PriorityQueue(int task_num): global_sn(0){
head = new Node();
}
~PriorityQueue(){};
void enqueue(K key, V val, int tid);
optional<V> dequeue(int tid);
};
template<typename K, typename V>
void PriorityQueue<K,V>::enqueue(K key, V val, int tid){
Node* new_node = new Node(this, key, val);
std::unique_lock<std::mutex> lock(mtx);
if(head->next == nullptr){
head->next = new_node;
}else{
if(key >= head->next->key){
new_node->next = head->next;
head->next = new_node;
}else{
Node* tmp = head->next;
while(tmp->next != nullptr && key < tmp->next->key){
tmp = tmp->next;
}
new_node->next = tmp->next;
tmp->next = new_node;
}
}
uint64_t s = global_sn.fetch_add(1);
begin_op();
new_node->set_sn(s);
end_op();
}
template<typename K, typename V>
optional<V> PriorityQueue<K,V>::dequeue(int tid){
std::unique_lock<std::mutex> lock(mtx);
optional<V> res = {};
if(head->next == nullptr){
res.reset();
}else{
Node* target = head->next;
head->next = target->next;
begin_op();
res = (V)target->payload->get_val();
delete(target);
end_op();
}
return res;
}
template <class T>
class PriorityQueueFactory : public RideableFactory{
Rideable* build(GlobalTestConfig* gtc){
return new PriorityQueue<T,T>(gtc->task_num);
}
};
#include <string>
#include "InPlaceString.hpp"
template<>
class PriorityQueue<std::string, std::string>::Payload : public pds::PBlk{
GENERATE_FIELD(pds::InPlaceString<TESTS_KEY_SIZE>, key, Payload);
GENERATE_FIELD(pds::InPlaceString<TESTS_VAL_SIZE>, val, Payload);
GENERATE_FIELD(uint64_t, sn, Payload);
public:
Payload(std::string k, std::string v):m_key(this, k), m_val(this, v), m_sn(0){}
Payload(const Payload& oth): pds::PBlk(oth), m_key(this, oth.m_key), m_val(this, oth.m_val), m_sn(oth.m_sn){}
void persist(){}
};
#endif
| 24.613139
| 112
| 0.643238
|
urcs-sync
|
0fdec6ca4673160d5f8aa509cb6137c4dd70dd47
| 11,641
|
cpp
|
C++
|
tests/ordered_map.cpp
|
N-A-D/libva
|
2c60242bf9094b2cd8cd40b616e6116a897b6e26
|
[
"MIT"
] | null | null | null |
tests/ordered_map.cpp
|
N-A-D/libva
|
2c60242bf9094b2cd8cd40b616e6116a897b6e26
|
[
"MIT"
] | null | null | null |
tests/ordered_map.cpp
|
N-A-D/libva
|
2c60242bf9094b2cd8cd40b616e6116a897b6e26
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "../include/libra/container/ordered_map.hpp"
#include "detail/constants.hpp"
#include <random>
#include <vector>
#include <algorithm>
using map_type = libra::ordered_map<int, int>;
using pair_type = std::pair<int, int>;
struct equivalent {
map_type::value_compare comp;
equivalent(map_type::value_compare comp)
: comp(comp) {}
bool operator()(const map_type::value_type& lhs, const map_type::value_type& rhs) const {
return !comp(lhs, rhs) && !comp(rhs, lhs);
}
};
std::mt19937 gen{ std::random_device{}() };
TEST(OrderedMapTests, ConstructorTests) {
map_type m1;
ASSERT_TRUE(m1.empty());
std::vector<pair_type> pairs(N);
std::generate(pairs.begin(), pairs.end(), [n = 0]() mutable {
auto value = n++;
return std::make_pair(value, value);
});
std::shuffle(pairs.begin(), pairs.end(), gen);
// Test constructor from external container
// Tests initializer list constructors as those forward to this one.
map_type m2(pairs.begin(), pairs.end());
ASSERT_EQ(pairs.size(), m2.size());
ASSERT_TRUE(std::is_sorted(m2.begin(), m2.end(), m2.value_comp()));
ASSERT_EQ(std::unique(m2.begin(), m2.end(), equivalent(m2.value_comp())), m2.end());
// Tests construction from external container with duplicates
size_t size = pairs.size();
auto copy(pairs);
for (auto it = copy.begin(); it != copy.end(); ++it)
pairs.emplace_back(*it);
std::shuffle(pairs.begin(), pairs.end(), gen);
map_type m3(pairs.begin(), pairs.end());
ASSERT_EQ(N, m3.size());
ASSERT_TRUE(std::is_sorted(m3.begin(), m3.end(), m3.value_comp()));
ASSERT_EQ(std::unique(m3.begin(), m3.end(), equivalent(m3.value_comp())), m3.end());
// Test copy construction
map_type copier(m3);
ASSERT_EQ(N, copier.size());
ASSERT_TRUE(std::is_sorted(copier.begin(), copier.end(), copier.value_comp()));
ASSERT_EQ(std::unique(copier.begin(), copier.end(), equivalent(copier.value_comp())), copier.end());
// Test move construction
map_type thief(std::move(copier));
ASSERT_TRUE(copier.empty());
ASSERT_TRUE(std::is_sorted(thief.begin(), thief.end(), thief.value_comp()));
ASSERT_EQ(std::unique(thief.begin(), thief.end(), equivalent(thief.value_comp())), thief.end());
}
TEST(OrderedMapTests, AssignmentTests) {
std::vector<pair_type> pairs(N);
std::generate(pairs.begin(), pairs.end(), [n = 0]() mutable {
auto value = n++;
return std::make_pair(value, value);
});
std::shuffle(pairs.begin(), pairs.end(), gen);
// Test copy assignment
map_type m1(pairs.begin(), pairs.end());
map_type m2 = m1;
ASSERT_EQ(N, m1.size());
ASSERT_EQ(m1.size(), m2.size());
ASSERT_TRUE(std::is_sorted(m2.begin(), m2.end(), m2.value_comp()));
ASSERT_EQ(std::unique(m2.begin(), m2.end(), equivalent(m2.value_comp())), m2.end());
// Test move assignment
map_type m3 = std::move(m2);
ASSERT_TRUE(m2.empty());
ASSERT_EQ(m1.size(), m3.size());
ASSERT_TRUE(std::is_sorted(m3.begin(), m3.end(), m3.value_comp()));
ASSERT_EQ(std::unique(m3.begin(), m3.end(), equivalent(m3.value_comp())), m3.end());
// Test initializer list assignment
std::initializer_list<pair_type> list{ {1, 1}, {2, 2}, {3, 3}, {4, 4} };
m3 = list;
ASSERT_EQ(list.size(), m3.size());
ASSERT_TRUE(std::is_sorted(m3.begin(), m3.end(), m3.value_comp()));
ASSERT_EQ(std::unique(m3.begin(), m3.end(), equivalent(m3.value_comp())), m3.end());
}
TEST(OrderedMapTests, InsertionTests) {
map_type map;
// Test insertion
for (int i = 0; i < N; ++i) {
auto ret = map.insert(map_type::value_type(i, i));
ASSERT_EQ(i, ret.first->first);
ASSERT_TRUE(ret.second);
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end(), map.value_comp()));
ASSERT_EQ(std::unique(map.begin(), map.end(), equivalent(map.value_comp())), map.end());
map.clear();
// Test insertion with correct hint
auto it = map.begin();
for (int i = 0; i < N; ++i) {
auto value = std::make_pair(i, i);
auto ret = map.insert(it, value);
ASSERT_EQ(value.first, ret->first);
it = map.end();
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Test insertion with incorrect hint
it = map.begin();
for (int i = N; i > 0; --i) {
auto value = std::make_pair(i, i);
auto ret = map.insert(it, value);
ASSERT_EQ(value.first, ret->first);
it = map.end();
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Test insertion with corrected hint
it = map.begin();
for (int i = N; i > 0; --i) {
auto value = std::make_pair(i, i);
auto ret = map.insert(it, value);
ASSERT_EQ(value.first, ret->first);
it = map.begin();
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Test insertion with close-by hints
it = map.begin();
for (int i = 0; i < N; ++i) {
auto value = std::make_pair(i, i);
it = map.insert(it, value);
ASSERT_EQ(value.first, it->first);
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Setup random integers
std::srand(std::time(nullptr));
std::vector<int> integers(N);
std::generate(integers.begin(), integers.end(), [n = 0]() mutable { return n++; });
std::shuffle(integers.begin(), integers.end(), gen);
// Test random integer insertion
for (auto integer : integers) {
auto ret = map.insert(std::make_pair(integer, integer));
ASSERT_EQ(integer, ret.first->first);
ASSERT_TRUE(ret.second);
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Test random hint insertion
it = map.begin();
for (auto integer : integers) {
auto value = std::make_pair(integer, integer);
it = map.insert(it, value);
ASSERT_EQ(value.first, it->first);
it = map.begin() + std::rand() % map.size();
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Duplicate value setup
auto copy = integers;
std::copy(copy.begin(), copy.end(), std::back_inserter(integers));
std::shuffle(integers.begin(), integers.end(), gen);
// Test random insertion with duplicates
for (auto integer : integers) {
auto ret = map.insert(std::make_pair(integer, integer));
ASSERT_EQ(integer, ret.first->first);
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
map.clear();
// Test random hinted insertion with duplicates
it = map.begin();
for (auto integer : integers) {
auto value = std::make_pair(integer, integer);
auto ret = map.insert(it, value);
ASSERT_EQ(value.first, ret->first);
it = map.begin() + std::rand() % map.size();
}
ASSERT_EQ(N, map.size());
ASSERT_TRUE(std::is_sorted(map.begin(), map.end()));
ASSERT_EQ(std::unique(map.begin(), map.end()), map.end());
}
TEST(OrderedMapTests, ElementAccess) {
std::vector<int> integers;
libra::ordered_map<int, bool> map;
for (int i = 0; i < N; ++i) {
map.emplace(std::make_pair(i, true));
integers.emplace_back(i);
}
std::shuffle(integers.begin(), integers.end(), gen);
for (auto integer : integers) {
ASSERT_TRUE(map.at(integer));
ASSERT_TRUE(map[integer]);
}
}
TEST(OrderedMapTests, TryEmplace) {
std::vector<int> integers(N);
std::generate(integers.begin(), integers.end(), [n = 0]() mutable { return n++; });
map_type map;
for (auto integer : integers) {
auto ret = map.try_emplace(integer, false);
ASSERT_EQ(integer, ret.first->first);
ASSERT_TRUE(ret.second);
ASSERT_FALSE(map.at(integer));
ASSERT_FALSE(map[integer]);
}
for (auto integer : integers) {
auto ret = map.try_emplace(integer, true);
ASSERT_EQ(integer, ret.first->first);
ASSERT_FALSE(ret.second);
ASSERT_FALSE(map.at(integer)); // The elements remain false
ASSERT_FALSE(map[integer]);
}
map.clear();
// Try emplace with hints
std::shuffle(integers.begin(), integers.end(), gen);
std::srand(std::time(nullptr));
// Random hint
auto it = map.begin();
for (auto integer : integers) {
auto ret = map.try_emplace(it, integer, true);
ASSERT_EQ(integer, ret->first);
ASSERT_TRUE(map.at(integer));
ASSERT_TRUE(map[integer]);
it = map.begin() + std::rand() % map.size();
}
it = map.begin();
std::shuffle(integers.begin(), integers.end(), gen);
for (auto integer : integers) {
auto ret = map.try_emplace(it, integer, false);
ASSERT_EQ(integer, ret->first);
ASSERT_TRUE(map.at(integer));
ASSERT_TRUE(map[integer]);
it = map.begin() + std::rand() % map.size();
}
}
TEST(OrderedMapTests, InsertOrAssignTests) {
std::vector<int> integers(N);
std::generate(integers.begin(), integers.end(), [n = 0]() mutable { return n++; });
map_type map;
for (auto integer : integers) {
auto ret = map.insert_or_assign(integer, false);
ASSERT_EQ(integer, ret.first->first);
ASSERT_TRUE(ret.second);
ASSERT_FALSE(map.at(integer));
ASSERT_FALSE(map[integer]);
}
for (auto integer : integers) {
auto ret = map.insert_or_assign(integer, true);
ASSERT_EQ(integer, ret.first->first);
ASSERT_FALSE(ret.second);
ASSERT_TRUE(map.at(integer));
ASSERT_TRUE(map[integer]);
}
map.clear();
// Try emplace with hints
std::shuffle(integers.begin(), integers.end(), gen);
std::srand(std::time(nullptr));
// Random hint
auto it = map.begin();
for (auto integer : integers) {
auto ret = map.insert_or_assign(it, integer, true);
ASSERT_EQ(integer, ret->first);
ASSERT_TRUE(map.at(integer));
ASSERT_TRUE(map[integer]);
it = map.begin() + std::rand() % map.size();
}
it = map.begin();
std::shuffle(integers.begin(), integers.end(), gen);
for (auto integer : integers) {
auto ret = map.insert_or_assign(it, integer, false);
ASSERT_EQ(integer, ret->first);
ASSERT_FALSE(map.at(integer));
ASSERT_FALSE(map[integer]);
it = map.begin() + std::rand() % map.size();
}
}
TEST(OrderedMapTests, ErasureTests) {
map_type map;
std::vector<int> integers;
for (int i = 0; i < N; ++i) {
integers.emplace_back(i);
auto value = map_type::value_type(i, i);
map.insert(map.end(), value);
}
for (auto integer : integers) {
ASSERT_EQ(1, map.erase(integer));
}
ASSERT_TRUE(map.empty());
for (auto integer : integers) {
map.insert(map_type::value_type(integer, integer));
}
for (auto integer : integers) {
auto it = map.find(integer);
map.erase(it);
ASSERT_FALSE(map.contains(integer));
}
}
TEST(OrderedMapTests, LookupTests) {
map_type map;
std::vector<int> integers;
for (int i = 1; i <= N; ++i) {
integers.emplace_back(i);
auto value = map_type::value_type(i, i);
map.insert(map.end(), value);
}
std::shuffle(integers.begin(), integers.end(), gen);
for (auto integer : integers) {
ASSERT_FALSE(map.contains(-integer));
ASSERT_EQ(0, map.count(-integer));
ASSERT_TRUE(map.contains(integer));
ASSERT_EQ(1, map.count(integer));
}
}
TEST(OrderedMapTests, LexicographicalTests) {
ASSERT_EQ(map_type({ {1, 1}, {2, 2}, {3, 3} }), map_type({ {1, 1}, {2, 2}, {3, 3} }));
ASSERT_LE(map_type({ {1, 1}, {2, 2}, {3, 3} }), map_type({ {2, 3}, {3, 8}, {4, 3} }));
}
TEST(OrderedMapTests, SwapTest) {
map_type m1({ {1, 1}, {2, 2}, {3, 3} });
map_type m2({ {2, 3}, {3, 8}, {4, 3} });
m1.swap(m2);
ASSERT_EQ(m1, map_type({ {2, 3}, {3, 8}, {4, 3} }));
ASSERT_EQ(m2, map_type({ {1, 1}, {2, 2}, {3, 3} }));
}
| 30.394256
| 101
| 0.657761
|
N-A-D
|
0fe078da94b72d621b0d165ba76336227aa2616f
| 5,222
|
cpp
|
C++
|
lib/libchen/test/src/data/json.cpp
|
chensoft/libxio
|
17345e500cca5085641b5392ce8ef7dc65369d69
|
[
"MIT"
] | 6
|
2018-07-28T08:03:24.000Z
|
2022-03-31T08:56:57.000Z
|
lib/libchen/test/src/data/json.cpp
|
chensoft/libxio
|
17345e500cca5085641b5392ce8ef7dc65369d69
|
[
"MIT"
] | null | null | null |
lib/libchen/test/src/data/json.cpp
|
chensoft/libxio
|
17345e500cca5085641b5392ce8ef7dc65369d69
|
[
"MIT"
] | 2
|
2019-05-21T02:26:36.000Z
|
2020-04-13T16:46:20.000Z
|
/**
* Created by Jian Chen
* @since 2016.06.17
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#include "chen/data/json.hpp"
#include "chen/base/str.hpp"
#include "chen/sys/fs.hpp"
#include "gtest/gtest.h"
#include "../conf.hpp"
TEST(DataJsonTest, Type)
{
using chen::json;
json json_object(json::Type::Object);
json json_array(json::Type::Array);
json json_number(json::Type::Number);
json json_string(json::Type::String);
json json_true(json::Type::True);
json json_false(json::Type::False);
json::object unused_o = json_object;
json::array unused_a = json_array;
double unused_d = json_number;
std::int8_t unused_i8 = json_number;
std::uint8_t unused_u8 = json_number;
std::int16_t unused_i16 = json_number;
std::uint16_t unused_u16 = json_number;
std::int32_t unused_i32 = json_number;
std::uint32_t unused_u32 = json_number;
std::int64_t unused_i64 = json_number;
std::uint64_t unused_u64 = json_number;
std::string unused_s = json_string;
bool unused_b = json_true;
EXPECT_EQ(0.0, unused_d);
EXPECT_EQ(0, unused_i8);
EXPECT_EQ(0, unused_u8);
EXPECT_EQ(0, unused_i16);
EXPECT_EQ(0, unused_u16);
EXPECT_EQ(0, unused_i32);
EXPECT_EQ(0u, unused_u32);
EXPECT_EQ(0, unused_i64);
EXPECT_EQ(0u, unused_u64);
EXPECT_EQ(true, unused_b);
json_object.getObject().clear();
json_array.getArray().clear();
json_number.getNumber() = 115;
json_string.getString() = "123";
EXPECT_TRUE(json_object.toObject().empty());
EXPECT_TRUE(json_array.toArray().empty());
EXPECT_TRUE(json(unused_o).getObject().empty());
EXPECT_TRUE(json(unused_a).getArray().empty());
EXPECT_TRUE(json(unused_s).getString().empty());
json assign_o;
json assign_a;
json assign_s;
json assign_d;
assign_o = unused_o;
assign_a = unused_a;
assign_s = unused_s;
assign_d = 115u;
EXPECT_TRUE(assign_o.getObject().empty());
EXPECT_TRUE(assign_a.getArray().empty());
EXPECT_TRUE(assign_s.getString().empty());
EXPECT_EQ(115u, assign_d.getUnsigned());
EXPECT_EQ(123, json_string.toNumber());
EXPECT_EQ(123, json_string.toInteger());
EXPECT_EQ(123u, json_string.toUnsigned());
EXPECT_EQ("115", json_number.toString());
EXPECT_TRUE(json_object.toBool());
EXPECT_TRUE(json(json::Type::None).isNone());
EXPECT_TRUE(json_object.isObject());
EXPECT_TRUE(json_array.isArray());
EXPECT_TRUE(json_number.isNumber());
EXPECT_TRUE(json_string.isString());
EXPECT_TRUE(json_true.isTrue());
EXPECT_TRUE(json_false.isFalse());
EXPECT_TRUE(json(json::Type::Null).isNull());
EXPECT_TRUE(json().isNone());
EXPECT_TRUE(json(json::object()).isObject());
EXPECT_TRUE(json(json::array()).isArray());
EXPECT_TRUE(json(115).isNumber());
EXPECT_TRUE(json(115u).isNumber());
EXPECT_TRUE(json(0.715002586).isNumber());
EXPECT_TRUE(json("Jian Chen").isString());
EXPECT_TRUE(json(std::string("Jian Chen")).isString());
EXPECT_TRUE(json(true).isTrue());
EXPECT_TRUE(json(false).isFalse());
EXPECT_TRUE(json(true).isBool());
EXPECT_TRUE(json(nullptr).isNull());
// parse special string
EXPECT_TRUE(json::parse(" ").isNone());
EXPECT_THROW(json::parse("-"), json::error);
EXPECT_THROW(json::parse("-03"), json::error);
EXPECT_THROW(json::parse("-0."), json::error);
EXPECT_THROW(json::parse("1e123456789"), json::error);
EXPECT_THROW(json::parse("\"ab\\"), json::error);
EXPECT_THROW(json::parse("\"ab\\u9A"), json::error);
EXPECT_THROW(json::parse("\"ab\\u9A@@"), json::error);
EXPECT_THROW(json::parse("\"\\uD83D\\uDE00\""), json::error);
EXPECT_THROW(json::parse("nul"), json::error);
}
TEST(DataJsonTest, Validate)
{
using chen::json;
using chen::str;
if (conf::data.empty())
return ::testing::internal::ColoredPrintf(::testing::internal::COLOR_YELLOW, "warning: you didn't specify test data folder, skip json test\n\n");
// fail
for (int i = 1; i <= 33; ++i)
{
if (i == 18) // I don't think too deep is an error
continue;
EXPECT_THROW(json::validate(conf::data + str::format("/json/fail%d.json", i), true), json::error);
}
EXPECT_THROW(json::validate(conf::data + "/json/role.json", true), json::error);
// pass
for (int j = 1; j <= 3; ++j)
{
EXPECT_NO_THROW(json::validate(conf::data + str::format("/json/pass%d.json", j), true));
}
EXPECT_NO_THROW(json::parse(conf::data + "/json/pass1.json", true));
// exist
EXPECT_THROW(json::parse(conf::data + "/json/not_exist.json", true), json::error);
// equal
std::string text = R"([
1,
2,
3,
false,
null,
{
"key": "val-\"\\\/\b\f\n\r\tchars"
}
])";
auto parse = json::parse(text);
EXPECT_EQ(text, json::stringify(parse, 4));
// error
text = "{unquoted_key: \"keys must be quoted\"}";
EXPECT_THROW(json::parse(text), json::error);
try
{
json::parse(text);
}
catch (const json::error &e)
{
EXPECT_EQ(1u, e.position);
}
}
| 29.670455
| 153
| 0.637112
|
chensoft
|
0fe668a8f6e6f4bfc57f42604c12417cb3983061
| 32,611
|
cpp
|
C++
|
planning/obstacle_cruise_planner/src/node.cpp
|
autowarefoundation/Autoware.Universe
|
618c3e912a9a96efe86f205a9c498e0d57f6d5b7
|
[
"Apache-2.0"
] | null | null | null |
planning/obstacle_cruise_planner/src/node.cpp
|
autowarefoundation/Autoware.Universe
|
618c3e912a9a96efe86f205a9c498e0d57f6d5b7
|
[
"Apache-2.0"
] | null | null | null |
planning/obstacle_cruise_planner/src/node.cpp
|
autowarefoundation/Autoware.Universe
|
618c3e912a9a96efe86f205a9c498e0d57f6d5b7
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2022 TIER IV, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "obstacle_cruise_planner/node.hpp"
#include "obstacle_cruise_planner/polygon_utils.hpp"
#include "obstacle_cruise_planner/utils.hpp"
#include "tier4_autoware_utils/ros/update_param.hpp"
#include "tier4_autoware_utils/trajectory/tmp_conversion.hpp"
#include <boost/format.hpp>
#include <algorithm>
#include <chrono>
namespace
{
VelocityLimitClearCommand createVelocityLimitClearCommandMsg(const rclcpp::Time & current_time)
{
VelocityLimitClearCommand msg;
msg.stamp = current_time;
msg.sender = "obstacle_cruise_planner";
msg.command = true;
return msg;
}
// TODO(murooka) make this function common
size_t findExtendedNearestIndex(
const Trajectory traj, const geometry_msgs::msg::Pose & pose, const double max_dist,
const double max_yaw)
{
const auto nearest_idx =
tier4_autoware_utils::findNearestIndex(traj.points, pose, max_dist, max_yaw);
if (nearest_idx) {
return nearest_idx.get();
}
return tier4_autoware_utils::findNearestIndex(traj.points, pose.position);
}
Trajectory trimTrajectoryFrom(const Trajectory & input, const double nearest_idx)
{
Trajectory output{};
for (size_t i = nearest_idx; i < input.points.size(); ++i) {
output.points.push_back(input.points.at(i));
}
return output;
}
bool isFrontObstacle(
const Trajectory & traj, const size_t ego_idx, const geometry_msgs::msg::Point & obj_pos)
{
size_t obj_idx = tier4_autoware_utils::findNearestSegmentIndex(traj.points, obj_pos);
const double ego_to_obj_distance =
tier4_autoware_utils::calcSignedArcLength(traj.points, ego_idx, obj_idx);
if (obj_idx == 0 && ego_to_obj_distance < 0) {
return false;
}
return true;
}
TrajectoryPoint calcLinearPoint(
const TrajectoryPoint & p_from, const TrajectoryPoint & p_to, const double length)
{
TrajectoryPoint output;
const double dx = p_to.pose.position.x - p_from.pose.position.x;
const double dy = p_to.pose.position.y - p_from.pose.position.y;
const double norm = std::hypot(dx, dy);
output = p_to;
output.pose.position.x += length * dx / norm;
output.pose.position.y += length * dy / norm;
return output;
}
// TODO(murooka) replace with spline interpolation
Trajectory decimateTrajectory(const Trajectory & input, const double step_length)
{
Trajectory output{};
if (input.points.empty()) {
return output;
}
double trajectory_length_sum = 0.0;
double next_length = 0.0;
for (int i = 0; i < static_cast<int>(input.points.size()) - 1; ++i) {
const auto & p_front = input.points.at(i);
const auto & p_back = input.points.at(i + 1);
constexpr double epsilon = 1e-3;
if (next_length <= trajectory_length_sum + epsilon) {
const auto p_interpolate =
calcLinearPoint(p_front, p_back, next_length - trajectory_length_sum);
output.points.push_back(p_interpolate);
next_length += step_length;
continue;
}
trajectory_length_sum += tier4_autoware_utils::calcDistance2d(p_front, p_back);
}
output.points.push_back(input.points.back());
return output;
}
PredictedPath getHighestConfidencePredictedPath(const PredictedObject & predicted_object)
{
const auto reliable_path = std::max_element(
predicted_object.kinematics.predicted_paths.begin(),
predicted_object.kinematics.predicted_paths.end(),
[](const PredictedPath & a, const PredictedPath & b) { return a.confidence < b.confidence; });
return *reliable_path;
}
bool isAngleAlignedWithTrajectory(
const Trajectory & traj, const geometry_msgs::msg::Pose & pose, const double threshold_angle)
{
if (traj.points.empty()) {
return false;
}
const double obj_yaw = tf2::getYaw(pose.orientation);
const size_t nearest_idx = tier4_autoware_utils::findNearestIndex(traj.points, pose.position);
const double traj_yaw = tf2::getYaw(traj.points.at(nearest_idx).pose.orientation);
const double diff_yaw = tier4_autoware_utils::normalizeRadian(obj_yaw - traj_yaw);
const bool is_aligned = std::abs(diff_yaw) <= threshold_angle;
return is_aligned;
}
double calcAlignedAdaptiveCruise(
const PredictedObject & predicted_object, const Trajectory & trajectory)
{
const auto & object_pos = predicted_object.kinematics.initial_pose_with_covariance.pose.position;
const auto & object_vel =
predicted_object.kinematics.initial_twist_with_covariance.twist.linear.x;
const size_t object_idx = tier4_autoware_utils::findNearestIndex(trajectory.points, object_pos);
const double object_yaw =
tf2::getYaw(predicted_object.kinematics.initial_pose_with_covariance.pose.orientation);
const double traj_yaw = tf2::getYaw(trajectory.points.at(object_idx).pose.orientation);
return object_vel * std::cos(object_yaw - traj_yaw);
}
} // namespace
namespace motion_planning
{
ObstacleCruisePlannerNode::ObstacleCruisePlannerNode(const rclcpp::NodeOptions & node_options)
: Node("obstacle_cruise_planner", node_options),
self_pose_listener_(this),
in_objects_ptr_(nullptr),
lpf_acc_ptr_(nullptr),
vehicle_info_(vehicle_info_util::VehicleInfoUtil(*this).getVehicleInfo())
{
using std::placeholders::_1;
// subscriber
trajectory_sub_ = create_subscription<Trajectory>(
"~/input/trajectory", rclcpp::QoS{1},
std::bind(&ObstacleCruisePlannerNode::onTrajectory, this, _1));
smoothed_trajectory_sub_ = create_subscription<Trajectory>(
"/planning/scenario_planning/trajectory", rclcpp::QoS{1},
std::bind(&ObstacleCruisePlannerNode::onSmoothedTrajectory, this, _1));
objects_sub_ = create_subscription<PredictedObjects>(
"~/input/objects", rclcpp::QoS{1}, std::bind(&ObstacleCruisePlannerNode::onObjects, this, _1));
odom_sub_ = create_subscription<Odometry>(
"~/input/odometry", rclcpp::QoS{1},
std::bind(&ObstacleCruisePlannerNode::onOdometry, this, std::placeholders::_1));
// publisher
trajectory_pub_ = create_publisher<Trajectory>("~/output/trajectory", 1);
vel_limit_pub_ =
create_publisher<VelocityLimit>("~/output/velocity_limit", rclcpp::QoS{1}.transient_local());
clear_vel_limit_pub_ = create_publisher<VelocityLimitClearCommand>(
"~/output/clear_velocity_limit", rclcpp::QoS{1}.transient_local());
debug_calculation_time_pub_ = create_publisher<Float32Stamped>("~/debug/calculation_time", 1);
debug_cruise_wall_marker_pub_ =
create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/cruise_wall_marker", 1);
debug_stop_wall_marker_pub_ =
create_publisher<visualization_msgs::msg::MarkerArray>("~/virtual_wall", 1);
debug_marker_pub_ = create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/marker", 1);
// longitudinal_info
const auto longitudinal_info = [&]() {
const double max_accel = declare_parameter<double>("normal.max_acc");
const double min_accel = declare_parameter<double>("normal.min_acc");
const double max_jerk = declare_parameter<double>("normal.max_jerk");
const double min_jerk = declare_parameter<double>("normal.min_jerk");
const double limit_max_accel = declare_parameter<double>("limit.max_acc");
const double limit_min_accel = declare_parameter<double>("limit.min_acc");
const double limit_max_jerk = declare_parameter<double>("limit.max_jerk");
const double limit_min_jerk = declare_parameter<double>("limit.min_jerk");
const double min_ego_accel_for_rss = declare_parameter<double>("common.min_ego_accel_for_rss");
const double min_object_accel_for_rss =
declare_parameter<double>("common.min_object_accel_for_rss");
const double idling_time = declare_parameter<double>("common.idling_time");
const double safe_distance_margin = declare_parameter<double>("common.safe_distance_margin");
return LongitudinalInfo{
max_accel,
min_accel,
max_jerk,
min_jerk,
limit_max_accel,
limit_min_accel,
limit_max_jerk,
limit_min_jerk,
idling_time,
min_ego_accel_for_rss,
min_object_accel_for_rss,
safe_distance_margin};
}();
const bool is_showing_debug_info_ = declare_parameter<bool>("common.is_showing_debug_info");
// low pass filter for ego acceleration
const double lpf_gain_for_accel = declare_parameter<double>("common.lpf_gain_for_accel");
lpf_acc_ptr_ = std::make_shared<LowpassFilter1d>(0.0, lpf_gain_for_accel);
{ // Obstacle filtering parameters
obstacle_filtering_param_.rough_detection_area_expand_width =
declare_parameter<double>("obstacle_filtering.rough_detection_area_expand_width");
obstacle_filtering_param_.detection_area_expand_width =
declare_parameter<double>("obstacle_filtering.detection_area_expand_width");
obstacle_filtering_param_.decimate_trajectory_step_length =
declare_parameter<double>("obstacle_filtering.decimate_trajectory_step_length");
obstacle_filtering_param_.crossing_obstacle_velocity_threshold =
declare_parameter<double>("obstacle_filtering.crossing_obstacle_velocity_threshold");
obstacle_filtering_param_.collision_time_margin =
declare_parameter<double>("obstacle_filtering.collision_time_margin");
obstacle_filtering_param_.ego_obstacle_overlap_time_threshold =
declare_parameter<double>("obstacle_filtering.ego_obstacle_overlap_time_threshold");
obstacle_filtering_param_.max_prediction_time_for_collision_check =
declare_parameter<double>("obstacle_filtering.max_prediction_time_for_collision_check");
obstacle_filtering_param_.crossing_obstacle_traj_angle_threshold =
declare_parameter<double>("obstacle_filtering.crossing_obstacle_traj_angle_threshold");
{
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.unknown")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::UNKNOWN);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.car")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::CAR);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.truck")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::TRUCK);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.bus")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::BUS);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.trailer")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::TRAILER);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.motorcycle")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::MOTORCYCLE);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.bicycle")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::BICYCLE);
}
if (declare_parameter<bool>("obstacle_filtering.ignored_outside_obstacle_type.pedestrian")) {
obstacle_filtering_param_.ignored_outside_obstacle_types.push_back(
ObjectClassification::PEDESTRIAN);
}
}
}
{ // planning algorithm
const std::string planning_algorithm_param =
declare_parameter<std::string>("common.planning_algorithm");
planning_algorithm_ = getPlanningAlgorithmType(planning_algorithm_param);
if (planning_algorithm_ == PlanningAlgorithm::OPTIMIZATION_BASE) {
planner_ptr_ =
std::make_unique<OptimizationBasedPlanner>(*this, longitudinal_info, vehicle_info_);
} else if (planning_algorithm_ == PlanningAlgorithm::PID_BASE) {
planner_ptr_ = std::make_unique<PIDBasedPlanner>(*this, longitudinal_info, vehicle_info_);
} else {
std::logic_error("Designated algorithm is not supported.");
}
min_behavior_stop_margin_ = declare_parameter<double>("common.min_behavior_stop_margin");
nearest_dist_deviation_threshold_ =
declare_parameter<double>("common.nearest_dist_deviation_threshold");
nearest_yaw_deviation_threshold_ =
declare_parameter<double>("common.nearest_yaw_deviation_threshold");
obstacle_velocity_threshold_from_cruise_to_stop_ =
declare_parameter<double>("common.obstacle_velocity_threshold_from_cruise_to_stop");
planner_ptr_->setParams(
is_showing_debug_info_, min_behavior_stop_margin_, nearest_dist_deviation_threshold_,
nearest_yaw_deviation_threshold_, obstacle_velocity_threshold_from_cruise_to_stop_);
}
// wait for first self pose
self_pose_listener_.waitForFirstPose();
// set parameter callback
set_param_res_ = this->add_on_set_parameters_callback(
std::bind(&ObstacleCruisePlannerNode::onParam, this, std::placeholders::_1));
}
ObstacleCruisePlannerNode::PlanningAlgorithm ObstacleCruisePlannerNode::getPlanningAlgorithmType(
const std::string & param) const
{
if (param == "pid_base") {
return PlanningAlgorithm::PID_BASE;
} else if (param == "optimization_base") {
return PlanningAlgorithm::OPTIMIZATION_BASE;
}
return PlanningAlgorithm::INVALID;
}
rcl_interfaces::msg::SetParametersResult ObstacleCruisePlannerNode::onParam(
const std::vector<rclcpp::Parameter> & parameters)
{
planner_ptr_->updateCommonParam(parameters);
planner_ptr_->updateParam(parameters);
tier4_autoware_utils::updateParam<bool>(
parameters, "common.is_showing_debug_info", is_showing_debug_info_);
planner_ptr_->setParams(
is_showing_debug_info_, min_behavior_stop_margin_, nearest_dist_deviation_threshold_,
nearest_yaw_deviation_threshold_, obstacle_velocity_threshold_from_cruise_to_stop_);
// obstacle_filtering
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.rough_detection_area_expand_width",
obstacle_filtering_param_.rough_detection_area_expand_width);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.detection_area_expand_width",
obstacle_filtering_param_.detection_area_expand_width);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.decimate_trajectory_step_length",
obstacle_filtering_param_.decimate_trajectory_step_length);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.crossing_obstacle_velocity_threshold",
obstacle_filtering_param_.crossing_obstacle_velocity_threshold);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.collision_time_margin",
obstacle_filtering_param_.collision_time_margin);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.ego_obstacle_overlap_time_threshold",
obstacle_filtering_param_.ego_obstacle_overlap_time_threshold);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.max_prediction_time_for_collision_check",
obstacle_filtering_param_.max_prediction_time_for_collision_check);
tier4_autoware_utils::updateParam<double>(
parameters, "obstacle_filtering.crossing_obstacle_traj_angle_threshold",
obstacle_filtering_param_.crossing_obstacle_traj_angle_threshold);
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
return result;
}
void ObstacleCruisePlannerNode::onObjects(const PredictedObjects::ConstSharedPtr msg)
{
in_objects_ptr_ = msg;
}
void ObstacleCruisePlannerNode::onOdometry(const Odometry::ConstSharedPtr msg)
{
if (current_twist_ptr_) {
prev_twist_ptr_ = current_twist_ptr_;
}
current_twist_ptr_ = std::make_unique<geometry_msgs::msg::TwistStamped>();
current_twist_ptr_->header = msg->header;
current_twist_ptr_->twist = msg->twist.twist;
}
void ObstacleCruisePlannerNode::onSmoothedTrajectory(const Trajectory::ConstSharedPtr msg)
{
planner_ptr_->setSmoothedTrajectory(msg);
}
void ObstacleCruisePlannerNode::onTrajectory(const Trajectory::ConstSharedPtr msg)
{
const auto current_pose_ptr = self_pose_listener_.getCurrentPose();
// check if subscribed variables are ready
if (
msg->points.empty() || !current_twist_ptr_ || !prev_twist_ptr_ || !in_objects_ptr_ ||
!current_pose_ptr) {
return;
}
stop_watch_.tic(__func__);
// create algorithmic data
DebugData debug_data;
const auto planner_data = createPlannerData(*msg, current_pose_ptr->pose, debug_data);
// generate Trajectory
boost::optional<VelocityLimit> vel_limit;
const auto output_traj = planner_ptr_->generateTrajectory(planner_data, vel_limit, debug_data);
// publisher external velocity limit if required
publishVelocityLimit(vel_limit);
// Publish trajectory
trajectory_pub_->publish(output_traj);
// publish debug data
publishDebugData(debug_data);
// publish and print calculation time
const double calculation_time = stop_watch_.toc(__func__);
publishCalculationTime(calculation_time);
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner"), is_showing_debug_info_, "%s := %f [ms]", __func__,
calculation_time);
}
ObstacleCruisePlannerData ObstacleCruisePlannerNode::createPlannerData(
const Trajectory & trajectory, const geometry_msgs::msg::Pose & current_pose,
DebugData & debug_data)
{
stop_watch_.tic(__func__);
const double current_vel = current_twist_ptr_->twist.linear.x;
const double current_accel = calcCurrentAccel();
// create planner_data
ObstacleCruisePlannerData planner_data;
planner_data.current_time = now();
planner_data.traj = trajectory;
planner_data.current_pose = current_pose;
planner_data.current_vel = current_vel;
planner_data.current_acc = current_accel;
planner_data.target_obstacles =
filterObstacles(*in_objects_ptr_, trajectory, current_pose, current_vel, debug_data);
// print calculation time
const double calculation_time = stop_watch_.toc(__func__);
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner"), is_showing_debug_info_, " %s := %f [ms]",
__func__, calculation_time);
return planner_data;
}
double ObstacleCruisePlannerNode::calcCurrentAccel() const
{
const double diff_vel = current_twist_ptr_->twist.linear.x - prev_twist_ptr_->twist.linear.x;
const double diff_time = std::max(
(rclcpp::Time(current_twist_ptr_->header.stamp) - rclcpp::Time(prev_twist_ptr_->header.stamp))
.seconds(),
1e-03);
const double accel = diff_vel / diff_time;
return lpf_acc_ptr_->filter(accel);
}
std::vector<TargetObstacle> ObstacleCruisePlannerNode::filterObstacles(
const PredictedObjects & predicted_objects, const Trajectory & traj,
const geometry_msgs::msg::Pose & current_pose, const double current_vel, DebugData & debug_data)
{
const auto time_stamp = rclcpp::Time(predicted_objects.header.stamp);
const size_t ego_idx = findExtendedNearestIndex(
traj, current_pose, nearest_dist_deviation_threshold_, nearest_yaw_deviation_threshold_);
// calculate decimated trajectory
const auto trimmed_traj = trimTrajectoryFrom(traj, ego_idx);
const auto decimated_traj =
decimateTrajectory(trimmed_traj, obstacle_filtering_param_.decimate_trajectory_step_length);
if (decimated_traj.points.size() < 2) {
return {};
}
// calculate decimated trajectory polygons
const auto decimated_traj_polygons = polygon_utils::createOneStepPolygons(
decimated_traj, vehicle_info_, obstacle_filtering_param_.detection_area_expand_width);
debug_data.detection_polygons = decimated_traj_polygons;
std::vector<TargetObstacle> target_obstacles;
for (const auto & predicted_object : predicted_objects.objects) {
// filter object whose label is not cruised or stopped
const bool is_target_obstacle =
planner_ptr_->isStopObstacle(predicted_object.classification.front().label) ||
planner_ptr_->isCruiseObstacle(predicted_object.classification.front().label);
if (!is_target_obstacle) {
RCLCPP_INFO_EXPRESSION(
get_logger(), is_showing_debug_info_, "Ignore obstacles since its label is not target.");
continue;
}
const auto & object_pose = predicted_object.kinematics.initial_pose_with_covariance.pose;
const auto & object_velocity =
predicted_object.kinematics.initial_twist_with_covariance.twist.linear.x;
const bool is_front_obstacle = isFrontObstacle(traj, ego_idx, object_pose.position);
if (!is_front_obstacle) {
RCLCPP_INFO_EXPRESSION(
get_logger(), is_showing_debug_info_, "Ignore obstacles since its not front obstacle.");
continue;
}
// rough detection area filtering without polygons
const double dist_from_obstacle_to_traj = [&]() {
return tier4_autoware_utils::calcLateralOffset(decimated_traj.points, object_pose.position);
}();
if (dist_from_obstacle_to_traj > obstacle_filtering_param_.rough_detection_area_expand_width) {
RCLCPP_INFO_EXPRESSION(
get_logger(), is_showing_debug_info_,
"Ignore obstacles since it is far from the trajectory.");
continue;
}
// calculate collision points
const auto obstacle_polygon =
polygon_utils::convertObstacleToPolygon(object_pose, predicted_object.shape);
std::vector<geometry_msgs::msg::Point> collision_points;
const auto first_within_idx = polygon_utils::getFirstCollisionIndex(
decimated_traj_polygons, obstacle_polygon, collision_points);
// precise detection area filtering with polygons
geometry_msgs::msg::Point nearest_collision_point;
if (first_within_idx) { // obstacles inside the trajectory
// calculate nearest collision point
nearest_collision_point =
calcNearestCollisionPoint(first_within_idx.get(), collision_points, decimated_traj);
debug_data.collision_points.push_back(nearest_collision_point);
const bool is_angle_aligned = isAngleAlignedWithTrajectory(
decimated_traj, object_pose,
obstacle_filtering_param_.crossing_obstacle_traj_angle_threshold);
const double has_high_speed =
std::abs(object_velocity) > obstacle_filtering_param_.crossing_obstacle_velocity_threshold;
// ignore running vehicle crossing the ego trajectory with high speed with some condition
if (!is_angle_aligned && has_high_speed) {
const double collision_time_margin = calcCollisionTimeMargin(
current_pose, current_vel, nearest_collision_point, predicted_object,
first_within_idx.get(), decimated_traj, decimated_traj_polygons);
if (collision_time_margin > obstacle_filtering_param_.collision_time_margin) {
// Ignore condition 1
// Ignore vehicle obstacles inside the trajectory, which is crossing the trajectory with
// high speed and does not collide with ego in a certain time.
RCLCPP_INFO_EXPRESSION(
get_logger(), is_showing_debug_info_,
"Ignore inside obstacles since it will not collide with the ego.");
debug_data.intentionally_ignored_obstacles.push_back(predicted_object);
continue;
}
}
} else { // obstacles outside the trajectory
const auto & types = obstacle_filtering_param_.ignored_outside_obstacle_types;
if (
std::find(types.begin(), types.end(), predicted_object.classification.front().label) !=
types.end()) {
continue;
}
const auto predicted_path_with_highest_confidence =
getHighestConfidencePredictedPath(predicted_object);
const bool will_collide = polygon_utils::willCollideWithSurroundObstacle(
decimated_traj, decimated_traj_polygons, predicted_path_with_highest_confidence,
predicted_object.shape, obstacle_filtering_param_.rough_detection_area_expand_width,
obstacle_filtering_param_.ego_obstacle_overlap_time_threshold,
obstacle_filtering_param_.max_prediction_time_for_collision_check);
// TODO(murooka) think later
nearest_collision_point = object_pose.position;
if (!will_collide) {
// Ignore condition 2
// Ignore vehicle obstacles outside the trajectory, whose predicted path
// overlaps the ego trajectory in a certain time.
RCLCPP_INFO_EXPRESSION(
get_logger(), is_showing_debug_info_,
"Ignore outside obstacles since it will not collide with the ego.");
debug_data.intentionally_ignored_obstacles.push_back(predicted_object);
continue;
}
}
// convert to obstacle type
const double trajectory_aligned_adaptive_cruise =
calcAlignedAdaptiveCruise(predicted_object, traj);
const auto target_obstacle = TargetObstacle(
time_stamp, predicted_object, trajectory_aligned_adaptive_cruise, nearest_collision_point);
target_obstacles.push_back(target_obstacle);
}
return target_obstacles;
}
geometry_msgs::msg::Point ObstacleCruisePlannerNode::calcNearestCollisionPoint(
const size_t & first_within_idx, const std::vector<geometry_msgs::msg::Point> & collision_points,
const Trajectory & decimated_traj)
{
std::array<geometry_msgs::msg::Point, 2> segment_points;
if (first_within_idx == 0) {
const auto & traj_front_pose = decimated_traj.points.at(0).pose;
segment_points.at(0) = traj_front_pose.position;
const auto front_pos = tier4_autoware_utils::calcOffsetPose(
traj_front_pose, vehicle_info_.max_longitudinal_offset_m, 0.0, 0.0)
.position;
segment_points.at(1) = front_pos;
} else {
const size_t seg_idx = first_within_idx - 1;
segment_points.at(0) = decimated_traj.points.at(seg_idx).pose.position;
segment_points.at(1) = decimated_traj.points.at(seg_idx + 1).pose.position;
}
size_t min_idx = 0;
double min_dist = std::numeric_limits<double>::max();
for (size_t cp_idx = 0; cp_idx < collision_points.size(); ++cp_idx) {
const auto & collision_point = collision_points.at(cp_idx);
const double dist =
tier4_autoware_utils::calcLongitudinalOffsetToSegment(segment_points, 0, collision_point);
if (dist < min_dist) {
min_dist = dist;
min_idx = cp_idx;
}
}
return collision_points.at(min_idx);
}
double ObstacleCruisePlannerNode::calcCollisionTimeMargin(
const geometry_msgs::msg::Pose & current_pose, const double current_vel,
const geometry_msgs::msg::Point & nearest_collision_point,
const PredictedObject & predicted_object, const size_t first_within_idx,
const Trajectory & decimated_traj,
const std::vector<tier4_autoware_utils::Polygon2d> & decimated_traj_polygons)
{
const auto & object_pose = predicted_object.kinematics.initial_pose_with_covariance.pose;
const auto & object_velocity =
predicted_object.kinematics.initial_twist_with_covariance.twist.linear.x;
const auto predicted_path_with_highest_confidence =
getHighestConfidencePredictedPath(predicted_object);
const double time_to_collision = [&]() {
const double dist_from_ego_to_obstacle =
tier4_autoware_utils::calcSignedArcLength(
decimated_traj.points, current_pose.position, nearest_collision_point) -
vehicle_info_.max_longitudinal_offset_m;
return dist_from_ego_to_obstacle / std::max(1e-6, current_vel);
}();
const double time_to_obstacle_getting_out = [&]() {
const auto obstacle_getting_out_idx = polygon_utils::getFirstNonCollisionIndex(
decimated_traj_polygons, predicted_path_with_highest_confidence, predicted_object.shape,
first_within_idx);
if (!obstacle_getting_out_idx) {
return std::numeric_limits<double>::max();
}
const double dist_to_obstacle_getting_out = tier4_autoware_utils::calcSignedArcLength(
decimated_traj.points, object_pose.position, obstacle_getting_out_idx.get());
return dist_to_obstacle_getting_out / object_velocity;
}();
return time_to_collision - time_to_obstacle_getting_out;
}
void ObstacleCruisePlannerNode::publishVelocityLimit(
const boost::optional<VelocityLimit> & vel_limit)
{
if (vel_limit) {
vel_limit_pub_->publish(vel_limit.get());
need_to_clear_vel_limit_ = true;
} else {
if (need_to_clear_vel_limit_) {
const auto clear_vel_limit_msg = createVelocityLimitClearCommandMsg(now());
clear_vel_limit_pub_->publish(clear_vel_limit_msg);
need_to_clear_vel_limit_ = false;
}
}
}
void ObstacleCruisePlannerNode::publishDebugData(const DebugData & debug_data) const
{
stop_watch_.tic(__func__);
visualization_msgs::msg::MarkerArray debug_marker;
const auto current_time = now();
// obstacles to cruise
for (size_t i = 0; i < debug_data.obstacles_to_cruise.size(); ++i) {
const auto marker = obstacle_cruise_utils::getObjectMarker(
debug_data.obstacles_to_cruise.at(i).pose, i, "obstacles_to_cruise", 0.7, 0.7, 0.0);
debug_marker.markers.push_back(marker);
}
// obstacles to stop
for (size_t i = 0; i < debug_data.obstacles_to_stop.size(); ++i) {
const auto marker = obstacle_cruise_utils::getObjectMarker(
debug_data.obstacles_to_stop.at(i).pose, i, "obstacles_to_stop", 1.0, 0.0, 0.0);
debug_marker.markers.push_back(marker);
}
// intentionally ignored obstacles to cruise or stop
for (size_t i = 0; i < debug_data.intentionally_ignored_obstacles.size(); ++i) {
const auto marker = obstacle_cruise_utils::getObjectMarker(
debug_data.intentionally_ignored_obstacles.at(i).kinematics.initial_pose_with_covariance.pose,
i, "intentionally_ignored_obstacles", 0.0, 1.0, 0.0);
debug_marker.markers.push_back(marker);
}
{ // footprint polygons
auto marker = tier4_autoware_utils::createDefaultMarker(
"map", current_time, "detection_polygons", 0, visualization_msgs::msg::Marker::LINE_LIST,
tier4_autoware_utils::createMarkerScale(0.01, 0.0, 0.0),
tier4_autoware_utils::createMarkerColor(0.0, 1.0, 0.0, 0.999));
for (const auto & detection_polygon : debug_data.detection_polygons) {
for (size_t dp_idx = 0; dp_idx < detection_polygon.outer().size(); ++dp_idx) {
const auto & current_point = detection_polygon.outer().at(dp_idx);
const auto & next_point =
detection_polygon.outer().at((dp_idx + 1) % detection_polygon.outer().size());
marker.points.push_back(
tier4_autoware_utils::createPoint(current_point.x(), current_point.y(), 0.0));
marker.points.push_back(
tier4_autoware_utils::createPoint(next_point.x(), next_point.y(), 0.0));
}
}
debug_marker.markers.push_back(marker);
}
{ // collision points
for (size_t i = 0; i < debug_data.collision_points.size(); ++i) {
auto marker = tier4_autoware_utils::createDefaultMarker(
"map", current_time, "collision_points", i, visualization_msgs::msg::Marker::SPHERE,
tier4_autoware_utils::createMarkerScale(0.25, 0.25, 0.25),
tier4_autoware_utils::createMarkerColor(1.0, 0.0, 0.0, 0.999));
marker.pose.position = debug_data.collision_points.at(i);
debug_marker.markers.push_back(marker);
}
}
debug_marker_pub_->publish(debug_marker);
// wall for cruise and stop
debug_cruise_wall_marker_pub_->publish(debug_data.cruise_wall_marker);
debug_stop_wall_marker_pub_->publish(debug_data.stop_wall_marker);
// print calculation time
const double calculation_time = stop_watch_.toc(__func__);
RCLCPP_INFO_EXPRESSION(
rclcpp::get_logger("ObstacleCruisePlanner"), is_showing_debug_info_, " %s := %f [ms]",
__func__, calculation_time);
}
void ObstacleCruisePlannerNode::publishCalculationTime(const double calculation_time) const
{
Float32Stamped calculation_time_msg;
calculation_time_msg.stamp = now();
calculation_time_msg.data = calculation_time;
debug_calculation_time_pub_->publish(calculation_time_msg);
}
} // namespace motion_planning
#include <rclcpp_components/register_node_macro.hpp>
RCLCPP_COMPONENTS_REGISTER_NODE(motion_planning::ObstacleCruisePlannerNode)
| 40.968593
| 100
| 0.761859
|
autowarefoundation
|
0fe838ead84214d24ff9ab8c5b72d8048a4b7a72
| 5,937
|
cpp
|
C++
|
landmark/landmark_detection.cpp
|
gao-duan/FaceRelighting
|
71594027af1605a643571b9628bedddf5fc3b0e9
|
[
"MIT"
] | 35
|
2019-09-02T01:23:35.000Z
|
2022-03-15T01:18:39.000Z
|
landmark/landmark_detection.cpp
|
gao-duan/FaceRelighting
|
71594027af1605a643571b9628bedddf5fc3b0e9
|
[
"MIT"
] | 2
|
2019-09-14T02:51:25.000Z
|
2019-12-19T13:19:54.000Z
|
landmark/landmark_detection.cpp
|
gao-duan/FaceRelighting
|
71594027af1605a643571b9628bedddf5fc3b0e9
|
[
"MIT"
] | 11
|
2019-08-31T09:58:10.000Z
|
2022-02-24T12:37:08.000Z
|
#include "landmark_detection.h"
#include "stdafx.h"
#include <LandmarkCoreIncludes.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <tbb/tbb.h>
#include "common.h"
static void convert_to_grayscale(const cv::Mat& in, cv::Mat& out)
{
if (in.channels() == 3)
{
// Make sure it's in a correct format
if (in.depth() != CV_8U)
{
if (in.depth() == CV_16U)
{
cv::Mat tmp = in / 256;
tmp.convertTo(tmp, CV_8U);
cv::cvtColor(tmp, out, CV_BGR2GRAY);
}
}
else
{
cv::cvtColor(in, out, CV_BGR2GRAY);
}
}
else if (in.channels() == 4)
{
cv::cvtColor(in, out, CV_BGRA2GRAY);
}
else
{
if (in.depth() == CV_16U)
{
cv::Mat tmp = in / 256;
out = tmp.clone();
}
else if (in.depth() != CV_8U)
{
in.convertTo(out, CV_8U);
}
else
{
out = in.clone();
}
}
}
class LandmarkDetectorImpl {
private:
LandmarkDetector::FaceModelParameters det_parameters;
LandmarkDetector::CLNF clnf_model;
cv::CascadeClassifier classifier;
dlib::frontal_face_detector face_detector_hog;
public:
LandmarkDetectorImpl(const string& model_path = "", const string& classifier_path = "");
std::vector<std::pair<float, float> > detect_landmarks_from_single_img(const string& img_path);
std::vector<std::pair<float, float> > detect_landmarks_from_single_img(const cv::Mat& img);
std::vector<std::vector<std::pair<float, float> > > detect_landmarks_from_multiple_img(const std::vector<string>& imgs_path);
std::vector<std::vector<std::pair<float, float> > > detect_landmarks_from_multiple_img(const std::vector<cv::Mat>& imgs);
};
std::vector<std::pair<float, float>> LandmarkDetectorImpl::detect_landmarks_from_single_img(const string & img_path)
{
cv::Mat read_image = cv::imread(img_path, -1);
return detect_landmarks_from_single_img(read_image);
}
std::vector<std::pair<float, float>> LandmarkDetectorImpl::detect_landmarks_from_single_img(const cv::Mat & img)
{
cv::Mat_<uchar> grayscale_image;
convert_to_grayscale(img, grayscale_image);
vector<cv::Rect_<double> > face_detections;
vector<double> confidences;
std::vector<std::pair<float, float>> res;
if (det_parameters.curr_face_detector == LandmarkDetector::FaceModelParameters::HOG_SVM_DETECTOR)
{
LandmarkDetector::DetectFacesHOG(face_detections, grayscale_image, face_detector_hog, confidences);
}
else
{
LandmarkDetector::DetectFaces(face_detections, grayscale_image, classifier);
}
// Detect landmarks around detected faces
int face_det = 0;
// perform landmark detection for every face detected
for (size_t face = 0; face < face_detections.size(); ++face)
{
// if there are multiple detections go through them
bool success = LandmarkDetector::DetectLandmarksInImage(grayscale_image, face_detections[face], clnf_model, det_parameters);
if (!success) {
continue;
}
int size = (clnf_model.detected_landmarks.size)[0];
bool valid = true;
for (int j = 0; j < size; ++j) {
if (isnan(clnf_model.detected_landmarks.at<double>(j, 0))) {
valid = false;
break;
}
}
if (!valid) {
continue;
}
for (int j = 0; j < size / 2; ++j) {
float x = clnf_model.detected_landmarks.at<double>(j, 0);
float y = clnf_model.detected_landmarks.at<double >(j + size / 2, 0);
res.push_back(std::make_pair(x,y));
}
break;
}
return res;
}
std::vector<std::vector<std::pair<float, float>>> LandmarkDetectorImpl::detect_landmarks_from_multiple_img(const std::vector<string>& imgs_path)
{
std::vector<std::vector<std::pair<float, float>>> res;
for (auto path : imgs_path) {
std::vector<std::pair<float, float> > tmp = detect_landmarks_from_single_img(path);
res.push_back(tmp);
}
return res;
}
std::vector<std::vector<std::pair<float, float>>> LandmarkDetectorImpl::detect_landmarks_from_multiple_img(const std::vector<cv::Mat>& imgs)
{
std::vector<std::vector<std::pair<float, float>>> res;
for (auto img : imgs) {
std::vector<std::pair<float, float> > tmp = detect_landmarks_from_single_img(img);
res.push_back(tmp);
}
return res;
}
LandmarkDetectorImpl::LandmarkDetectorImpl(const string & _model_path, const string & _classifier_path)
{
string default_model_path = solution_dir + "data/model/main_clnf_general.txt";
string default_classifier_path = solution_dir + "data/classifiers/haarcascade_frontalface_alt.xml";
string model_path = (_model_path.empty()) ? default_model_path : _model_path;
string classifier_path = (_classifier_path.empty()) ? default_classifier_path : _classifier_path;
det_parameters = LandmarkDetector::FaceModelParameters();
det_parameters.validate_detections = false;
det_parameters.model_location = model_path;
det_parameters.face_detector_location = classifier_path;
clnf_model = LandmarkDetector::CLNF(det_parameters.model_location);
classifier = cv::CascadeClassifier(det_parameters.face_detector_location);
face_detector_hog = dlib::get_frontal_face_detector();
}
LandmarkDetectorWrapper::LandmarkDetectorWrapper(const string & _model_path, const string & _classfier_path)
{
impl = new LandmarkDetectorImpl(_model_path, _classfier_path);
}
LandmarkDetectorWrapper::~LandmarkDetectorWrapper()
{
delete impl;
}
std::vector<std::pair<float, float>> LandmarkDetectorWrapper::detect_landmarks_from_single_img(const string & img_path)
{
return impl->detect_landmarks_from_single_img(img_path);
}
std::vector<std::pair<float, float>> LandmarkDetectorWrapper::detect_landmarks_from_single_img(const cv::Mat & img)
{
return impl->detect_landmarks_from_single_img(img);
}
std::vector<std::vector<std::pair<float, float>>> LandmarkDetectorWrapper::detect_landmarks_from_multiple_img(const std::vector<string>& imgs_path)
{
return impl->detect_landmarks_from_multiple_img(imgs_path);
}
std::vector<std::vector<std::pair<float, float>>> LandmarkDetectorWrapper::detect_landmarks_from_multiple_img(const std::vector<cv::Mat>& imgs)
{
return impl->detect_landmarks_from_multiple_img(imgs);
}
| 30.137056
| 147
| 0.742126
|
gao-duan
|
0fe86d5221917bf300debb7d4c701b47bf16e838
| 10,980
|
cpp
|
C++
|
src/EIoFilterChain.cpp
|
cxxjava/CxxConet
|
43a617636ab437616c15c20f9826247cb17a66f0
|
[
"Apache-2.0"
] | 23
|
2017-05-11T01:42:15.000Z
|
2021-11-24T06:50:51.000Z
|
src/EIoFilterChain.cpp
|
cxxjava/CxxConet
|
43a617636ab437616c15c20f9826247cb17a66f0
|
[
"Apache-2.0"
] | null | null | null |
src/EIoFilterChain.cpp
|
cxxjava/CxxConet
|
43a617636ab437616c15c20f9826247cb17a66f0
|
[
"Apache-2.0"
] | 8
|
2017-05-11T07:55:22.000Z
|
2022-01-14T09:14:09.000Z
|
/*
* EIoFilterChain.cpp
*
* Created on: 2017-3-16
* Author: cxxjava@163.com
*/
#include "../inc/EIoFilterChain.hh"
#include "../inc/EIoFilterAdapter.hh"
#include "../inc/EIoBuffer.hh"
namespace efc {
namespace naf {
class EIoFilterChain::EntryImpl: public EIoFilterChain::Entry {
public:
~EntryImpl() {
delete nextFilter;
}
EntryImpl(EntryImpl* prevEntry, EntryImpl* nextEntry, const char* name,
EIoFilter* filter, EIoFilterChain* difc) {
if (filter == null) {
throw EIllegalArgumentException(__FILE__, __LINE__, "filter");
}
if (name == null) {
throw EIllegalArgumentException(__FILE__, __LINE__, "name");
}
this->prevEntry = prevEntry;
this->nextEntry = nextEntry;
this->name = name;
this->filter = filter;
this->owner = difc;
class _NextFilter: public EIoFilter::NextFilter {
private:
EntryImpl* ei;
EIoFilterChain* ifc;
public:
_NextFilter(EntryImpl* e, EIoFilterChain* f): ei(e), ifc(f) {
}
virtual ~_NextFilter() {
}
virtual boolean sessionCreated(EIoSession* session) {
Entry* nextEntry = ei->nextEntry;
return ifc->callNextSessionCreated(nextEntry, session);
}
virtual void sessionClosed(EIoSession* session) {
Entry* nextEntry = ei->nextEntry;
ifc->callNextSessionClosed(nextEntry, session);
}
virtual sp<EObject> messageReceived(EIoSession* session, sp<EObject> message) {
Entry* nextEntry = ei->nextEntry;
return ifc->callNextMessageReceived(nextEntry, session, message);
}
sp<EObject> messageSend(EIoSession* session, sp<EObject> message) {
Entry* nextEntry = ei->nextEntry;
return ifc->callNextMessageSend(nextEntry, session, message);
}
virtual EString toString() {
return ei->nextEntry->name;
}
};
this->nextFilter = new _NextFilter(this, difc);
}
/**
* @return the name of the filter.
*/
const char* getName() {
return name.c_str();
}
/**
* @return the filter.
*/
EIoFilter* getFilter() {
return filter;
}
/**
* @return The {@link NextFilter} of the filter.
*/
EIoFilter::NextFilter* getNextFilter() {
return nextFilter;
}
/**
* Adds the specified filter with the specified name just before this entry.
*
* @param name The Filter's name
* @param filter The added Filter
*/
void addBefore(const char* name, EIoFilter* filter) {
owner->addBefore(getName(), name, filter);
}
/**
* Adds the specified filter with the specified name just after this entry.
*
* @param name The Filter's name
* @param filter The added Filter
*/
void addAfter(const char* name, EIoFilter* filter) {
owner->addAfter(getName(), name, filter);
}
/**
* Removes this entry from the chain it belongs to.
*/
void remove() {
owner->remove(getName());
}
virtual EString toString() {
EString sb;
// Add the current filter
sb.append("('").append(getName()).append('\'');
// Add the previous filter
sb.append(", prev: '");
if (prevEntry != null) {
sb.append(prevEntry->name);
sb.append(':');
sb.append(typeid(prevEntry->getFilter()).name());
} else {
sb.append("null");
}
// Add the next filter
sb.append("', next: '");
if (nextEntry != null) {
sb.append(nextEntry->name);
sb.append(':');
sb.append(typeid(nextEntry->getFilter()).name());
} else {
sb.append("null");
}
sb.append("')");
return sb;
}
public:
EntryImpl* prevEntry;
EntryImpl* nextEntry;
EString name;
EIoFilter* filter;
EIoFilter::NextFilter* nextFilter;
EIoFilterChain* owner;
};
EIoFilterChain::~EIoFilterChain() {
delete head->getFilter(); //!
delete head;
delete tail->getFilter(); //!
delete tail;
delete name2entry;
}
EIoFilterChain::EIoFilterChain(EIoSession* session) {
if (session == null) {
throw EIllegalArgumentException(__FILE__, __LINE__, "session");
}
this->session = session;
head = new EntryImpl(null, null, "head", new EIoFilterAdapter(), this);
tail = new EntryImpl(head, null, "tail", new EIoFilterAdapter(), this);
head->nextEntry = tail;
name2entry = new EHashMap<EString*, EntryImpl*>();
}
EIoSession* EIoFilterChain::getSession() {
return session;
}
EIoFilterChain::Entry* EIoFilterChain::getEntry(
const char* name) {
EString ns(name);
return name2entry->get(&ns);
}
EIoFilterChain::Entry* EIoFilterChain::getEntry(
EIoFilter* filter) {
EntryImpl* e = head->nextEntry;
while (e != tail) {
if (e->getFilter() == filter) {
return e;
}
e = e->nextEntry;
}
return null;
}
EIoFilter* EIoFilterChain::get(const char* name) {
EIoFilterChain::Entry* e = getEntry(name);
if (e == null) {
return null;
}
return e->getFilter();
}
boolean EIoFilterChain::contains(const char* name) {
return getEntry(name) != null;
}
boolean EIoFilterChain::contains(EIoFilter* filter) {
return getEntry(filter) != null;
}
EIoFilter::NextFilter* EIoFilterChain::getNextFilter(const char* name) {
EIoFilterChain::Entry* e = getEntry(name);
if (e == null) {
return null;
}
return e->getNextFilter();
}
EIoFilter::NextFilter* EIoFilterChain::getNextFilter(EIoFilter* filter) {
EIoFilterChain::Entry* e = getEntry(filter);
if (e == null) {
return null;
}
return e->getNextFilter();
}
void EIoFilterChain::addFirst(const char* name, EIoFilter* filter) {
checkAddable(name);
register_(head, name, filter);
}
void EIoFilterChain::addLast(const char* name, EIoFilter* filter) {
checkAddable(name);
register_(tail->prevEntry, name, filter);
}
void EIoFilterChain::addBefore(const char* baseName, const char* name,
EIoFilter* filter) {
EntryImpl* baseEntry = checkOldName(baseName);
checkAddable(name);
register_(baseEntry->prevEntry, name, filter);
}
void EIoFilterChain::addAfter(const char* baseName, const char* name,
EIoFilter* filter) {
EntryImpl* baseEntry = checkOldName(baseName);
checkAddable(name);
register_(baseEntry, name, filter);
}
EIoFilter* EIoFilterChain::remove(const char* name) {
EntryImpl* entry = checkOldName(name);
deregister(entry);
EIoFilter* filter = entry->getFilter();
delete entry; //!
return filter;
}
EIoFilter* EIoFilterChain::remove(EIoFilter* filter) {
EntryImpl* e = head->nextEntry;
while (e != tail) {
if (e->getFilter() == filter) {
deregister(e);
delete e; //!
return filter;
}
e = e->nextEntry;
}
EString msg("Filter not found: ");
msg += filter->toString();
throw EIllegalArgumentException(__FILE__, __LINE__, msg.c_str());
}
void EIoFilterChain::clear() {
sp<EIterator<EMapEntry<EString*, EntryImpl*>*> > iter = name2entry->entrySet()->iterator();
while (iter->hasNext()) {
EMapEntry<EString*, EntryImpl*>* entry = iter->next();
EntryImpl* e = entry->getValue();
deregister(e);
delete e; //!
}
}
EString EIoFilterChain::toString() {
EString buf("{ ");
boolean empty = true;
EntryImpl* e = head->nextEntry;
while (e != tail) {
if (!empty) {
buf.append(", ");
} else {
empty = false;
}
buf.append('(');
buf.append(e->getName());
buf.append(':');
buf.append(e->getFilter()->toString());
buf.append(')');
e = e->nextEntry;
}
if (empty) {
buf.append("empty");
}
buf.append(" }");
return buf;
}
void EIoFilterChain::checkAddable(const char* name) {
EString ns(name);
if (name2entry->containsKey(&ns)) {
EString msg("Other filter is using the same name '");
msg += name;
msg += "'";
throw EIllegalArgumentException(__FILE__, __LINE__, msg.c_str());
}
}
void EIoFilterChain::register_(EntryImpl* prevEntry, const char* name, EIoFilter* filter) {
EntryImpl* newEntry = new EntryImpl(prevEntry, prevEntry->nextEntry, name, filter, this);
prevEntry->nextEntry->prevEntry = newEntry;
prevEntry->nextEntry = newEntry;
delete name2entry->put(new EString(name), newEntry);
}
void EIoFilterChain::deregister(EntryImpl* entry) {
EntryImpl* prevEntry = entry->prevEntry;
EntryImpl* nextEntry = entry->nextEntry;
prevEntry->nextEntry = nextEntry;
nextEntry->prevEntry = prevEntry;
EString ns(entry->name);
name2entry->remove(&ns); //delay to free the entry!
}
EIoFilterChain::EntryImpl* EIoFilterChain::checkOldName(const char* baseName) {
EString ns(baseName);
EntryImpl* e = dynamic_cast<EntryImpl*>(name2entry->get(&ns));
if (e == null) {
EString msg("Filter not found:");
msg += baseName;
throw EIllegalArgumentException(__FILE__, __LINE__, msg.c_str());
}
return e;
}
boolean EIoFilterChain::fireSessionCreated() {
return callNextSessionCreated(head, session);
}
boolean EIoFilterChain::callNextSessionCreated(EIoFilterChain::Entry* entry, EIoSession* session) {
if (!entry) return true;
EIoFilter* filter = entry->getFilter();
EIoFilter::NextFilter* nextFilter = entry->getNextFilter();
return filter->sessionCreated(nextFilter, session);
}
void EIoFilterChain::fireSessionClosed() {
callNextSessionClosed(head, session);
}
void EIoFilterChain::callNextSessionClosed(Entry* entry, EIoSession* session) {
if (!entry) return;
EIoFilter* filter = entry->getFilter();
EIoFilter::NextFilter* nextFilter = entry->getNextFilter();
filter->sessionClosed(nextFilter, session);
}
sp<EObject> EIoFilterChain::fireMessageReceived(sp<EObject> message) {
llong currTime = 0;
EIoBuffer* buf = dynamic_cast<EIoBuffer*>(message.get());
if (buf) {
if (currTime == 0) currTime = ESystem::currentTimeMillis();
session->increaseReadBytes(buf->remaining(), currTime);
}
if (message != null) {
if (currTime == 0) currTime = ESystem::currentTimeMillis();
session->increaseReadMessages(currTime);
}
return callNextMessageReceived(head, session, message);
}
sp<EObject> EIoFilterChain::callNextMessageReceived(Entry* entry, EIoSession* session, sp<EObject> message) {
if (!entry) return message;
EIoFilter* filter = entry->getFilter();
EIoFilter::NextFilter* nextFilter = entry->getNextFilter();
return filter->messageReceived(nextFilter, session, message);
}
sp<EObject> EIoFilterChain::fireMessageSend(sp<EObject> message) {
sp<EObject> o = callNextMessageSend(head, session, message);
llong currTime = 0;
EIoBuffer* buf = dynamic_cast<EIoBuffer*>(o.get());
if (buf) {
if (currTime == 0) currTime = ESystem::currentTimeMillis();
session->increaseWrittenBytes(buf->remaining(), currTime);
} else {
EFile* file = dynamic_cast<EFile*>(o.get());
if (file) {
if (currTime == 0) currTime = ESystem::currentTimeMillis();
session->increaseWrittenBytes(file->length(), currTime);
} else {
throw EIllegalStateException(__FILE__, __LINE__, "Unsupported this message type.");
}
}
if (message != null) {
if (currTime == 0) currTime = ESystem::currentTimeMillis();
session->increaseWrittenMessages(currTime);
}
return o;
}
sp<EObject> EIoFilterChain::callNextMessageSend(Entry* entry, EIoSession* session, sp<EObject> message) {
if (!entry) return message;
EIoFilter* filter = entry->getFilter();
EIoFilter::NextFilter* nextFilter = entry->getNextFilter();
return filter->messageSend(nextFilter, session, message);
}
} /* namespace naf */
} /* namespace efc */
| 23.869565
| 109
| 0.691439
|
cxxjava
|
0fe8a7ee3801ecfedb54cc1e4d4c7fb30a1bf896
| 7,799
|
cpp
|
C++
|
poppler-21.11.0/qt6/tests/check_strings.cpp
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
poppler-21.11.0/qt6/tests/check_strings.cpp
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
poppler-21.11.0/qt6/tests/check_strings.cpp
|
stackoverflowed/multimodal
|
95668d0b34d297e96b5ef76521e587578ef2581f
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2010, 2011, Pino Toscano <pino@kde.org>
* Copyright (C) 2021 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QtTest/QtTest>
#include <poppler-qt6.h>
#include <poppler-private.h>
#include <GlobalParams.h>
Q_DECLARE_METATYPE(GooString *)
Q_DECLARE_METATYPE(Unicode *)
class TestStrings : public QObject
{
Q_OBJECT
public:
explicit TestStrings(QObject *parent = nullptr) : QObject(parent) { }
private slots:
void initTestCase();
void cleanupTestCase();
void check_unicodeToQString_data();
void check_unicodeToQString();
void check_UnicodeParsedString_data();
void check_UnicodeParsedString();
void check_QStringToUnicodeGooString_data();
void check_QStringToUnicodeGooString();
void check_QStringToGooString_data();
void check_QStringToGooString();
private:
GooString *newGooString(const char *s);
GooString *newGooString(const char *s, int l);
QVector<GooString *> m_gooStrings;
};
void TestStrings::initTestCase()
{
qRegisterMetaType<GooString *>("GooString*");
qRegisterMetaType<Unicode *>("Unicode*");
globalParams = std::make_unique<GlobalParams>();
}
void TestStrings::cleanupTestCase()
{
qDeleteAll(m_gooStrings);
globalParams.reset();
}
void TestStrings::check_unicodeToQString_data()
{
QTest::addColumn<Unicode *>("data");
QTest::addColumn<int>("length");
QTest::addColumn<QString>("result");
{
const int l = 1;
Unicode *u = new Unicode[l];
u[0] = int('a');
QTest::newRow("a") << u << l << QStringLiteral("a");
}
{
const int l = 1;
Unicode *u = new Unicode[l];
u[0] = 0x0161;
QTest::newRow("\u0161") << u << l << QStringLiteral("\u0161");
}
{
const int l = 2;
Unicode *u = new Unicode[l];
u[0] = int('a');
u[1] = int('b');
QTest::newRow("ab") << u << l << QStringLiteral("ab");
}
{
const int l = 2;
Unicode *u = new Unicode[l];
u[0] = int('a');
u[1] = 0x0161;
QTest::newRow("a\u0161") << u << l << QStringLiteral("a\u0161");
}
{
const int l = 2;
Unicode *u = new Unicode[l];
u[0] = 0x5c01;
u[1] = 0x9762;
QTest::newRow("\xe5\xb0\x81\xe9\x9d\xa2") << u << l << QStringLiteral("封面");
}
{
const int l = 3;
Unicode *u = new Unicode[l];
u[0] = 0x5c01;
u[1] = 0x9762;
u[2] = 0x0;
QTest::newRow("\xe5\xb0\x81\xe9\x9d\xa2 + 0") << u << l << QStringLiteral("封面");
}
{
const int l = 4;
Unicode *u = new Unicode[l];
u[0] = 0x5c01;
u[1] = 0x9762;
u[2] = 0x0;
u[3] = 0x0;
QTest::newRow("\xe5\xb0\x81\xe9\x9d\xa2 + two 0") << u << l << QStringLiteral("封面");
}
}
void TestStrings::check_unicodeToQString()
{
QFETCH(Unicode *, data);
QFETCH(int, length);
QFETCH(QString, result);
QCOMPARE(Poppler::unicodeToQString(data, length), result);
delete[] data;
}
void TestStrings::check_UnicodeParsedString_data()
{
QTest::addColumn<GooString *>("string");
QTest::addColumn<QString>("result");
// non-unicode strings
QTest::newRow("<empty>") << newGooString("") << QString();
QTest::newRow("a") << newGooString("a") << QStringLiteral("a");
QTest::newRow("ab") << newGooString("ab") << QStringLiteral("ab");
QTest::newRow("~") << newGooString("~") << QStringLiteral("~");
QTest::newRow("test string") << newGooString("test string") << QStringLiteral("test string");
// unicode strings
QTest::newRow("<unicode marks>") << newGooString("\xFE\xFF") << QString();
QTest::newRow("U a") << newGooString("\xFE\xFF\0a", 4) << QStringLiteral("a");
QTest::newRow("U ~") << newGooString("\xFE\xFF\0~", 4) << QStringLiteral("~");
QTest::newRow("U aa") << newGooString("\xFE\xFF\0a\0a", 6) << QStringLiteral("aa");
QTest::newRow("U \xC3\x9F") << newGooString("\xFE\xFF\0\xDF", 4) << QStringLiteral("ß");
QTest::newRow("U \xC3\x9F\x61") << newGooString("\xFE\xFF\0\xDF\0\x61", 6) << QStringLiteral("ßa");
QTest::newRow("U \xC5\xA1") << newGooString("\xFE\xFF\x01\x61", 4) << QStringLiteral("š");
QTest::newRow("U \xC5\xA1\x61") << newGooString("\xFE\xFF\x01\x61\0\x61", 6) << QStringLiteral("ša");
QTest::newRow("test string") << newGooString("\xFE\xFF\0t\0e\0s\0t\0 \0s\0t\0r\0i\0n\0g", 24) << QStringLiteral("test string");
QTest::newRow("UTF16-LE") << newGooString("\xFF\xFE\xDA\x00\x6E\x00\xEE\x00\x63\x00\xF6\x00\x64\x00\xE9\x00\x51\x75", 18) << QStringLiteral("Únîcödé畑");
}
void TestStrings::check_UnicodeParsedString()
{
QFETCH(GooString *, string);
QFETCH(QString, result);
QCOMPARE(Poppler::UnicodeParsedString(string), result);
}
void TestStrings::check_QStringToUnicodeGooString_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<QByteArray>("result");
QTest::newRow("<null>") << QString() << QByteArray("");
QTest::newRow("<empty>") << QString(QLatin1String("")) << QByteArray("");
QTest::newRow("a") << QStringLiteral("a") << QByteArray("\0a", 2);
QTest::newRow("ab") << QStringLiteral("ab") << QByteArray("\0a\0b", 4);
QTest::newRow("test string") << QStringLiteral("test string") << QByteArray("\0t\0e\0s\0t\0 \0s\0t\0r\0i\0n\0g", 22);
QTest::newRow("\xC3\x9F") << QStringLiteral("ß") << QByteArray("\0\xDF", 2);
QTest::newRow("\xC3\x9F\x61") << QStringLiteral("ßa") << QByteArray("\0\xDF\0\x61", 4);
}
void TestStrings::check_QStringToUnicodeGooString()
{
QFETCH(QString, string);
QFETCH(QByteArray, result);
GooString *goo = Poppler::QStringToUnicodeGooString(string);
if (string.isEmpty()) {
QVERIFY(goo->toStr().empty());
QCOMPARE(goo->getLength(), 0);
} else {
QVERIFY(goo->hasUnicodeMarker());
QCOMPARE(goo->getLength(), string.length() * 2 + 2);
QCOMPARE(result, QByteArray::fromRawData(goo->c_str() + 2, goo->getLength() - 2));
}
delete goo;
}
void TestStrings::check_QStringToGooString_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<GooString *>("result");
QTest::newRow("<null>") << QString() << newGooString("");
QTest::newRow("<empty>") << QString(QLatin1String("")) << newGooString("");
QTest::newRow("a") << QStringLiteral("a") << newGooString("a");
QTest::newRow("ab") << QStringLiteral("ab") << newGooString("ab");
}
void TestStrings::check_QStringToGooString()
{
QFETCH(QString, string);
QFETCH(GooString *, result);
GooString *goo = Poppler::QStringToGooString(string);
QCOMPARE(goo->c_str(), result->c_str());
delete goo;
}
GooString *TestStrings::newGooString(const char *s)
{
GooString *goo = new GooString(s);
m_gooStrings.append(goo);
return goo;
}
GooString *TestStrings::newGooString(const char *s, int l)
{
GooString *goo = new GooString(s, l);
m_gooStrings.append(goo);
return goo;
}
QTEST_GUILESS_MAIN(TestStrings)
#include "check_strings.moc"
| 31.963115
| 156
| 0.625593
|
stackoverflowed
|
0feb4ccdee2dca734c3d1267c3e4d138bfa1cc62
| 1,962
|
cpp
|
C++
|
timer.cpp
|
RaphaelPoncet/2016-macs2-projet-hpc
|
1ae8936113ee24f0b49a303627d4fd5bc045f78d
|
[
"Apache-2.0"
] | 2
|
2017-07-19T09:14:20.000Z
|
2017-09-17T11:39:52.000Z
|
timer.cpp
|
RaphaelPoncet/2016-macs2-projet-hpc
|
1ae8936113ee24f0b49a303627d4fd5bc045f78d
|
[
"Apache-2.0"
] | null | null | null |
timer.cpp
|
RaphaelPoncet/2016-macs2-projet-hpc
|
1ae8936113ee24f0b49a303627d4fd5bc045f78d
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2016 Raphael Poncet.
// 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 goveroning permissions and
// limitations under the License.
#include <algorithm>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <numeric>
#include "timer.hpp"
namespace Timer {
struct timespec Now() {
struct timespec temp;
clock_gettime(CLOCK_MONOTONIC_RAW, &temp);
return temp;
}
double DiffTime(const struct timespec& start, const struct timespec& end) {
struct timespec temp;
if ((end.tv_nsec - start.tv_nsec) < 0) {
temp.tv_sec = end.tv_sec-start.tv_sec - 1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
const double time_in_ms = 1.0e3 * temp.tv_sec + 1.0e-6 * temp.tv_nsec;
return time_in_ms;
}
void PrintTimings(const std::vector<RealT>& timings,
const std::string& kernel_name,
std::ostream* os_ptr) {
if (!timings.empty()) {
const double mean = std::accumulate(timings.begin(), timings.end(), 0.0);
*os_ptr << std::setprecision(10) << kernel_name << " : "
<< "min="
<< *std::min_element(timings.begin(), timings.end()) << "ms, "
<< "mean="
<< mean / timings.size() << "ms, "
<< "max="
<< *std::max_element(timings.begin(), timings.end()) << "ms\n";
}
}
}
| 25.480519
| 79
| 0.622324
|
RaphaelPoncet
|
0fec23990e35247c9d4c9783b30b935dd56a3032
| 2,950
|
cpp
|
C++
|
src/Application.cpp
|
sujeong-choi/2020-1-OSSP2-CarpeDiem-5
|
f6873e347aac05598e7d3e3a5d7547b9e82555ac
|
[
"MIT"
] | 24
|
2015-02-02T15:36:59.000Z
|
2022-01-29T01:32:32.000Z
|
src/Application.cpp
|
sujeong-choi/2020-1-OSSP2-CarpeDiem-5
|
f6873e347aac05598e7d3e3a5d7547b9e82555ac
|
[
"MIT"
] | 20
|
2020-04-14T06:25:36.000Z
|
2020-06-21T09:01:01.000Z
|
src/Application.cpp
|
kyureekim/2020-1-OSSP2-CarpeDiem-5
|
646560fb22301c77282756b71c497adfb12dbfa8
|
[
"MIT"
] | 9
|
2015-02-21T04:07:33.000Z
|
2021-03-25T19:56:30.000Z
|
/*******************************************************************//*
* Implementation of the Application class.
*
* @author Brandon To
* @version 1.0
* @since 2014-08-05
* @modified 2015-02-21
*********************************************************************/
#include "Application.h"
#include <cstdio>
#include <cstddef>
#ifdef _WIN32
#include <SDL.h>
#endif
#ifdef __linux
#include <SDL2/SDL.h>
#endif
#include "ApplicationStateManager.h"
#include "AudioSystem.h"
#include "SDL_util.h"
// Constructor
Application::Application()
: applicationStateManager(NULL)
{
windowElements.window = NULL;
windowElements.renderer = NULL;
}
// Destructor
Application::~Application()
{
if (applicationStateManager!=NULL) { delete applicationStateManager; }
}
// Main game loop
int Application::start()
{
if (!initialize())
{
return -1;
}
while (!applicationStateManager->isExitState())
{
fpsManager.beginFrame();
applicationStateManager->onEvent();
applicationStateManager->onUpdate();
applicationStateManager->changeState();
applicationStateManager->onRender();
fpsManager.endFrame();
}
terminate();
return 0;
}
// Initialize all modules and allocates memory to assets
bool Application::initialize()
{
// Initializes all SDL modules
if (!SDL_util::initialize())
{
printf("Could not initialize SDL: %s\n", SDL_GetError());
return false;
}
windowElements.window = SDL_CreateWindow(
"Space Shooter",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
windowElements.WINDOW_WIDTH,
windowElements.WINDOW_HEIGHT,
//SDL_WINDOW_FULLSCREEN
SDL_WINDOW_FULLSCREEN_DESKTOP
//SDL_WINDOW_SHOWN
);
if (windowElements.window == NULL)
{
printf("Could not create SDL_Window: %s\n", SDL_GetError());
return false;
}
windowElements.fullScreen = true;
windowElements.renderer = SDL_CreateRenderer(windowElements.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
if (windowElements.renderer == NULL)
{
printf("Could not create SDL_Renderer: %s\n", SDL_GetError());
return false;
}
SDL_SetRenderDrawColor(windowElements.renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderSetLogicalSize(windowElements.renderer, windowElements.WINDOW_WIDTH, windowElements.WINDOW_HEIGHT);
AudioSystem::getInstance()->initialize();
applicationStateManager = new ApplicationStateManager(&windowElements);
return true;
}
// Deinitializes all modules and free all allocated memory
void Application::terminate()
{
AudioSystem::getInstance()->terminate();
SDL_DestroyRenderer(windowElements.renderer);
windowElements.renderer = NULL;
SDL_DestroyWindow(windowElements.window);
windowElements.window = NULL;
SDL_util::terminate();
}
| 24.380165
| 131
| 0.651864
|
sujeong-choi
|
0fee3b6ddc1fde72596aa29971c5f9799cc7b734
| 9,943
|
cpp
|
C++
|
src/ariel/io/utilities.cpp
|
lymastee/gslib
|
1b165b7a812526c4b2a3179588df9a7c2ff602a6
|
[
"MIT"
] | 9
|
2016-10-18T09:40:09.000Z
|
2022-02-11T09:44:51.000Z
|
src/ariel/io/utilities.cpp
|
lymastee/gslib
|
1b165b7a812526c4b2a3179588df9a7c2ff602a6
|
[
"MIT"
] | null | null | null |
src/ariel/io/utilities.cpp
|
lymastee/gslib
|
1b165b7a812526c4b2a3179588df9a7c2ff602a6
|
[
"MIT"
] | 1
|
2016-10-19T15:20:58.000Z
|
2016-10-19T15:20:58.000Z
|
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* 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 <gslib/error.h>
#include <ariel/io/utilities.h>
#define ariel_io_blanks _t(" \t\v\r\n\f")
__ariel_begin__
bool io_bad_eof(const string& src, int32 curr)
{
if(curr < 0) {
set_error(_t("An error was already existed.\n"));
return true;
}
if(curr >= src.length()) {
set_error(_t("Unexpected end of file.\n"));
return true;
}
return false;
}
int32 io_skip_blank_charactors(const string& src, int32 start)
{
int32 p = (int32)src.find_first_not_of(ariel_io_blanks, start);
if(p == string::npos)
return src.length();
return p;
}
int32 io_read_section_name(const string& src, string& name, int32 start)
{
int32 p = (int32)src.find_first_of(ariel_io_blanks ":{", start);
if(p == string::npos)
return src.length();
if(p > start)
name.assign(src.c_str() + start, p - start);
return p;
}
int32 io_read_notation(const string& src, string& notation, int32 start)
{
int32 p = (int32)src.find_first_of(ariel_io_blanks "{", start);
if(p == string::npos)
return src.length();
if(p > start)
notation.assign(src.c_str() + start, p - start);
return p;
}
int32 io_skip_section(const string& src, int32 start)
{
int32 next = (int32)src.find_first_of(_t("{}"), start);
if(next == string::npos)
return -1;
if(src.at(next) == _t('}'))
return ++ next;
if(++ next >= src.length())
return -1;
int layercnt = 1;
for(;; ++ next) {
next = src.find_first_of(_t("{}"), start = next);
if(next == string::npos)
return -1;
switch(src.at(next))
{
case _t('{'):
layercnt ++;
break;
case _t('}'):
default:
layercnt --;
break;
}
if(!layercnt)
break;
}
assert(src.at(next) == _t('}'));
return ++ next;
}
int32 io_enter_section(const string& src, int32 start, gchar st)
{
assert(start < src.length());
if(src.at(start) == st)
return ++ start;
int32 next = io_skip_blank_charactors(src, start);
if(io_bad_eof(src, next) || src.at(next) != st)
return -1;
return ++ next;
}
int32 io_read_line_of_section(const string& src, string& line, int32 start)
{
assert(start < src.length());
int32 p = (int32)src.find_first_of(_t("\r\n}"), start);
if(io_bad_eof(src, p))
return -1;
if(src.at(p) == _t('}')) {
set_error(_t("Unexpected end of section.\n"));
return -1;
}
line.assign(src, start, p - start);
return (int32)src.find_first_not_of(_t("\r\n"), p);
}
io_binary_stream::io_binary_stream(int32 size)
{
_current = 0;
_size = size;
}
io_binary_stream::control_type io_binary_stream::read_control_type()
{
if(!next_byte_valid()) {
set_error(_t("io_binary_stream::read_control_type failed."));
return ctl_unknown;
}
byte ct1 = read_byte(), ct2;
switch(ct1)
{
case _t('#'):
return ctl_section;
case _t('$'):
return ctl_notation;
case _t('@'):
return ctl_counter;
case _t('%'):
assert(next_byte_valid());
ct2 = read_byte();
switch(ct2)
{
case _t('b'):
return ctl_byte_stream_field;
case _t('w'):
return ctl_word_stream_field;
case _t('d'):
return ctl_dword_stream_field;
case _t('q'):
return ctl_qword_stream_field;
default:
return ctl_unknown;
}
}
return ctl_unknown;
}
bool io_binary_stream::section_stack_valid(int32 bytes) const
{
if(_section_stack.empty())
return true;
for(size_t i = 0; i < _section_stack.size(); ++ i) {
int32 rest = _section_stack.at(i);
if(rest < bytes)
return false;
}
return true;
}
void io_binary_stream::take_next_n_bytes(int32 n)
{
_current += n;
assert(_current <= _size);
if(_section_stack.empty())
return;
for(int i = (int)_section_stack.size() - 1; i >= 0; i --) {
_section_stack.at(i) -= n;
assert(_section_stack.at(i) >= 0);
}
}
bool io_binary_stream::next_n_bytes_valid(int32 bytes) const
{
if(_size - _current < bytes)
return false;
return section_stack_valid(bytes);
}
void io_binary_stream::seek_to(int32 bytes)
{
seek_by(bytes - _current);
}
void io_binary_stream::seek_by(int32 bytes)
{
take_next_n_bytes(bytes);
rewind_to(_current);
}
void io_binary_stream::rewind_by(int32 bytes)
{
int32 pos = current_dev_pos();
rewind_to(pos + bytes);
}
float io_binary_stream::read_float()
{
dword dat = read_dword();
return *(float*)&dat;
}
double io_binary_stream::read_double()
{
qword dat = read_qword();
return *(double*)&dat;
}
int32 io_binary_stream::read_nstring(string& str)
{
if(!next_dword_valid()) {
set_error(_t("io_binary_stream: bad format for string.\n"));
return -1;
}
int32 size = (int32)read_dword();
if(!next_n_bytes_valid(size)) {
set_error(_t("io_binary_stream: bad format for string.\n"));
return -1;
}
str.resize(size);
read_field_to_buf(&str.front(), size);
take_next_n_bytes(size);
return size;
}
int32 io_binary_stream::read_string(string& str, const string& stopch)
{
if(stopch.empty())
return -1;
str.clear();
auto sto = current_dev_pos();
while(next_byte_valid()) {
gchar c = (gchar)read_byte();
if(stopch.find(c, 0) != string::npos) {
seek_by(-1);
return (int32)str.size();
}
str.push_back(c);
}
seek_to(sto);
return -1;
}
bool io_binary_stream::exit_section()
{
if(_section_stack.empty())
return false;
if(_section_stack.back() <= 0) {
_section_stack.pop_back();
return true;
}
return false;
}
bool io_binary_stream::skip_current_section()
{
if(_section_stack.empty())
return false;
int32 cssz = _section_stack.back();
if(cssz <= 0) {
exit_section();
return true;
}
seek_by(cssz);
verify(exit_section());
return true;
}
bool io_binary_stream::skip_next_section()
{
auto ct = read_control_type();
if(ct == ctl_notation) {
string cast;
if(read_string(cast, _t("$@")) <= 0) {
set_error(_t("skip next section failed.\n"));
return false;
}
ct = read_control_type();
}
if(ct != ctl_counter) {
set_error(_t("skip next section failed.\n"));
return false;
}
int32 sz = (int32)read_dword();
enter_section(sz);
return skip_current_section();
}
io_binary_memory::io_binary_memory(const void* ptr, int32 size):
io_binary_stream(size)
{
_mem = (const byte*)ptr;
}
byte io_binary_memory::read_byte()
{
byte r = *(_mem + _current);
take_next_n_bytes(1);
return r;
}
word io_binary_memory::read_word()
{
word r = *(word*)(_mem + _current);
take_next_n_bytes(2);
return r;
}
dword io_binary_memory::read_dword()
{
dword r = *(dword*)(_mem + _current);
take_next_n_bytes(4);
return r;
}
qword io_binary_memory::read_qword()
{
qword r = *(qword*)(_mem + _current);
take_next_n_bytes(8);
return r;
}
bool io_binary_memory::read_field_to_buf(void* ptr, int32 bytes)
{
if(!next_n_bytes_valid(bytes))
return false;
memcpy(ptr, _mem + _current, bytes);
take_next_n_bytes(bytes);
return true;
}
io_binary_file::io_binary_file(file& pf):
_file(pf), io_binary_stream(pf.size())
{
}
byte io_binary_file::read_byte()
{
byte r;
_file.get(&r, 1);
take_next_n_bytes(1);
return r;
}
word io_binary_file::read_word()
{
word r;
_file.get(&r, 1);
take_next_n_bytes(2);
return r;
}
dword io_binary_file::read_dword()
{
dword r;
_file.get(&r, 1);
take_next_n_bytes(4);
return r;
}
qword io_binary_file::read_qword()
{
qword r;
_file.get(&r, 1);
take_next_n_bytes(8);
return r;
}
bool io_binary_file::read_field_to_buf(void* ptr, int32 bytes)
{
if(!next_n_bytes_valid(bytes))
return false;
_file.get((byte*)ptr, bytes);
take_next_n_bytes(bytes);
return true;
}
__ariel_end__
| 24.795511
| 82
| 0.592276
|
lymastee
|
0fee709307fea0efda066ba6d5a3c287be83b691
| 1,158
|
cpp
|
C++
|
NewBouncePlaneDialog.cpp
|
jambolo/ConfettiMachine
|
02512f43e5a613dd972bdb06fa6a17acfc7d7ef8
|
[
"MIT"
] | null | null | null |
NewBouncePlaneDialog.cpp
|
jambolo/ConfettiMachine
|
02512f43e5a613dd972bdb06fa6a17acfc7d7ef8
|
[
"MIT"
] | null | null | null |
NewBouncePlaneDialog.cpp
|
jambolo/ConfettiMachine
|
02512f43e5a613dd972bdb06fa6a17acfc7d7ef8
|
[
"MIT"
] | null | null | null |
/********************************************************************************************************************
NewBouncePlaneDialog.cpp
Copyright 2003, John J. Bolton
--------------------------------------------------------------------------------------------------------------
$Header: //depot/ConfettiMachine/NewBouncePlaneDialog.cpp#1 $
$NoKeywords: $
********************************************************************************************************************/
#include "stdafx.h"
#include "NewBouncePlaneDialog.h"
// CNewBouncePlaneDialog dialog
IMPLEMENT_DYNAMIC(CNewBouncePlaneDialog, CDialog)
CNewBouncePlaneDialog::CNewBouncePlaneDialog(CWnd* pParent /*=NULL*/)
: CDialog(CNewBouncePlaneDialog::IDD, pParent)
, m_Name(_T(""))
{
}
CNewBouncePlaneDialog::~CNewBouncePlaneDialog()
{
}
void CNewBouncePlaneDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_NEWBOUNCEPLANE_NAME, m_Name);
}
BEGIN_MESSAGE_MAP(CNewBouncePlaneDialog, CDialog)
END_MESSAGE_MAP()
// CNewBouncePlaneDialog message handlers
| 26.318182
| 118
| 0.501727
|
jambolo
|
0fee7af9d0845c138594054cd846b8eb80e64645
| 6,072
|
cpp
|
C++
|
lib/soci/src/core/backend-loader.cpp
|
parki02/starall
|
f6c0878560a6220c44db21e2ea0cbaf1c0dd9a2f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
lib/soci/src/core/backend-loader.cpp
|
parki02/starall
|
f6c0878560a6220c44db21e2ea0cbaf1c0dd9a2f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
lib/soci/src/core/backend-loader.cpp
|
parki02/starall
|
f6c0878560a6220c44db21e2ea0cbaf1c0dd9a2f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
//
// Copyright (C) 2008 Maciej Sobczak with contributions from Artyom Tonkikh
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define SOCI_SOURCE
#include "backend-loader.h"
#include "error.h"
#include <cassert>
#include <cstdlib>
#include <map>
#include <string>
#include <vector>
#ifndef _MSC_VER
#include <stdint.h>
#endif
#include "soci_backends_config.h"
using namespace soci;
using namespace soci::dynamic_backends;
#ifdef _WIN32
#include <windows.h>
typedef CRITICAL_SECTION soci_mutex_t;
typedef HMODULE soci_handler_t;
#define LOCK(x) EnterCriticalSection(x)
#define UNLOCK(x) LeaveCriticalSection(x)
#define MUTEX_INIT(x) InitializeCriticalSection(x)
#define MUTEX_DEST(x) DeleteCriticalSection(x)
#ifdef _UNICODE
#define DLOPEN(x) LoadLibraryA(x)
#else
#define DLOPEN(x) LoadLibrary(x)
#endif
#define DLCLOSE(x) FreeLibrary(x)
#define DLSYM(x, y) GetProcAddress(x, y)
#ifdef SOCI_ABI_VERSION
#define LIBNAME(x) (SOCI_LIB_PREFIX + x + "_" SOCI_ABI_VERSION SOCI_LIB_SUFFIX)
#else
#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX)
#endif // SOCI_ABI_VERSION
#else
#include <pthread.h>
#include <dlfcn.h>
typedef pthread_mutex_t soci_mutex_t;
typedef void * soci_handler_t;
#define LOCK(x) pthread_mutex_lock(x)
#define UNLOCK(x) pthread_mutex_unlock(x)
#define MUTEX_INIT(x) pthread_mutex_init(x, NULL)
#define MUTEX_DEST(x) pthread_mutex_destroy(x)
#define DLOPEN(x) dlopen(x, RTLD_LAZY)
#define DLCLOSE(x) dlclose(x)
#define DLSYM(x, y) dlsym(x, y)
#ifdef SOCI_ABI_VERSION
#ifdef __APPLE__
#define LIBNAME(x) (SOCI_LIB_PREFIX + x + "." SOCI_ABI_VERSION SOCI_LIB_SUFFIX)
#else
#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX "." SOCI_ABI_VERSION)
#endif
#else
#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX)
#endif // SOCI_ABI_VERSION
#endif // _WIN32
namespace // unnamed
{
struct info
{
soci_handler_t handler_;
backend_factory const * factory_;
info() : handler_(0), factory_(0) {}
};
typedef std::map<std::string, info> factory_map;
factory_map factories_;
std::vector<std::string> search_paths_;
soci_mutex_t mutex_;
std::vector<std::string> get_default_paths()
{
std::vector<std::string> paths;
// TODO: may be problem with finding getenv in std namespace in Visual C++ --mloskot
char const* const penv = std::getenv("SOCI_BACKENDS_PATH");
if (0 == penv)
{
paths.push_back(".");
paths.push_back(DEFAULT_BACKENDS_PATH);
return paths;
}
std::string const env = penv;
if (env.empty())
{
paths.push_back(".");
paths.push_back(DEFAULT_BACKENDS_PATH);
return paths;
}
std::string::size_type searchFrom = 0;
while (searchFrom != env.size())
{
std::string::size_type const found = env.find(":", searchFrom);
if (found == searchFrom)
{
++searchFrom;
}
else if (std::string::npos != found)
{
std::string const path(env.substr(searchFrom, found - searchFrom));
paths.push_back(path);
searchFrom = found + 1;
}
else // found == npos
{
std::string const path = env.substr(searchFrom);
paths.push_back(path);
searchFrom = env.size();
}
}
return paths;
}
// used to automatically initialize the global state
struct static_state_mgr
{
static_state_mgr()
{
MUTEX_INIT(&mutex_);
search_paths_ = get_default_paths();
}
~static_state_mgr()
{
unload_all();
MUTEX_DEST(&mutex_);
}
} static_state_mgr_;
class scoped_lock
{
public:
scoped_lock(soci_mutex_t * m) : mptr(m) { LOCK(m); };
~scoped_lock() { UNLOCK(mptr); };
private:
soci_mutex_t * mptr;
};
// non-synchronized helper for the other functions
void do_unload(std::string const & name)
{
// Starall-core customization: no dynamic loading of backends.
}
// non-synchronized helper
void do_register_backend(std::string const & name, std::string const & shared_object)
{
// Starall-core customization: no dynamic loading of backends.
throw soci_error("Failed to find shared library for backend " + name);
}
} // unnamed namespace
backend_factory const& dynamic_backends::get(std::string const& name)
{
scoped_lock lock(&mutex_);
factory_map::iterator i = factories_.find(name);
if (i != factories_.end())
{
return *(i->second.factory_);
}
// no backend found with this name, try to register it first
do_register_backend(name, std::string());
// second attempt, must succeed (the backend is already loaded)
i = factories_.find(name);
assert(i != factories_.end());
return *(i->second.factory_);
}
SOCI_DECL std::vector<std::string>& search_paths()
{
return search_paths_;
}
SOCI_DECL void dynamic_backends::register_backend(
std::string const& name, std::string const& shared_object)
{
scoped_lock lock(&mutex_);
do_register_backend(name, shared_object);
}
SOCI_DECL void dynamic_backends::register_backend(
std::string const& name, backend_factory const& factory)
{
scoped_lock lock(&mutex_);
// unload the existing handler if it's already loaded
do_unload(name);
info new_entry;
new_entry.factory_ = &factory;
factories_[name] = new_entry;
}
SOCI_DECL std::vector<std::string> dynamic_backends::list_all()
{
scoped_lock lock(&mutex_);
std::vector<std::string> ret;
ret.reserve(factories_.size());
for (factory_map::iterator i = factories_.begin(); i != factories_.end(); ++i)
{
std::string const& name = i->first;
ret.push_back(name);
}
return ret;
}
SOCI_DECL void dynamic_backends::unload(std::string const& name)
{
scoped_lock lock(&mutex_);
do_unload(name);
}
SOCI_DECL void dynamic_backends::unload_all()
{
// Starall-core customization: no dynamic loading of backends.
factories_.clear();
}
| 22.656716
| 88
| 0.680665
|
parki02
|
0feee6d7048015ab85b009c166744f834938db73
| 3,122
|
cpp
|
C++
|
lib/IRremoteESP8266/src/ir_Teknopoint.cpp
|
Eliauk-Forever/JARVIS
|
69569e530f0bc66c90bc2ba2a266edb65006bd6f
|
[
"MulanPSL-1.0"
] | 14
|
2019-07-09T09:38:59.000Z
|
2022-02-11T13:57:18.000Z
|
lib/IRremoteESP8266/src/ir_Teknopoint.cpp
|
Eliauk-Forever/JARVIS
|
69569e530f0bc66c90bc2ba2a266edb65006bd6f
|
[
"MulanPSL-1.0"
] | null | null | null |
lib/IRremoteESP8266/src/ir_Teknopoint.cpp
|
Eliauk-Forever/JARVIS
|
69569e530f0bc66c90bc2ba2a266edb65006bd6f
|
[
"MulanPSL-1.0"
] | 1
|
2021-06-26T22:26:58.000Z
|
2021-06-26T22:26:58.000Z
|
// Copyright 2021 David Conran (crankyoldgit)
/// @file
/// @brief Support for the Teknopoint protocol
/// @see https://github.com/crankyoldgit/IRremoteESP8266/issues/1486
// Supports:
// Brand: Teknopoint, Model: Allegro SSA-09H A/C
// Brand: Teknopoint, Model: GZ-055B-E1 remote
#include "IRrecv.h"
#include "IRsend.h"
#include "IRutils.h"
// Protocol timings
const uint16_t kTeknopointHdrMark = 3600;
const uint16_t kTeknopointBitMark = 477;
const uint16_t kTeknopointHdrSpace = 1600;
const uint16_t kTeknopointOneSpace = 1200;
const uint16_t kTeknopointZeroSpace = 530;
const uint16_t kTeknopointFreq = 38000; // Hz. (Guess Only)
const uint8_t kTeknopointExtraTol = 10; // Extra tolerance percentage.
#if SEND_TEKNOPOINT
/// Send a Teknopoint formatted message.
/// Status: BETA / Probably works.
/// @param[in] data An array of bytes containing the IR command.
/// @param[in] nbytes Nr. of bytes of data in the array.
/// @param[in] repeat Nr. of times the message is to be repeated.
void IRsend::sendTeknopoint(const uint8_t data[], const uint16_t nbytes,
const uint16_t repeat) {
sendGeneric(kTeknopointHdrMark, kTeknopointHdrSpace,
kTeknopointBitMark, kTeknopointOneSpace,
kTeknopointBitMark, kTeknopointZeroSpace,
kTeknopointBitMark, kDefaultMessageGap,
data, nbytes, // Bytes
kTeknopointFreq, false, repeat, kDutyDefault);
}
#endif // SEND_TEKNOPOINT
#if DECODE_TEKNOPOINT
/// Decode the supplied Teknopoint message.
/// Status: Alpha / Probably works.
/// @param[in,out] results Ptr to the data to decode & where to store the decode
/// @param[in] offset The starting index to use when attempting to decode the
/// raw data. Typically/Defaults to kStartOffset.
/// @param[in] nbits The number of data bits to expect.
/// @param[in] strict Flag indicating if we should perform strict matching.
/// @return A boolean. True if it can decode it, false if it can't.
bool IRrecv::decodeTeknopoint(decode_results *results, uint16_t offset,
const uint16_t nbits, const bool strict) {
if (results->rawlen < 2 * nbits + kHeader + kFooter - 1 - offset)
return false; // Too short a message to match.
if (strict && nbits != kTeknopointBits)
return false;
if (!matchGeneric(results->rawbuf + offset, results->state,
results->rawlen - offset, nbits,
kTeknopointHdrMark, kTeknopointHdrSpace,
kTeknopointBitMark, kTeknopointOneSpace,
kTeknopointBitMark, kTeknopointZeroSpace,
kTeknopointBitMark, kDefaultMessageGap,
true, _tolerance + kTeknopointExtraTol,
kMarkExcess, false)) return false;
// Compliance
if (strict) {
// Is the checksum valid?
if (sumBytes(results->state, kTeknopointStateLength - 1) !=
results->state[kTeknopointStateLength - 1]) return false;
}
// Success
results->decode_type = decode_type_t::TEKNOPOINT;
results->bits = nbits;
return true;
}
#endif // DECODE_TEKNOPOINT
| 41.078947
| 80
| 0.685138
|
Eliauk-Forever
|
0fefa0d67ed2b46aa836549ed299f74f99151e89
| 4,142
|
cpp
|
C++
|
problems_001-050/euler_49.cpp
|
sedihub/project_euler
|
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
|
[
"Apache-2.0"
] | null | null | null |
problems_001-050/euler_49.cpp
|
sedihub/project_euler
|
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
|
[
"Apache-2.0"
] | null | null | null |
problems_001-050/euler_49.cpp
|
sedihub/project_euler
|
2d7d40ee67a1e0402aa68e78a5f7d7cf18221db5
|
[
"Apache-2.0"
] | null | null | null |
/*
PROBLEM:
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is
unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this
property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
SOLUTION:
Here's the idea: I will break down the search for four-digit primes with this property into
several steps:
1. find all four-digit primes. The result will be ordered as we find them in order.
2. group them by their digits using a `std::map`: keys are sorted vectors of digits and values
are the primes composed of the digits in the map keys. Since 1 was sorted, this values in
this map will be sorted.
3. consider only groups with more than four four-digit primes.
4. Check which ones satisfy the equidistance criterion. It's particularly easy for the cases
with four primes. For more than four,
ANSWER: 2969-6299-9629
1487, 4817, 8147
1487 1847 4817 4871 7481 7841 8147 8741
2969, 6299, 9629
2699 2969 6299 9629
**/
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
typedef unsigned int uint;
bool is_prime(uint n)
{
if (n == 2) return true;
else if (n % 2 == 0) return false;
else if (n == 3) return true;
else if (n % 3 == 0) return false;
else if (n == 5) return true;
else if (n % 5 == 0) return false;
else if (n == 7) return true;
else if (n == 11) return true;
else if (n == 13) return true;
else if (n == 17) return true;
else if (n == 19) return true;
uint k = 6;
while (k * k <= n) {
if (n % (k + 1) == 0) return false;
if (n % (k + 5) == 0) return false;
k += 6;
}
return true;
}
std::vector<uint> find_four_digit_primes()
{
std::vector<uint> primes;
for (uint n = 1002; n <= 9994; n += 6) { // 1002 = 6 * 167
if (is_prime(n + 1)) primes.push_back(n + 1);
if (is_prime(n + 5)) primes.push_back(n + 5);
}
return primes;
}
std::map<std::vector<uint>, std::vector<uint> > group_by_digits(
const std::vector<uint> &nums)
{
std::map<std::vector<uint>, std::vector<uint> > groups;
std::vector<uint>::const_iterator it;
std::vector<uint> digits;
uint temp;
for (it = nums.begin(); it != nums.end(); it++) {
digits.clear();
temp = *it;
while (temp > 0) {
digits.push_back(temp % 10);
temp /= 10;
}
std::sort(digits.begin(), digits.end());
if (groups.find(digits) == groups.end()){
groups[std::vector<uint>(digits)] = std::vector<uint>{*it};
}
else{
groups[digits].push_back(*it);
}
}
return groups;
}
bool contains_equidistance_subset_of_three(std::vector<uint> &vec, bool print=true)
{
uint last_elem;
for (uint i = 0; i < vec.size() - 2; i++) { // the index of the first one:
for (uint j = i+1; j < vec.size() - 1; j++) {
last_elem = 2 * vec[j] - vec[i];
if (std::find(vec.begin()+j, vec.end(), last_elem) != vec.end()) {
if (print)
std::cout << vec[i] << ", " << vec[j] << ", " << last_elem << std::endl;
return true;
}
}
}
return false;
}
int main()
{
// Find four-digit primes:
std::vector<uint> four_digit_primes = find_four_digit_primes();
std::vector<uint>::iterator it;
// Group them by digits:
std::map<std::vector<uint>, std::vector<uint> > groups = group_by_digits(four_digit_primes);
// Find the groups that satisfy the equidistance criteria:
std::map<std::vector<uint>, std::vector<uint> >::iterator mit;
for (mit = groups.begin(); mit != groups.end(); mit++) {
if ((mit->second).size() < 3) {
continue;
}
// Finds the suitable ones and prints them.
if (contains_equidistance_subset_of_three(mit->second)) {
for (it = (mit->second).begin(); it != (mit->second).end(); it++ )
std::cout << *it << "\t";
std::cout << std::endl;
}
}
return 0;
}
| 27.071895
| 97
| 0.616127
|
sedihub
|
0ff0341df5e7ab8411a839c766e4bd49632a0edc
| 2,337
|
cpp
|
C++
|
engine/modules/video/video_player.cpp
|
Texas-C/echo
|
486acc57c9149363206a2367c865a2ccbac69975
|
[
"MIT"
] | null | null | null |
engine/modules/video/video_player.cpp
|
Texas-C/echo
|
486acc57c9149363206a2367c865a2ccbac69975
|
[
"MIT"
] | null | null | null |
engine/modules/video/video_player.cpp
|
Texas-C/echo
|
486acc57c9149363206a2367c865a2ccbac69975
|
[
"MIT"
] | null | null | null |
#include "video_player.h"
#include "engine/core/main/Engine.h"
#include "engine/core/io/IO.h"
namespace Echo
{
VideoPlayer::VideoPlayer()
{
}
VideoPlayer::~VideoPlayer()
{
}
void VideoPlayer::bindMethods()
{
CLASS_BIND_METHOD(VideoPlayer, is2d, DEF_METHOD("is2d"));
CLASS_BIND_METHOD(VideoPlayer, set2d, DEF_METHOD("set2d"));
CLASS_BIND_METHOD(VideoPlayer, isLoop, DEF_METHOD("isLoop"));
CLASS_BIND_METHOD(VideoPlayer, setLoop, DEF_METHOD("setLoop"));
CLASS_BIND_METHOD(VideoPlayer, isPlayOnAwake, DEF_METHOD("isPlayOnAwake"));
CLASS_BIND_METHOD(VideoPlayer, setPlayOnAwake, DEF_METHOD("setPlayOnAwake"));
CLASS_BIND_METHOD(VideoPlayer, getVideo, DEF_METHOD("getVideo"));
CLASS_BIND_METHOD(VideoPlayer, setVideo, DEF_METHOD("setVideo"));
CLASS_REGISTER_PROPERTY(VideoPlayer, "Is2D", Variant::Type::Bool, "is2d", "set2d");
CLASS_REGISTER_PROPERTY(VideoPlayer, "Loop", Variant::Type::Bool, "isLoop", "setLoop");
CLASS_REGISTER_PROPERTY(VideoPlayer, "PlayOnAwake", Variant::Type::Bool, "isPlayOnAwake", "setPlayOnAwake");
CLASS_REGISTER_PROPERTY(VideoPlayer, "Volume", Variant::Type::Real, "getVolume", "setVolume");
CLASS_REGISTER_PROPERTY(VideoPlayer, "Video", Variant::Type::ResourcePath, "getVideo", "setVideo");
}
void VideoPlayer::setLoop(bool loop)
{
m_isLoop = loop;
}
void VideoPlayer::set2d(bool is2d)
{
m_is2D = is2d;
}
bool VideoPlayer::isPlaying()
{
return false;
}
void VideoPlayer::start()
{
if (m_isPlayOnAwake && IsGame)
{
play();
}
}
void VideoPlayer::updateInternal(float elapsedTime)
{
const Vector3& position = getWorldPosition();
// update self position
updatePosition(position);
}
void VideoPlayer::updatePosition(const Vector3& position)
{
}
void VideoPlayer::play()
{
if (m_isCustomRender)
{
m_videoRender = nullptr;
}
m_jplayer = EchoNew(cmpeg::player(m_videoRender, m_videoRes.getPath().c_str()));
m_jplayer->play();
}
void VideoPlayer::pause()
{
}
void VideoPlayer::stop()
{
}
void VideoPlayer::setVideo(const ResourcePath& res)
{
m_videoRes=res;
}
}
| 24.6
| 116
| 0.646983
|
Texas-C
|
0ff1882551a7cefb0ab48cd5f104c3b76da45c58
| 5,073
|
cpp
|
C++
|
src/tests/q_tech_ind/main.cpp
|
gtaifu/CACTUS
|
a05f47423ac37b14989ec38c525741ec597b4826
|
[
"Apache-2.0"
] | 8
|
2020-01-04T06:40:13.000Z
|
2020-12-04T19:29:02.000Z
|
src/tests/q_tech_ind/main.cpp
|
gtaifu/CACTUS
|
a05f47423ac37b14989ec38c525741ec597b4826
|
[
"Apache-2.0"
] | null | null | null |
src/tests/q_tech_ind/main.cpp
|
gtaifu/CACTUS
|
a05f47423ac37b14989ec38c525741ec597b4826
|
[
"Apache-2.0"
] | 1
|
2021-07-05T02:14:05.000Z
|
2021-07-05T02:14:05.000Z
|
#include <iostream>
#include <systemc>
#include "global_json.h"
#include "instruction_generator.h"
#include "q_data_type.h"
#include "q_decoder.h"
#include "q_tech_ind.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
using cactus::config_reader;
using namespace cactus;
using namespace sc_core;
using sc_core::sc_in;
using sc_core::sc_out;
using sc_dt::sc_uint;
void config();
int sc_main(int argc, char* argv[]) {
auto telf_logger = safe_create_logger("telf_logger", CODE_POSITION); // used for telf_module
auto console_logger =
safe_create_logger("console", CODE_POSITION); // used for terminal console
spdlog::set_level(spdlog::level::trace); // Set global log level to info
sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING);
config();
// clock
sc_clock clock("my_clock", 1, sc_core::SC_NS);
// instance sub modules
Instruction_generator insn_stimu("Insn_stimulus");
Q_tech_ind q_tech_ind("Q_tech_ind");
// signals between modules
sc_signal<Qasm_instruction> bundle;
sc_signal<bool> valid;
sc_signal<sc_uint<32>> rs_wait_time;
sc_signal<Q_pipe_interface> out_tech_ind_q_pipe_interface;
sc_signal<Generic_meas_if> meas_issue;
sc_signal<bool> reset;
// ------------------------------------------------------------------------------------------
// stimulator
// ------------------------------------------------------------------------------------------
// input
insn_stimu.in_clock(clock);
// interface to q_tech_ind
insn_stimu.out_bundle(bundle);
insn_stimu.out_valid(valid);
insn_stimu.out_rs_wait_time(rs_wait_time);
// ------------------------------------------------------------------------------------------
// q_tech_ind
// ------------------------------------------------------------------------------------------
// input
q_tech_ind.in_clock(clock);
q_tech_ind.in_bundle(bundle);
q_tech_ind.in_valid_bundle(valid);
q_tech_ind.in_rs_wait_time(rs_wait_time);
q_tech_ind.reset(reset);
// output
q_tech_ind.out_q_pipe_interface(out_tech_ind_q_pipe_interface);
q_tech_ind.out_Qp2MRF_meas_issue(meas_issue);
// run test
reset.write(false);
for (unsigned int i = 0; i < 300; ++i) {
sc_start(1.0, sc_core::SC_NS);
}
sc_stop();
return 0;
}
void config() {
// The list of all the edges whose right qubit is i.
std::vector<std::vector<unsigned int>> in_edges_of_qubit;
// The list of all the edges whose left qubit is i.
std::vector<std::vector<unsigned int>> out_edges_of_qubit;
unsigned int left_qubit = 0;
unsigned int right_qubit = 0;
unsigned int num_directed_edges = 16;
in_edges_of_qubit.resize(num_directed_edges);
out_edges_of_qubit.resize(num_directed_edges);
for (size_t i = 0; i < in_edges_of_qubit.size(); ++i) {
in_edges_of_qubit[i].clear();
out_edges_of_qubit[i].clear();
}
std::vector<std::pair<int, int>> directed_edges;
directed_edges.push_back(std::make_pair(2, 0));
directed_edges.push_back(std::make_pair(0, 3));
directed_edges.push_back(std::make_pair(3, 1));
directed_edges.push_back(std::make_pair(1, 4));
directed_edges.push_back(std::make_pair(2, 5));
directed_edges.push_back(std::make_pair(5, 3));
directed_edges.push_back(std::make_pair(3, 6));
directed_edges.push_back(std::make_pair(6, 4));
directed_edges.push_back(std::make_pair(0, 2));
directed_edges.push_back(std::make_pair(3, 0));
directed_edges.push_back(std::make_pair(1, 3));
directed_edges.push_back(std::make_pair(4, 1));
directed_edges.push_back(std::make_pair(5, 2));
directed_edges.push_back(std::make_pair(3, 5));
directed_edges.push_back(std::make_pair(6, 3));
directed_edges.push_back(std::make_pair(4, 6));
for (size_t i = 0; i < num_directed_edges; i++) {
left_qubit = directed_edges[i].first;
right_qubit = directed_edges[i].second;
out_edges_of_qubit[left_qubit].push_back(static_cast<unsigned int>(i));
in_edges_of_qubit[right_qubit].push_back(static_cast<unsigned int>(i));
}
Global_config& global_config = Global_config::get_instance();
global_config.output_dir = "./sim_output";
// global_config.output_dir = "D:/ihub/qarchsim/vsbuild/sim_output/";
global_config.num_qubits = 7;
global_config.vliw_width = 2;
global_config.in_edges_of_qubit = in_edges_of_qubit;
global_config.out_edges_of_qubit = out_edges_of_qubit;
global_config.instruction_type = Instruction_type::BIN;
global_config.qisa_asm_fn = "../src/tests/q_tech_ind/quantum_prog";
create_dir_if_not_exist(global_config.output_dir);
if (global_config.instruction_type != Instruction_type::BIN) {
auto asm_logger =
safe_create_logger("asm_logger", CODE_POSITION); // used for terminal console
}
}
| 34.277027
| 97
| 0.642224
|
gtaifu
|
0ff37a888340fea492799711ec7d7f934edf0fab
| 46,512
|
cc
|
C++
|
src/simutrans/tool/simmenu.cc
|
Varkalandar/simutrans
|
894ab5b9ebd2106fde698d36d5daa3d267624d83
|
[
"Artistic-1.0"
] | null | null | null |
src/simutrans/tool/simmenu.cc
|
Varkalandar/simutrans
|
894ab5b9ebd2106fde698d36d5daa3d267624d83
|
[
"Artistic-1.0"
] | null | null | null |
src/simutrans/tool/simmenu.cc
|
Varkalandar/simutrans
|
894ab5b9ebd2106fde698d36d5daa3d267624d83
|
[
"Artistic-1.0"
] | null | null | null |
/*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include <string>
#include <algorithm>
#include "../utils/unicode.h"
#include "../simevent.h"
#include "../world/simworld.h"
#include "../gui/simwin.h"
#include "../player/simplay.h"
#include "../tool/simmenu.h"
#include "../tool/simtool.h"
#include "../tool/simtool-dialogs.h"
#include "../tool/simtool-scripted.h"
#include "../simskin.h"
#include "../simsound.h"
#include "../builder/hausbauer.h"
#include "../builder/wegbauer.h"
#include "../builder/brueckenbauer.h"
#include "../builder/tunnelbauer.h"
#include "../script/script_tool_manager.h"
#include "../descriptor/building_desc.h"
#include "../descriptor/bridge_desc.h"
#include "../descriptor/tunnel_desc.h"
#include "../ground/grund.h"
#include "../obj/way/strasse.h"
#include "../dataobj/environment.h"
#include "../dataobj/tabfile.h"
#include "../dataobj/scenario.h"
#include "../obj/roadsign.h"
#include "../obj/wayobj.h"
#include "../obj/zeiger.h"
#include "../gui/tool_selector.h"
#include "../utils/simstring.h"
#include "../network/memory_rw.h"
karte_ptr_t tool_t::welt;
// for key lookup; is always sorted during the game
vector_tpl<tool_t *>tool_t::char_to_tool(0);
// here are the default values, icons, cursor, sound definitions ...
vector_tpl<tool_t *>tool_t::general_tool(GENERAL_TOOL_COUNT);
vector_tpl<tool_t *>tool_t::simple_tool(SIMPLE_TOOL_COUNT);
vector_tpl<tool_t *>tool_t::dialog_tool(DIALOGE_TOOL_COUNT);
// the number of toolbars is not know yet
vector_tpl<toolbar_t *>tool_t::toolbar_tool(0);
char tool_t::toolstr[1024];
toolbar_last_used_t *toolbar_last_used_t::last_used_tools = NULL;
const char *tool_t::id_to_string(uint16 id)
{
#define CASE_TO_STRING(entry) case entry: return #entry
if (id & GENERAL_TOOL) {
switch (id & ~GENERAL_TOOL) {
CASE_TO_STRING(TOOL_QUERY);
CASE_TO_STRING(TOOL_REMOVER);
CASE_TO_STRING(TOOL_RAISE_LAND);
CASE_TO_STRING(TOOL_LOWER_LAND);
CASE_TO_STRING(TOOL_SETSLOPE);
CASE_TO_STRING(TOOL_RESTORESLOPE);
CASE_TO_STRING(TOOL_MARKER);
CASE_TO_STRING(TOOL_CLEAR_RESERVATION);
CASE_TO_STRING(TOOL_TRANSFORMER);
CASE_TO_STRING(TOOL_ADD_CITY);
CASE_TO_STRING(TOOL_CHANGE_CITY_SIZE);
CASE_TO_STRING(TOOL_PLANT_TREE);
CASE_TO_STRING(TOOL_SCHEDULE_ADD);
CASE_TO_STRING(TOOL_SCHEDULE_INS);
CASE_TO_STRING(TOOL_BUILD_WAY);
CASE_TO_STRING(TOOL_BUILD_BRIDGE);
CASE_TO_STRING(TOOL_BUILD_TUNNEL);
CASE_TO_STRING(TOOL_WAYREMOVER);
CASE_TO_STRING(TOOL_BUILD_WAYOBJ);
CASE_TO_STRING(TOOL_BUILD_STATION);
CASE_TO_STRING(TOOL_BUILD_ROADSIGN);
CASE_TO_STRING(TOOL_BUILD_DEPOT);
CASE_TO_STRING(TOOL_BUILD_HOUSE);
CASE_TO_STRING(TOOL_BUILD_LAND_CHAIN);
CASE_TO_STRING(TOOL_CITY_CHAIN);
CASE_TO_STRING(TOOL_BUILD_FACTORY);
CASE_TO_STRING(TOOL_LINK_FACTORY);
CASE_TO_STRING(TOOL_HEADQUARTER);
CASE_TO_STRING(TOOL_LOCK_GAME);
CASE_TO_STRING(TOOL_ADD_CITYCAR);
CASE_TO_STRING(TOOL_FOREST);
CASE_TO_STRING(TOOL_STOP_MOVER);
CASE_TO_STRING(TOOL_MAKE_STOP_PUBLIC);
CASE_TO_STRING(TOOL_REMOVE_WAYOBJ);
CASE_TO_STRING(TOOL_SLICED_AND_UNDERGROUND_VIEW);
CASE_TO_STRING(TOOL_BUY_HOUSE);
CASE_TO_STRING(TOOL_BUILD_CITYROAD);
CASE_TO_STRING(TOOL_ERROR_MESSAGE);
CASE_TO_STRING(TOOL_CHANGE_WATER_HEIGHT);
CASE_TO_STRING(TOOL_SET_CLIMATE);
CASE_TO_STRING(TOOL_ROTATE_BUILDING);
CASE_TO_STRING(TOOL_MERGE_STOP);
CASE_TO_STRING(TOOL_EXEC_SCRIPT);
CASE_TO_STRING(TOOL_EXEC_TWO_CLICK_SCRIPT);
CASE_TO_STRING(TOOL_PLANT_GROUNDOBJ);
CASE_TO_STRING(TOOL_ADD_MESSAGE);
}
}
else if (id & SIMPLE_TOOL) {
switch (id & ~SIMPLE_TOOL) {
CASE_TO_STRING(TOOL_PAUSE);
CASE_TO_STRING(TOOL_FASTFORWARD);
CASE_TO_STRING(TOOL_SCREENSHOT);
CASE_TO_STRING(TOOL_INCREASE_INDUSTRY);
CASE_TO_STRING(TOOL_UNDO);
CASE_TO_STRING(TOOL_SWITCH_PLAYER);
CASE_TO_STRING(TOOL_STEP_YEAR);
CASE_TO_STRING(TOOL_CHANGE_GAME_SPEED);
CASE_TO_STRING(TOOL_ZOOM_IN);
CASE_TO_STRING(TOOL_ZOOM_OUT);
CASE_TO_STRING(TOOL_SHOW_COVERAGE);
CASE_TO_STRING(TOOL_SHOW_NAME);
CASE_TO_STRING(TOOL_SHOW_GRID);
CASE_TO_STRING(TOOL_SHOW_TREES);
CASE_TO_STRING(TOOL_SHOW_HOUSES);
CASE_TO_STRING(TOOL_SHOW_UNDERGROUND);
CASE_TO_STRING(TOOL_ROTATE90);
CASE_TO_STRING(TOOL_QUIT);
CASE_TO_STRING(TOOL_FILL_TREES);
CASE_TO_STRING(TOOL_DAYNIGHT_LEVEL);
CASE_TO_STRING(TOOL_VEHICLE_TOOLTIPS);
CASE_TO_STRING(TOOL_TOOGLE_PAX);
CASE_TO_STRING(TOOL_TOOGLE_PEDESTRIANS);
CASE_TO_STRING(TOOL_TRAFFIC_LEVEL);
CASE_TO_STRING(TOOL_CHANGE_CONVOI);
CASE_TO_STRING(TOOL_CHANGE_LINE);
CASE_TO_STRING(TOOL_CHANGE_DEPOT);
CASE_TO_STRING(TOOL_CHANGE_PLAYER);
CASE_TO_STRING(TOOL_CHANGE_TRAFFIC_LIGHT);
CASE_TO_STRING(TOOL_CHANGE_CITY);
CASE_TO_STRING(TOOL_RENAME);
CASE_TO_STRING(TOOL_TOGGLE_RESERVATION);
CASE_TO_STRING(TOOL_VIEW_OWNER);
CASE_TO_STRING(TOOL_HIDE_UNDER_CURSOR);
CASE_TO_STRING(TOOL_MOVE_MAP);
CASE_TO_STRING(TOOL_ROLLUP_ALL_WIN);
CASE_TO_STRING(TOOL_RECOLOUR_TOOL);
CASE_TO_STRING(UNUSED_TOOL_ADD_MESSAGE);
CASE_TO_STRING(UNUSED_WKZ_PWDHASH_TOOL);
}
}
else if (id & DIALOGE_TOOL) {
switch (id & ~DIALOGE_TOOL) {
CASE_TO_STRING(DIALOG_HELP);
CASE_TO_STRING(DIALOG_OPTIONS);
CASE_TO_STRING(DIALOG_MINIMAP);
CASE_TO_STRING(DIALOG_LINEOVERVIEW);
CASE_TO_STRING(DIALOG_MESSAGES);
CASE_TO_STRING(DIALOG_FINANCES);
CASE_TO_STRING(DIALOG_PLAYERS);
CASE_TO_STRING(DIALOG_DISPLAYOPTIONS);
CASE_TO_STRING(DIALOG_SOUND);
CASE_TO_STRING(DIALOG_LANGUAGE);
CASE_TO_STRING(DIALOG_PLAYERCOLOR);
CASE_TO_STRING(DIALOG_JUMP);
CASE_TO_STRING(DIALOG_LOAD);
CASE_TO_STRING(DIALOG_SAVE);
CASE_TO_STRING(DIALOG_LIST_HALT);
CASE_TO_STRING(DIALOG_LIST_CONVOI);
CASE_TO_STRING(DIALOG_LIST_TOWN);
CASE_TO_STRING(DIALOG_LIST_GOODS);
CASE_TO_STRING(DIALOG_LIST_FACTORY);
CASE_TO_STRING(DIALOG_LIST_CURIOSITY);
CASE_TO_STRING(DIALOG_EDIT_FACTORY);
CASE_TO_STRING(DIALOG_EDIT_ATTRACTION);
CASE_TO_STRING(DIALOG_EDIT_HOUSE);
CASE_TO_STRING(DIALOG_EDIT_TREE);
CASE_TO_STRING(DIALOG_ENLARGE_MAP);
CASE_TO_STRING(DIALOG_LIST_LABEL);
CASE_TO_STRING(DIALOG_CLIMATES);
CASE_TO_STRING(DIALOG_SETTINGS);
CASE_TO_STRING(DIALOG_GAMEINFO);
CASE_TO_STRING(DIALOG_THEMES);
CASE_TO_STRING(DIALOG_SCENARIO);
CASE_TO_STRING(DIALOG_SCENARIO_INFO);
CASE_TO_STRING(DIALOG_LIST_DEPOT);
CASE_TO_STRING(DIALOG_LIST_VEHICLE);
CASE_TO_STRING(DIALOG_SCRIPT_TOOL);
CASE_TO_STRING(DIALOG_EDIT_GROUNDOBJ);
}
}
return "<unknown tool>";
}
// separator in toolbars
class tool_dummy_t : public tool_t {
public:
tool_dummy_t() : tool_t(dummy_id) {}
bool init(player_t*) OVERRIDE { return false; }
bool is_init_network_safe() const OVERRIDE { return true; }
bool is_work_network_safe() const OVERRIDE { return true; }
bool is_move_network_safe(player_t*) const OVERRIDE { return true; }
};
tool_t *tool_t::dummy = new tool_dummy_t();
tool_t *create_general_tool(int toolnr)
{
tool_t* tool = NULL;
switch(toolnr) {
case TOOL_QUERY: tool = new tool_query_t(); break;
case TOOL_REMOVER: tool = new tool_remover_t(); break;
case TOOL_RAISE_LAND: tool = new tool_raise_t(); break;
case TOOL_LOWER_LAND: tool = new tool_lower_t(); break;
case TOOL_SETSLOPE: tool = new tool_setslope_t(); break;
case TOOL_RESTORESLOPE: tool = new tool_restoreslope_t(); break;
case TOOL_MARKER: tool = new tool_marker_t(); break;
case TOOL_CLEAR_RESERVATION: tool = new tool_clear_reservation_t(); break;
case TOOL_TRANSFORMER: tool = new tool_transformer_t(); break;
case TOOL_ADD_CITY: tool = new tool_add_city_t(); break;
case TOOL_CHANGE_CITY_SIZE: tool = new tool_change_city_size_t(); break;
case TOOL_PLANT_TREE: tool = new tool_plant_tree_t(); break;
case TOOL_SCHEDULE_ADD: tool = new tool_schedule_add_t(); break;
case TOOL_SCHEDULE_INS: tool = new tool_schedule_ins_t(); break;
case TOOL_BUILD_WAY: tool = new tool_build_way_t(); break;
case TOOL_BUILD_BRIDGE: tool = new tool_build_bridge_t(); break;
case TOOL_BUILD_TUNNEL: tool = new tool_build_tunnel_t(); break;
case TOOL_WAYREMOVER: tool = new tool_wayremover_t(); break;
case TOOL_BUILD_WAYOBJ: tool = new tool_build_wayobj_t(); break;
case TOOL_BUILD_STATION: tool = new tool_build_station_t(); break;
case TOOL_BUILD_ROADSIGN: tool = new tool_build_roadsign_t(); break;
case TOOL_BUILD_DEPOT: tool = new tool_build_depot_t(); break;
case TOOL_BUILD_HOUSE: tool = new tool_build_house_t(); break;
case TOOL_BUILD_LAND_CHAIN: tool = new tool_build_land_chain_t(); break;
case TOOL_CITY_CHAIN: tool = new tool_city_chain_t(); break;
case TOOL_BUILD_FACTORY: tool = new tool_build_factory_t(); break;
case TOOL_LINK_FACTORY: tool = new tool_link_factory_t(); break;
case TOOL_HEADQUARTER: tool = new tool_headquarter_t(); break;
case TOOL_LOCK_GAME: tool = new tool_lock_game_t(); break;
case TOOL_ADD_CITYCAR: tool = new tool_add_citycar_t(); break;
case TOOL_FOREST: tool = new tool_forest_t(); break;
case TOOL_STOP_MOVER: tool = new tool_stop_mover_t(); break;
case TOOL_MAKE_STOP_PUBLIC: tool = new tool_make_stop_public_t(); break;
case TOOL_REMOVE_WAYOBJ: tool = new tool_remove_wayobj_t(); break;
case TOOL_SLICED_AND_UNDERGROUND_VIEW: tool = new tool_show_underground_t(); break;
case TOOL_BUY_HOUSE: tool = new tool_buy_house_t(); break;
case TOOL_BUILD_CITYROAD: tool = new tool_build_cityroad(); break;
case TOOL_ERROR_MESSAGE: tool = new tool_error_message_t(); break;
case TOOL_CHANGE_WATER_HEIGHT: tool = new tool_change_water_height_t(); break;
case TOOL_SET_CLIMATE: tool = new tool_set_climate_t(); break;
case TOOL_ROTATE_BUILDING: tool = new tool_rotate_building_t(); break;
case TOOL_MERGE_STOP: tool = new tool_merge_stop_t(); break;
case TOOL_EXEC_SCRIPT: tool = new tool_exec_script_t(); break;
case TOOL_EXEC_TWO_CLICK_SCRIPT: tool = new tool_exec_two_click_script_t(); break;
case TOOL_PLANT_GROUNDOBJ: tool = new tool_plant_groundobj_t(); break;
case TOOL_ADD_MESSAGE: tool = new tool_add_message_t(); break;
default:
dbg->error("create_general_tool()","cannot satisfy request for general_tool[%i]!",toolnr);
return NULL;
}
// check for right id (exception: TOOL_SLICED_AND_UNDERGROUND_VIEW)
assert(tool->get_id() == (toolnr | GENERAL_TOOL) || toolnr==TOOL_SLICED_AND_UNDERGROUND_VIEW);
return tool;
}
tool_t *create_simple_tool(int toolnr)
{
tool_t* tool = NULL;
switch(toolnr) {
case TOOL_PAUSE: tool = new tool_pause_t(); break;
case TOOL_FASTFORWARD: tool = new tool_fastforward_t(); break;
case TOOL_SCREENSHOT: tool = new tool_screenshot_t(); break;
case TOOL_INCREASE_INDUSTRY: tool = new tool_increase_industry_t(); break;
case TOOL_UNDO: tool = new tool_undo_t(); break;
case TOOL_SWITCH_PLAYER: tool = new tool_switch_player_t(); break;
case TOOL_STEP_YEAR: tool = new tool_step_year_t(); break;
case TOOL_CHANGE_GAME_SPEED: tool = new tool_change_game_speed_t(); break;
case TOOL_ZOOM_IN: tool = new tool_zoom_in_t(); break;
case TOOL_ZOOM_OUT: tool = new tool_zoom_out_t(); break;
case TOOL_SHOW_COVERAGE: tool = new tool_show_coverage_t(); break;
case TOOL_SHOW_NAME: tool = new tool_show_name_t(); break;
case TOOL_SHOW_GRID: tool = new tool_show_grid_t(); break;
case TOOL_SHOW_TREES: tool = new tool_show_trees_t(); break;
case TOOL_SHOW_HOUSES: tool = new tool_show_houses_t(); break;
case TOOL_SHOW_UNDERGROUND: tool = new tool_show_underground_t(); break;
case TOOL_ROTATE90: tool = new tool_rotate90_t(); break;
case TOOL_QUIT: tool = new tool_quit_t(); break;
case TOOL_FILL_TREES: tool = new tool_fill_trees_t(); break;
case TOOL_DAYNIGHT_LEVEL: tool = new tool_daynight_level_t(); break;
case TOOL_VEHICLE_TOOLTIPS: tool = new tool_vehicle_tooltips_t(); break;
case TOOL_TOOGLE_PAX: tool = new tool_toggle_pax_station_t(); break;
case TOOL_TOOGLE_PEDESTRIANS: tool = new tool_toggle_pedestrians_t(); break;
case TOOL_TRAFFIC_LEVEL: tool = new tool_traffic_level_t(); break;
case TOOL_CHANGE_CONVOI: tool = new tool_change_convoi_t(); break;
case TOOL_CHANGE_LINE: tool = new tool_change_line_t(); break;
case TOOL_CHANGE_DEPOT: tool = new tool_change_depot_t(); break;
case TOOL_CHANGE_PLAYER: tool = new tool_change_player_t(); break;
case TOOL_CHANGE_TRAFFIC_LIGHT: tool = new tool_change_traffic_light_t(); break;
case TOOL_CHANGE_CITY: tool = new tool_change_city_t(); break;
case TOOL_RENAME: tool = new tool_rename_t(); break;
case TOOL_TOGGLE_RESERVATION: tool = new tool_toggle_reservation_t(); break;
case TOOL_VIEW_OWNER: tool = new tool_view_owner_t(); break;
case TOOL_HIDE_UNDER_CURSOR: tool = new tool_hide_under_cursor_t(); break;
case TOOL_MOVE_MAP: tool = new tool_move_map_t(); break;
case TOOL_ROLLUP_ALL_WIN: tool = new tool_rollup_all_win_t(); break;
case TOOL_RECOLOUR_TOOL: tool = new tool_recolour_t(); break;
case TOOL_SHOW_FACTORY_STORAGE: tool = new tool_show_factory_storage_t(); break;
case UNUSED_TOOL_ADD_MESSAGE: // fall-through - intended!!!111elf
case UNUSED_WKZ_PWDHASH_TOOL:
dbg->warning("create_simple_tool()", "Deprecated tool [%i] requested", toolnr);
return NULL;
default:
dbg->error("create_simple_tool()","cannot satisfy request for simple_tool[%i]!",toolnr);
return NULL;
}
assert(tool->get_id() == (toolnr | SIMPLE_TOOL));
return tool;
}
tool_t *create_dialog_tool(int toolnr)
{
tool_t* tool = NULL;
switch(toolnr) {
case DIALOG_HELP: tool = new dialog_help_t(); break;
case DIALOG_OPTIONS: tool = new dialog_options_t(); break;
case DIALOG_MINIMAP: tool = new dialog_minimap_t(); break;
case DIALOG_LINEOVERVIEW: tool = new dialog_lines_t(); break;
case DIALOG_MESSAGES: tool = new dialog_messages_t(); break;
case DIALOG_FINANCES: tool = new dialog_finances_t(); break;
case DIALOG_PLAYERS: tool = new dialog_players_t(); break;
case DIALOG_DISPLAYOPTIONS: tool = new dialog_displayoptions_t(); break;
case DIALOG_SOUND: tool = new dialog_sound_t(); break;
case DIALOG_LANGUAGE: tool = new dialog_language_t(); break;
case DIALOG_PLAYERCOLOR: tool = new dialog_playercolor_t(); break;
case DIALOG_JUMP: tool = new dialog_jump_t(); break;
case DIALOG_LOAD: tool = new dialog_load_t(); break;
case DIALOG_SAVE: tool = new dialog_save_t(); break;
case DIALOG_LIST_HALT: tool = new dialog_list_halt_t(); break;
case DIALOG_LIST_CONVOI: tool = new dialog_list_convoi_t(); break;
case DIALOG_LIST_TOWN: tool = new dialog_list_town_t(); break;
case DIALOG_LIST_GOODS: tool = new dialog_list_goods_t(); break;
case DIALOG_LIST_FACTORY: tool = new dialog_list_factory_t(); break;
case DIALOG_LIST_CURIOSITY: tool = new dialog_list_curiosity_t(); break;
case DIALOG_EDIT_FACTORY: tool = new dialog_edit_factory_t(); break;
case DIALOG_EDIT_ATTRACTION: tool = new dialog_edit_attraction_t(); break;
case DIALOG_EDIT_HOUSE: tool = new dialog_edit_house_t(); break;
case DIALOG_EDIT_TREE: tool = new dialog_edit_tree_t(); break;
case DIALOG_ENLARGE_MAP: tool = new dialog_enlarge_map_t(); break;
case DIALOG_LIST_LABEL: tool = new dialog_list_label_t(); break;
case DIALOG_CLIMATES: tool = new dialog_climates_t(); break;
case DIALOG_SETTINGS: tool = new dialog_settings_t(); break;
case DIALOG_GAMEINFO: tool = new dialog_gameinfo_t(); break;
case DIALOG_THEMES: tool = new dialog_themes_t(); break;
case DIALOG_SCENARIO: tool = new dialog_scenario_t(); break;
case DIALOG_SCENARIO_INFO: tool = new dialog_scenario_info_t(); break;
case DIALOG_LIST_DEPOT: tool = new dialog_list_depot_t(); break;
case DIALOG_LIST_VEHICLE: tool = new dialog_list_vehicle_t(); break;
case DIALOG_SCRIPT_TOOL: tool = new dialog_script_tool_t(); break;
case DIALOG_EDIT_GROUNDOBJ: tool = new dialog_edit_groundobj_t(); break;
default:
dbg->error("create_dialog_tool()","cannot satisfy request for dialog_tool[%i]!",toolnr);
return NULL;
}
assert(tool->get_id() == (toolnr | DIALOGE_TOOL));
return tool;
}
tool_t *create_tool(int toolnr)
{
tool_t *tool = NULL;
if( toolnr & GENERAL_TOOL ) {
tool = create_general_tool(toolnr & 0xFFF);
}
else if( toolnr & SIMPLE_TOOL ) {
tool = create_simple_tool(toolnr & 0xFFF);
}
else if( toolnr & DIALOGE_TOOL ) {
tool = create_dialog_tool(toolnr & 0xFFF);
}
if (tool == NULL) {
dbg->error("create_tool()","cannot satisfy request for tool with id %i!",toolnr);
}
return tool;
}
/**
* Returns desc and tool pointer corresponding to the
* general toolid with name @p param_str.
*/
void general_tool_get_desc_builder(uint16 id, const char *param_str, const obj_desc_timelined_t* &desc, tool_t* &tool)
{
if ( id & ((uint16)SIMPLE_TOOL | (uint16)DIALOGE_TOOL) ) {
return;
}
id = id & (~GENERAL_TOOL);
const obj_desc_transport_infrastructure_t* desc1 = NULL;
if (param_str) {
switch (id) {
case TOOL_BUILD_WAY:
desc1 = way_builder_t::get_desc(param_str);
break;
case TOOL_BUILD_BRIDGE:
desc1 = bridge_builder_t::get_desc(param_str);
break;
case TOOL_BUILD_TUNNEL:
desc1 = tunnel_builder_t::get_desc(param_str);
break;
case TOOL_BUILD_ROADSIGN:
desc1 = roadsign_t::find_desc(param_str);
break;
case TOOL_BUILD_WAYOBJ:
desc1 = wayobj_t::find_desc(param_str);
break;
// The following 3's descriptions are registered by hausbauer_t.
case TOOL_BUILD_DEPOT:
case TOOL_BUILD_STATION:
case TOOL_HEADQUARTER: {
const building_desc_t* desc2 = hausbauer_t::get_desc(param_str);
desc = desc2;
tool = desc2 ? desc2->get_builder() : NULL;
return;
}
default: ;
}
}
if (desc1) {
desc = desc1;
tool = desc1->get_builder();
}
}
/**
* Set the defaults of a newly created general tool.
*/
void set_defaults_general_tool(tool_t *tool, const char *param_str)
{
if ( tool == NULL ) {
return;
}
tool_t* copy_from = NULL;
const obj_desc_timelined_t* desc = NULL;
general_tool_get_desc_builder(tool->get_id(), param_str, desc, copy_from);
if (copy_from) {
*tool = *copy_from;
}
}
/**
* Checks whether a tool is available in the current timeline.
*
* Note that this function would return true on error. It is done so
* if no description was found, the previous toolbar button logic
* will still be applied - show buttons with icons regardless of
* whether the objects they build are available or not.
*/
bool check_tool_availability(const tool_t *tool, uint16 time)
{
if ( tool == NULL ) {
return true;
}
tool_t* dummy = NULL;
const obj_desc_timelined_t* desc = NULL;
general_tool_get_desc_builder(tool->get_id(), tool->get_default_param(), desc, dummy);
return desc ? desc->is_available(time) : true;
}
static utf32 str_to_key( const char *str, uint8 *modifier )
{
*modifier = 0; // default no modufier check
if( str[1]==',' || str[1]<=' ') {
return (uint8)*str;
}
else {
// check for control char
if(str[0]=='^') {
if( str[1]==0 || str[1]=='^' ) {
return str[1];
}
else {
*modifier = 2;
// only single character following =>make is 1..26 value
if( isalpha( str[1] ) ) {
return tolower(str[1]) - 'a' + 1;
}
str++;
}
}
// add shift as requested modifier?
if(str[0]=='+') {
if( str[ 1 ] == '+' || str[1]==0 ) {
return '+';
}
*modifier = 1;
str++;
}
// direct value (decimal)
if(str[0]=='#') {
return (str[1]=='#') ? str[1] : atoi(str+1);
}
// check for utf8
if( 127<(uint8)*str ) {
size_t len = 0;
utf32 const c = utf8_decoder_t::decode((utf8 const *)str, len);
if(str[len]==',') {
return c;
}
}
// Function key?
if(str[0]=='F') {
uint8 function = atoi(str+1);
if(function>0) {
return SIM_KEY_F1+function-1;
}
}
// COMMA
if (strstart(str, "COMMA")) {
return ',';
}
// Scroll lock
if (strstart(str, "SCROLLLOCK")) {
return SIM_KEY_SCROLLLOCK;
}
// break/pause key
if (strstart(str, "PAUSE")) {
return SIM_KEY_PAUSE;
}
// HOME
if (strstart(str, "HOME")) {
return SIM_KEY_HOME;
}
// END
if (strstart(str, "END")) {
return SIM_KEY_END;
}
// END
if (strstart(str, "ESC")) {
// but currently fixed binding!
return SIM_KEY_ESCAPE;
}
if (strstart(str, "DELETE")) {
// but currently fixed binding!
return SIM_KEY_DELETE;
}
if (strstart(str, "BACKSPACE")) {
// but currently fixed binding!
return SIM_KEY_BACKSPACE;
}
// NUMPAD
if( const char *c=strstart(str, "NUM_") ) {
return SIM_KEY_NUMPAD_BASE + atoi( c );
}
}
// invalid key
return 0xFFFF;
}
// just fills the default tables before other tools are added
void tool_t::init_menu()
{
for( uint16 i=0; i<GENERAL_TOOL_COUNT; i++ ) {
tool_t *tool = create_general_tool( i );
general_tool.append(tool);
}
for( uint16 i=0; i<SIMPLE_TOOL_COUNT; i++ ) {
// To squelch warning on startup
if( i == UNUSED_TOOL_ADD_MESSAGE || i == UNUSED_WKZ_PWDHASH_TOOL) {
simple_tool.append(NULL);
continue;
}
tool_t *tool = create_simple_tool( i );
simple_tool.append(tool);
}
for( uint16 i=0; i<DIALOGE_TOOL_COUNT; i++ ) {
tool_t *tool = create_dialog_tool( i );
dialog_tool.append(tool);
}
}
void tool_t::exit_menu()
{
clear_ptr_vector( general_tool );
clear_ptr_vector( simple_tool );
clear_ptr_vector( dialog_tool );
}
// for sorting: compare tool key
static bool compare_tool(tool_t const* const a, tool_t const* const b)
{
uint16 const ac = a->command_key & ~32;
uint16 const bc = b->command_key & ~32;
return ac != bc ? ac < bc : a->command_key < b->command_key;
}
// read a tab file to add images, cursors and sound to the tools
bool tool_t::read_menu(const std::string &menuconf_path)
{
char_to_tool.clear();
tabfile_t menuconf;
// only use pak specific menus, since otherwise images may be missing
if (!menuconf.open(menuconf_path.c_str())) {
return false;
}
tabfileobj_t contents;
menuconf.read(contents);
// structure to hold information for iterating through different tool types
struct tool_class_info_t {
const char* type;
uint16 count;
vector_tpl<tool_t *> &tools;
const skin_desc_t *icons;
const skin_desc_t *cursor;
bool with_sound;
};
tool_class_info_t info[] = {
{ "general_tool", GENERAL_TOOL_COUNT, general_tool, skinverwaltung_t::tool_icons_general, skinverwaltung_t::cursor_general, true },
{ "simple_tool", SIMPLE_TOOL_COUNT, simple_tool, skinverwaltung_t::tool_icons_simple, NULL, false},
{ "dialog_tool", DIALOGE_TOOL_COUNT, dialog_tool, skinverwaltung_t::tool_icons_dialoge, NULL, false }
};
// first init all tools
DBG_MESSAGE( "tool_t::read_menu()", "Reading general menu" );
for( uint16 t=0; t<3; t++) {
for( uint16 i=0; i<info[t].count; i++ ) {
char id[256];
sprintf( id, "%s[%i]", info[t].type, i );
const char *str = contents.get( id );
/* Format of str:
* for general tools: icon,cursor,sound,key
* icon is image number in menu.GeneralTools, cursor image number in cursor.GeneralTools
* for simple and dialog tools: icon,key
* icon is image number in menu.SimpleTools and menu.DialogeTools
* -1 will disable any of them
*/
tool_t *tool = info[t].tools[i];
if (!tool) {
if (str && strcmp(str, "") != 0) {
// this key is present in the tab file
dbg->warning("tool_t::read_menu", "Ignoring deprecated %s[%i] (%s)", info[t].type, i, tool_t::id_to_string((1<<(t+12)) | i));
}
continue;
}
while(*str==' ') {
str++;
}
if(*str && *str!=',') {
// ok, first comes icon
uint16 icon = (uint16)atoi(str);
if( icon==0 && *str!='0' ) {
// check, if file name ...
int i=0;
while( str[i]!=0 && str[i]!=',' ) {
i++;
}
const skin_desc_t *s=skinverwaltung_t::get_extra(str,i-1);
tool->icon = s ? s->get_image_id(0) : IMG_EMPTY;
}
else {
if( icon>=info[t].icons->get_count() ) {
dbg->warning( "tool_t::init_menu()", "wrong icon (%i) given for %s[%i]", icon, info[t].type, i );
}
tool->icon = info[t].icons->get_image_id(icon);
}
do {
str++;
} while(*str && *str!=',');
}
if(info[t].cursor) {
if(*str==',') {
// next comes cursor
str++;
if(*str && *str!=',') {
uint16 cursor = (uint16)atoi(str);
if( cursor>=info[t].cursor->get_count() ) {
dbg->warning( "tool_t::init_menu()", "wrong cursor (%i) given for %s[%i]", cursor, info[t].type, i );
}
tool->cursor = info[t].cursor->get_image_id(cursor);
do {
str++;
} while(*str && *str!=',');
}
}
}
if(info[t].with_sound) {
if(*str==',') {
// ok_sound
str++;
if(*str && *str!=',') {
int sound = atoi(str);
if( sound>0 ) {
tool->ok_sound = sound_desc_t::get_compatible_sound_id(sound);
}
do {
str++;
} while(*str && *str!=',');
}
}
}
if(*str==',') {
// key
str++;
while(*str==' ') {
str++;
}
if(*str>=' ') {
tool->command_key = str_to_key(str, &tool->command_flags);
char_to_tool.append(tool);
}
}
}
}
// now the toolbar tools
DBG_MESSAGE( "tool_t::read_menu()", "Reading toolbars" );
toolbar_last_used_t::last_used_tools = new toolbar_last_used_t( TOOL_LAST_USED | TOOLBAR_TOOL, "Last used tools", "last_used.txt" );
// first: add main menu
toolbar_tool.resize( skinverwaltung_t::tool_icons_toolbars->get_count() );
toolbar_tool.append(new toolbar_t(TOOLBAR_TOOL, "", ""));
for( uint16 i=0; i<toolbar_tool.get_count(); i++ ) {
char id[256];
for( int j=0; ; j++ ) {
/* str should now contain something like 1,2,-1
* first parameter is the image number in "GeneralTools"
* next is the cursor in "GeneralTools"
* final is the sound
* -1 will disable any of them
*/
sprintf( id, "toolbar[%i][%i]", i, j );
const char *str = contents.get( id );
if(*str==0) {
// empty entry => toolbar finished ...
break;
}
tool_t *addtool = NULL;
/* first, parse the string; we could have up to four parameters */
const char *toolname = str;
image_id icon = IMG_EMPTY;
const char *key_str = NULL;
const char *param_str = NULL; // in case of toolbars, it will also contain the tooltip
// parse until next zero-level comma
uint level = 0;
while(*str) {
if (*str == ')') {
level++;
}
else if (*str == '(') {
level--;
}
else if (*str == ',' && level == 0) {
break;
}
str++;
}
// icon
if(*str==',') {
str++;
if(*str!=',') {
// ok, first come icon
while(*str==' ') {
str++;
}
icon = (uint16)atoi(str);
if( icon==0 && *str!='0' ) {
// check, if file name ...
int i=0;
while( str[i]!=0 && str[i]!=',' ) {
i++;
}
const skin_desc_t *s=skinverwaltung_t::get_extra(str,i-1);
icon = s ? s->get_image_id(0) : IMG_EMPTY;
}
else {
if( icon>=skinverwaltung_t::tool_icons_toolbars->get_count() ) {
dbg->warning( "tool_t::read_menu()", "wrong icon (%i) given for toolbar_tool[%i][%i]", icon, i, j );
icon = 0;
}
icon = skinverwaltung_t::tool_icons_toolbars->get_image_id(icon);
}
while(*str && *str!=',') {
str++;
}
}
}
// key
if(*str==',') {
str++;
while(*str==' ' && *str) {
str ++;
}
if(*str!=',' && *str) {
key_str = str;
}
while(*str!=',' && *str) {
str ++;
}
}
// parameter
if(*str==',') {
str++;
if(*str>=' ') {
param_str = str;
}
}
bool create_tool = icon!=IMG_EMPTY || key_str || param_str;
if (char const* const c = strstart(toolname, "general_tool[")) {
uint8 toolnr = atoi(c);
if( toolnr<GENERAL_TOOL_COUNT ) {
if(create_tool) {
// compatibility mode: tool_cityroad is used for tool_wegebau with defaultparam 'cityroad'
if( toolnr==TOOL_BUILD_WAY && param_str && strcmp(param_str,"city_road")==0) {
toolnr = TOOL_BUILD_CITYROAD;
dbg->warning("tool_t::read_menu()", "toolbar[%i][%i]: replaced way-builder(id=14) with default param=cityroad by cityroad builder(id=36)", i,j);
}
// now create tool
addtool = create_general_tool( toolnr );
// copy defaults
*addtool = *(general_tool[toolnr]);
set_defaults_general_tool(addtool, param_str);
general_tool.append( addtool );
}
else {
addtool = general_tool[toolnr];
}
}
else {
dbg->warning( "tool_t::read_menu()", "When parsing menuconf.tab: General tool id is not valid (%hhu >= %i). Tool ignored.", toolnr, (int)GENERAL_TOOL_COUNT );
}
}
else if (char const* const c = strstart(toolname, "simple_tool[")) {
uint8 const toolnr = atoi(c);
if( toolnr<SIMPLE_TOOL_COUNT ) {
if(create_tool) {
addtool = create_simple_tool( toolnr );
*addtool = *(simple_tool[toolnr]);
simple_tool.append( addtool );
}
else {
addtool = simple_tool[toolnr];
}
}
else {
dbg->warning( "tool_t::read_menu()", "When parsing menuconf.tab: Simple tool id is not valid (%hhu >= %i). Tool ignored.", toolnr, (int)SIMPLE_TOOL_COUNT );
}
}
else if (char const* const c = strstart(toolname, "dialog_tool[")) {
uint8 const toolnr = atoi(c);
if( toolnr<DIALOGE_TOOL_COUNT ) {
if(create_tool) {
addtool = create_dialog_tool( toolnr );
*addtool = *(dialog_tool[toolnr]);
dialog_tool.append( addtool );
}
else {
addtool = dialog_tool[toolnr];
}
}
else {
dbg->warning( "tool_t::read_menu()", "When parsing menuconf.tab: Dialog tool id is not valid (%hhu >= %i). Tool ignored.", toolnr, (int)DIALOGE_TOOL_COUNT );
}
}
else if (char const* const c = strstart(toolname, "toolbar[")) {
uint8 const toolnr = atoi(c);
if( toolnr==0 ) {
if( strstr( c, "LAST_USED" ) ) {
toolbar_last_used_t::last_used_tools->icon = icon;
addtool = toolbar_last_used_t::last_used_tools;
}
else {
dbg->error( "Error in menuconf: toolbar cannot call main toolbar", "%s", toolname );
return false;
}
}
if(toolbar_tool.get_count()==toolnr) {
if(param_str==NULL) {
param_str = "Unnamed toolbar";
dbg->warning( "tool_t::read_menu()", "Missing title for toolbar[%hhu]", toolnr);
}
char *c = strdup(param_str);
const char *title = c;
c += strcspn(c, ",");
if (*c != '\0') {
*c++ = '\0';
}
toolbar_t* const tb = new toolbar_t(toolbar_tool.get_count() | TOOLBAR_TOOL, title, c);
toolbar_tool.append(tb);
addtool = tb;
}
}
else {
// make a default tool to add the parameter here
addtool = new tool_dummy_t();
addtool->default_param = strdup(toolname);
addtool->command_key = 1;
}
if(addtool) {
if(icon!=IMG_EMPTY) {
addtool->icon = icon;
}
if(key_str!=NULL) {
addtool->command_key = str_to_key(key_str,&(addtool->command_flags));
char_to_tool.append(addtool);
}
if(param_str!=NULL && ((addtool->get_id() & TOOLBAR_TOOL) == 0)) {
addtool->default_param = strdup(param_str);
}
toolbar_tool[i]->append(addtool);
}
}
}
toolbar_tool.append( toolbar_last_used_t::last_used_tools );
// sort characters
std::sort(char_to_tool.begin(), char_to_tool.end(), compare_tool);
return true;
}
void tool_t::update_toolbars()
{
// renew toolbar
// iterate twice, to get correct icons if a toolbar changes between empty and non-empty
for(uint j=0; j<2; j++) {
bool change = false;
for(toolbar_t* const i : toolbar_tool) {
bool old_icon_empty = i->get_icon(welt->get_active_player()) == IMG_EMPTY;
i->update(welt->get_active_player());
change |= old_icon_empty ^ (i->get_icon(welt->get_active_player()) == IMG_EMPTY);
}
if (!change) {
// no toolbar changes between empty and non-empty, no need to loop again
break;
}
}
}
void tool_t::draw_after(scr_coord pos, bool dirty) const
{
// default action: grey corner if selected
image_id id = get_icon( welt->get_active_player() );
if( id!=IMG_EMPTY && is_selected() ) {
display_img_blend( id, pos.x, pos.y, TRANSPARENT50_FLAG|OUTLINE_FLAG|color_idx_to_rgb(COL_BLACK), false, dirty );
}
}
bool tool_t::is_selected() const
{
return welt->get_tool(welt->get_active_player_nr())==this;
}
const char *tool_t::check_pos(player_t *, koord3d pos )
{
grund_t *gr = welt->lookup(pos);
return (gr && !gr->is_visible()) ? "" : NULL;
}
bool tool_t::check_valid_pos(koord k ) const
{
if(is_grid_tool()) {
return welt->is_within_grid_limits(k);
}
return welt->is_within_limits(k);
};
/**
* Initializes cursor object: image, y-offset, size of marked area,
* has to be called after init().
* @param zeiger cursor object
*/
void tool_t::init_cursor( zeiger_t *zeiger) const
{
zeiger->set_image( cursor );
zeiger->set_yoff( offset );
zeiger->set_area( cursor_area, cursor_centered, cursor_offset);
}
const char *kartenboden_tool_t::check_pos(player_t *, koord3d pos )
{
grund_t *gr = welt->lookup_kartenboden(pos.get_2d());
return (gr && !gr->is_visible()) ? "" : NULL;
}
image_id toolbar_t::get_icon(player_t *player) const
{
// no image for edit tools => do not open
if( icon==IMG_EMPTY || (player!=NULL && strcmp(default_param,"EDITTOOLS")==0 && player->get_player_nr()!=PUBLIC_PLAYER_NR) ) {
return IMG_EMPTY;
}
// now have we a least one visible tool?
if (tool_selector && !tool_selector->empty(player)) {
return icon;
}
return IMG_EMPTY;
}
// simply true, if visible
bool toolbar_t::is_selected() const
{
return win_get_magic(magic_toolbar + toolbar_tool.index_of(const_cast<toolbar_t*>(this)));
}
// just returns sound info after bracket
static sint16 get_sound( const char *c )
{
while( *c && *c!=')' ) {
c++;
}
while( *c && *c!=',' ) {
c++;
}
return (*c ? atoi( c+1 )-2 : NO_SOUND);
}
// fills and displays a toolbar
void toolbar_t::update(player_t *player)
{
const bool create = (tool_selector == NULL);
if(create) {
DBG_MESSAGE("toolbar_t::update()","create toolbar %s",default_param);
tool_selector = new tool_selector_t( default_param, helpfile, toolbar_tool.index_of(this), this!=tool_t::toolbar_tool[0] );
}
else {
DBG_MESSAGE("toolbar_t::update()","update toolbar %s",default_param);
}
tool_selector->reset_tools();
// now (re)fill it
for(tool_t* const w : tools) {
// no way to call this tool? => then it is most likely a metatool
if(w->command_key==1 && w->get_icon(player)==IMG_EMPTY) {
if (char const* const param = w->get_default_param()) {
if( create ) {
DBG_DEBUG("toolbar_t::update()", "add metatool (param=%s)", param);
}
if (char const* c = strstart(param, "ways(")) {
waytype_t way = (waytype_t)atoi(c);
while(*c && *c!=',' && *c!=')') {
c++;
}
systemtype_t subtype = (systemtype_t)(*c!=0 ? atoi(++c) : 0);
way_builder_t::fill_menu( tool_selector, way, subtype, get_sound(c));
}
else if (char const* const c = strstart(param, "bridges(")) {
waytype_t const way = (waytype_t)atoi(c);
bridge_builder_t::fill_menu(tool_selector, way, get_sound(c));
}
else if (char const* const c = strstart(param, "tunnels(")) {
waytype_t const way = (waytype_t)atoi(c);
tunnel_builder_t::fill_menu(tool_selector, way, get_sound(c));
}
else if (char const* const c = strstart(param, "signs(")) {
waytype_t const way = (waytype_t)atoi(c);
roadsign_t::fill_menu(tool_selector, way, get_sound(c));
}
else if (char const* const c = strstart(param, "wayobjs(")) {
waytype_t const way = (waytype_t)atoi(c);
wayobj_t::fill_menu(tool_selector, way, get_sound(c));
}
else if (char const* c = strstart(param, "buildings(")) {
building_desc_t::btype const utype = (building_desc_t::btype)atoi(c);
while(*c && *c!=',' && *c!=')') {
c++;
}
waytype_t way = (waytype_t)(*c!=0 ? atoi(++c) : 0);
hausbauer_t::fill_menu( tool_selector, utype, way, get_sound(c));
}
else if (char const* const c = strstart(param, "scripts(")) {
const char* end = strchr(c, '\0');
char buf[1000];
size_t len = end ? min(lengthof(buf)-1, end-c) : lengthof(buf)-1;
tstrncpy(buf, c, len);
script_tool_manager_t::fill_menu(tool_selector, buf, get_sound(c));
}
else if (param[0] == '-') {
// add dummy tool_t as seperator
tool_selector->add_tool_selector( dummy );
}
}
}
else if(w->get_icon(player)!=IMG_EMPTY) {
// get the right city_road
if(w->get_id() == (TOOL_BUILD_CITYROAD | GENERAL_TOOL)) {
w->flags = 0;
w->init(player);
}
if( create ) {
DBG_DEBUG( "toolbar_t::update()", "add tool %i (param=%s)", w->get_id(), w->get_default_param() );
}
scenario_t *scen = welt->get_scenario();
if( scen->is_scripted() && !scen->is_tool_allowed(player, w->get_id(), w->get_waytype())) {
continue;
}
if ( !check_tool_availability(w, welt->get_timeline_year_month()) ) {
continue;
}
// now add it to the toolbar gui
tool_selector->add_tool_selector( w );
}
}
if( (strcmp(this->default_param,"EDITTOOLS")==0 && player!=welt->get_public_player()) ) {
destroy_win(tool_selector);
return;
}
}
// fills and displays a toolbar
bool toolbar_t::init(player_t *player)
{
update( player );
bool close = (strcmp(this->default_param,"EDITTOOLS")==0 && player!=welt->get_public_player());
// show/create window
if( close ) {
destroy_win(tool_selector);
return false;
}
if( this != tool_t::toolbar_tool[0] ) {
// not main menu
create_win( tool_selector, w_info|w_do_not_delete|w_no_overlap, magic_toolbar+toolbar_tool.index_of(this) );
DBG_MESSAGE("toolbar_t::init()", "ID=%id", get_id());
}
return false;
}
bool toolbar_t::exit(player_t *)
{
if( win_get_magic(magic_toolbar+toolbar_tool.index_of(this)) ) {
destroy_win(tool_selector);
}
return false;
}
// from here on last used toolbar tools (for each player!)
void toolbar_last_used_t::update(player_t *sp)
{
tools.clear();
if( sp ) {
for( slist_tpl<tool_t *>::iterator iter = all_tools[sp->get_player_nr()].begin(); iter != all_tools[sp->get_player_nr()].end(); ++iter ) {
tools.append( *iter );
}
}
toolbar_t::update( sp );
}
void toolbar_last_used_t::clear()
{
for( int i=0; i < MAX_PLAYER_COUNT; i++ ) {
all_tools[i].clear();
}
tools.clear();
}
// currently only needed for last used tools
void toolbar_last_used_t::append( tool_t *t, player_t *sp )
{
static int exclude_from_adding[8]={
TOOL_SCHEDULE_ADD|GENERAL_TOOL,
TOOL_SCHEDULE_INS|GENERAL_TOOL,
TOOL_CHANGE_CONVOI|SIMPLE_TOOL,
TOOL_CHANGE_LINE|SIMPLE_TOOL,
TOOL_CHANGE_DEPOT|SIMPLE_TOOL,
UNUSED_WKZ_PWDHASH_TOOL|SIMPLE_TOOL,
TOOL_CHANGE_PLAYER|SIMPLE_TOOL,
TOOL_RENAME|SIMPLE_TOOL
};
if( !sp || t->get_icon(sp)==IMG_EMPTY ) {
return;
}
// do not add certain tools
for( uint i=0; i<lengthof(exclude_from_adding); i++ ) {
if( t->get_id() == exclude_from_adding[i] ) {
return;
}
}
slist_tpl<tool_t *> &players_tools = all_tools[sp->get_player_nr()];
if( players_tools.is_contained(t) ) {
players_tools.remove( t );
}
else {
while( players_tools.get_count() >= MAX_LAST_TOOLS ) {
players_tools.remove( players_tools.back() );
}
}
players_tools.insert( t );
// if current => update
if( sp == world()->get_active_player() ) {
update( sp );
}
}
bool two_click_tool_t::init(player_t *)
{
first_click_var = true;
start = koord3d::invalid;
if (is_local_execution()) {
welt->show_distance = koord3d::invalid;
}
cleanup( true );
return true;
}
void two_click_tool_t::rdwr_custom_data(memory_rw_t *packet)
{
packet->rdwr_bool(first_click_var);
sint16 posx = start.x; packet->rdwr_short(posx); start.x = posx;
sint16 posy = start.y; packet->rdwr_short(posy); start.y = posy;
sint8 posz = start.z; packet->rdwr_byte(posz); start.z = posz;
}
bool two_click_tool_t::is_first_click() const
{
return first_click_var;
}
bool two_click_tool_t::is_work_here_network_safe(player_t *player, koord3d pos )
{
if( !is_first_click() ) {
return false;
}
const char *error = ""; //default: nosound
uint8 value = is_valid_pos( player, pos, error, koord3d::invalid );
DBG_MESSAGE("two_click_tool_t::is_work_here_network_safe", "Position %s valid=%d", pos.get_str(), value );
if( value == 0 ) {
// cannot work here at all -> safe
return true;
}
// work directly if possible and ctrl is NOT pressed
if( (value & 1) && !( (value & 2) && is_ctrl_pressed())) {
// would work here directly.
return false;
}
else {
// set starting position only
return true;
}
}
const char *two_click_tool_t::work(player_t *player, koord3d pos )
{
if( !is_first_click() && start_marker ) {
start = start_marker->get_pos(); // if map was rotated.
}
// remove marker
cleanup( true );
const char *error = NULL;
uint8 value = is_valid_pos( player, pos, error, !is_first_click() ? start : koord3d::invalid );
DBG_MESSAGE("two_click_tool_t::work", "Position %s valid=%d", pos.get_str(), value );
if( value == 0 ) {
if (error == NULL) {
error = ""; // propagate errors
}
flags &= ~(WFL_SHIFT | WFL_CTRL);
init( player );
return error;
}
if( is_first_click() ) {
// work directly if possible and ctrl is NOT pressed
if( (value & 1) && !( (value & 2) && is_ctrl_pressed())) {
// Work here directly.
DBG_MESSAGE("two_click_tool_t::work", "Call tool at %s", pos.get_str() );
error = do_work( player, pos, koord3d::invalid );
}
else {
// set starting position.
DBG_MESSAGE("two_click_tool_t::work", "Setting start to %s", pos.get_str() );
start_at( pos );
error = NULL;
}
}
else {
if( value & 2 ) {
DBG_MESSAGE("two_click_tool_t::work", "Setting end to %s", pos.get_str() );
error = do_work( player, start, pos );
}
flags &= ~(WFL_SHIFT | WFL_CTRL);
init( player ); // Do the cleanup stuff after(!) do_work (otherwise start==koord3d::invalid).
}
return error;
}
const char *two_click_tool_t::move(player_t *player, uint16 buttonstate, koord3d pos )
{
DBG_MESSAGE("two_click_tool_t::move", "Button: %d, Pos: %s", buttonstate, pos.get_str());
if( buttonstate == 0 ) {
return "";
}
if( start == pos ) {
init( player );
}
const char *error = NULL;
if( start == koord3d::invalid ) {
// start dragging.
cleanup( true );
uint8 value = is_valid_pos( player, pos, error, koord3d::invalid );
if( error || value == 0 ) {
return error;
}
if( value & 2 ) {
start_at( pos );
}
}
else {
// continue dragging.
cleanup( false );
if( start_marker ) {
start = start_marker->get_pos(); // if map was rotated.
}
uint8 value = is_valid_pos( player, pos, error, start );
if( error || value == 0 ) {
return error;
}
if( value & 2 ) {
display_show_load_pointer( true );
mark_tiles( player, start, pos );
display_show_load_pointer( false );
}
}
return "";
}
void two_click_tool_t::start_at( koord3d &new_start )
{
first_click_var = false;
start = new_start;
if (is_local_execution()) {
welt->show_distance = new_start;
start_marker = new zeiger_t(start, NULL);
start_marker->set_image( get_marker_image() );
grund_t *gr = welt->lookup( start );
if( gr ) {
gr->obj_add(start_marker);
}
}
DBG_MESSAGE("two_click_tool_t::start_at", "Setting start to %s", start.get_str());
}
void two_click_tool_t::cleanup( bool delete_start_marker )
{
// delete marker.
if( start_marker!=NULL && delete_start_marker) {
start_marker->mark_image_dirty( start_marker->get_image(), 0 );
delete start_marker;
start_marker = NULL;
}
// delete old route.
while(!marked.empty()) {
zeiger_t *z = marked.remove_first();
z->mark_image_dirty( z->get_image(), 0 );
z->mark_image_dirty( z->get_front_image(), 0 );
koord3d pos = z->get_pos();
grund_t *gr = welt->lookup( pos );
delete z;
// Remove dummy ground (placed by tool_build_tunnel_t and tool_build_way_t):
if(gr && gr->is_dummy_ground()) {
welt->access(pos.get_2d())->boden_entfernen(gr);
delete gr;
assert( !welt->lookup(pos));
}
}
// delete tooltip.
win_set_static_tooltip( NULL );
}
image_id two_click_tool_t::get_marker_image() const
{
return skinverwaltung_t::bauigelsymbol->get_image_id(0);
}
| 31.901235
| 163
| 0.648908
|
Varkalandar
|
0ff40cc9934e8fc6eb151ab62ec4d5168bf996ca
| 586
|
cpp
|
C++
|
BZOJ/1251/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/1251/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/1251/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#define rg register
#define rep(i,x,y) for(rg int i=(x);i<=(y);++i)
#define per(i,x,y) for(rg int i=(x);i>=(y);--i)
using namespace std;
const int N=5e4+10;
int n,m,a[N];
int main(){
scanf("%d%d",&n,&m);
rep(i,1,m){
int op;scanf("%d",&op);
if(op==1){
int l,r,v;scanf("%d%d%d",&l,&r,&v);
rep(i,l,r)a[i]+=v;
}else if(op==2){
int l,r;scanf("%d%d",&l,&r);
rep(i,l,r)if(i<r-i+l)swap(a[i],a[r-i+l]);
}else{
int l,r;scanf("%d%d",&l,&r);
int ret=-1e9;
rep(i,l,r)if(a[i]>ret)ret=a[i];
printf("%d\n",ret);
}
}
return 0;
}
| 20.928571
| 47
| 0.522184
|
sjj118
|
0ff75eae9f0d1d4fedc6cc3ade5d9cfbb5d0b13d
| 2,843
|
cpp
|
C++
|
LOT_spi0_cpp/LOT_spi0.cpp
|
hhk7734/sundries
|
2979db941be25adc2be6eb1fd95838561135af62
|
[
"MIT"
] | 1
|
2018-11-12T00:52:08.000Z
|
2018-11-12T00:52:08.000Z
|
LOT_spi0_cpp/LOT_spi0.cpp
|
hhk7734/AVR_lib
|
2979db941be25adc2be6eb1fd95838561135af62
|
[
"MIT"
] | null | null | null |
LOT_spi0_cpp/LOT_spi0.cpp
|
hhk7734/AVR_lib
|
2979db941be25adc2be6eb1fd95838561135af62
|
[
"MIT"
] | null | null | null |
/**
* @file LOT_spi0.cpp
* @author Hyeon-ki, Hong (hhk7734@gmail.com)
* @brief
*/
#include "LOT_spi0.h"
LOT_spi0::LOT_spi0()
: error_count( 0 )
{
}
void LOT_spi0::setup( LOT_spi_data_order_typedef data_order,
LOT_spi_clk_idle_state_typedef clk_idle,
LOT_spi_clk_sampling_edge_typedef clk_sampling_edge,
LOT_spi_clk_divider_typedef clk_divider )
{
/// MOSI output
/// MISO input
/// SCK output
#if defined( __AVR_ATmega328P__ )
DDRB |= _BV( DDB3 );
DDRB &= ~_BV( DDB4 );
DDRB |= _BV( DDB5 );
#endif
SPCR = _BV( SPE ) | _BV( MSTR );
if( data_order == LOT_SPI_LSB_FIRST ) { SPCR |= _BV( DORD ); }
if( clk_idle == LOT_SPI_CLK_IDLE_HIGH ) { SPCR |= _BV( CPOL ); }
if( clk_sampling_edge == LOT_SPI_CLK_SAMPLING_2_EDGE ) { SPCR |= _BV( CPHA ); }
SPSR &= ~_BV( SPI2X );
switch( clk_divider )
{
case LOT_SPI_SCK_DIV_2: SPSR |= _BV( SPI2X );
case LOT_SPI_SCK_DIV_4: break;
case LOT_SPI_SCK_DIV_8: SPSR |= _BV( SPI2X );
case LOT_SPI_SCK_DIV_16: SPCR |= _BV( SPR0 ); break;
case LOT_SPI_SCK_DIV_32: SPSR |= _BV( SPI2X );
case LOT_SPI_SCK_DIV_64: SPCR |= _BV( SPR1 ); break;
case LOT_SPI_SCK_DIV_128: SPCR |= _BV( SPR1 ) | _BV( SPR0 ); break;
}
}
LOT_status_typedef
LOT_spi0::transmit( const uint8_t register_address, const uint8_t *data, uint8_t size )
{
if( transmit( register_address ) == LOT_OK )
{
for( ; size > 0; --size ) { transmit( *data ); }
return LOT_OK;
}
else
{
error();
return LOT_ERROR;
}
}
LOT_status_typedef LOT_spi0::transmit( const uint8_t register_address, const uint8_t data )
{
transmit( register_address );
return transmit( data );
}
LOT_status_typedef LOT_spi0::receive( const uint8_t register_address, uint8_t *data, uint8_t size )
{
if( transmit( register_address | LOT_SPI0_READ_MASK ) == LOT_OK )
{
for( ; size > 0; --size )
{
transmit( 0 );
*data++ = SPDR;
}
return LOT_OK;
}
else
{
error();
return LOT_ERROR;
}
}
uint8_t LOT_spi0::receive( const uint8_t register_address )
{
transmit( register_address | LOT_SPI0_READ_MASK );
transmit( 0 );
return SPDR;
}
LOT_status_typedef LOT_spi0::transceive( uint8_t *data, uint8_t size )
{
if( transmit( *data ) == LOT_OK )
{
for( ; size > 1; --size )
{
*data++ = SPDR;
transmit( *data );
}
*data = SPDR;
return LOT_OK;
}
else
{
error();
return LOT_ERROR;
}
}
void LOT_spi0::error( void )
{
++error_count;
if( error_count > 10 )
{
for( ;; ) {}
}
}
LOT_spi0 spi0;
| 22.563492
| 99
| 0.572283
|
hhk7734
|
0ffbeb606c68fc22d481d3685f0f3be0822ac105
| 1,716
|
cc
|
C++
|
lib/consumers/aggregator_consumer.cc
|
pal-robotics/statsdcc
|
3398c71019ac202e1b3dccd6e2cbef6537d82975
|
[
"MIT"
] | 1
|
2020-06-09T23:48:06.000Z
|
2020-06-09T23:48:06.000Z
|
lib/consumers/aggregator_consumer.cc
|
pal-robotics/statsdcc
|
3398c71019ac202e1b3dccd6e2cbef6537d82975
|
[
"MIT"
] | 2
|
2019-07-04T21:50:11.000Z
|
2020-03-17T18:12:51.000Z
|
lib/consumers/aggregator_consumer.cc
|
pal-robotics/statsdcc
|
3398c71019ac202e1b3dccd6e2cbef6537d82975
|
[
"MIT"
] | 1
|
2020-06-09T15:43:27.000Z
|
2020-06-09T15:43:27.000Z
|
/**
* Source file for class AggregatorConsumer
* Please see statsdcc_consumer.h and consumer.h for documentaion
*/
#include "statsdcc/consumers/aggregator_consumer.h"
#include <gperftools/tcmalloc.h>
#include <string.h>
#include <cstring>
#include <sstream>
#include "statsdcc/configs/aggregator_config.h"
#include "statsdcc/workers/aggregator/worker.h"
namespace statsdcc { namespace consumers {
AggregatorConsumer::AggregatorConsumer() {
std::string bad_keys_key = ::config->name + ".bad_keys";
this->bad_keys_metric = bad_keys_key + ":1|c";
this->bad_keys_queue_hash =
this->str_hash(bad_keys_key) % ::config->workers;
}
void AggregatorConsumer::consume(const std::string& metric) const {
std::size_t pos = metric.find_first_of(":");
if (std::string::npos != pos) {
consume(metric, metric.substr(0, pos));
} else {
char* metric_ptr = (char*) tc_malloc(this->bad_keys_metric.length() + 1);
if (metric_ptr == NULL) {
::logger->warn("unable to tc_malloc");
return;
}
std::strcpy(metric_ptr, this->bad_keys_metric.c_str());
::workers[this->bad_keys_queue_hash]->submit(metric_ptr);
}
}
void AggregatorConsumer::consume(const std::string &metric,
const std::string &metric_name) const {
auto idx = str_hash(metric_name) % ::config->workers;
// explicit tc_malloc is faster than strdup
// - possibly because length() is O(1)
char* metric_ptr = (char*) tc_malloc(metric.length() + 1);
if (metric_ptr == NULL) {
::logger->warn("unable to tc_malloc");
return;
}
std::strcpy(metric_ptr, metric.c_str());
::workers[idx]->submit(metric_ptr);
}
} // namespace consumers
} // namespace statsdcc
| 27.238095
| 77
| 0.681235
|
pal-robotics
|
0ffcf51b1886253cc551639358ae85d13d4faa33
| 6,271
|
cc
|
C++
|
scripts/makePlotsOfAllBranches.cc
|
ats2008/CMS-TIFR
|
339b61fac76d65079cb4c53708117e255cbe8af8
|
[
"MIT"
] | null | null | null |
scripts/makePlotsOfAllBranches.cc
|
ats2008/CMS-TIFR
|
339b61fac76d65079cb4c53708117e255cbe8af8
|
[
"MIT"
] | null | null | null |
scripts/makePlotsOfAllBranches.cc
|
ats2008/CMS-TIFR
|
339b61fac76d65079cb4c53708117e255cbe8af8
|
[
"MIT"
] | null | null | null |
/*
Plot all the branches in a tree froma .root file
Usage :
root -b -q 'makePlotsOfAllBranches.cc("<pathToRootFile>","<nameOfTTreeInFile>","<prefixToThePicToSave>")"
eg. : user@pc $ root -b -q 'makePlaotsOfAllBranches.cc("data/bmm5sample.root","Events","outputs/plots/test/")
*/
void setCanvasStyle(TCanvas *c);
void setGlobalStyles();
void putCMStags(TCanvas *c);
void addLegend(TCanvas *c,TLegend **legend_cms=nullptr,TH1* hist=nullptr,string label="labelX",float x1=0.55,float y1=0.82,float x2=0.88, float y2=0.88, string options="lp");
void addText(TCanvas *c,float x=0.16,float y =0.72,string text="sample text",EColor col=kBlack,float fontSize=0.03,int font=42);
void saveCanvas(TCanvas *c1, string name="sample",string prefix="plots/", string type=".png");
void plotHist(TCanvas * c1,TH1* ahist,TString opts,EColor col=kBlue,int lwidth=2,bool putStats=0,bool clear=1,float maximum=1.15);
void makePlotsOfAllBranches(string fname="",string treeName="",string prefix="")
{
// string fname="/home/aravind/cernbox/work/bs2mumug/analysis2018/bmm5/outputs/photonDrDistribution.root";
// string prefix="/home/aravind/cernbox/work/bs2mumug/analysis2018/bmm5/outputs/plots/";
TFile * ifile= new TFile(fname.c_str(),"read");
TTree * aTree = (TTree* ) ifile->Get(treeName.c_str());
TCanvas *c1 = new TCanvas("c", "c",473,281,800,727);
TLegend *alegend=nullptr;
setGlobalStyles();
const int nq=2;
const int NBINS=20;
Double_t xq[nq]={0.01,0.98}; // position where to compute the quantiles in [0,1]
Double_t yq[nq]; // array to contain the quantiles
string branchName,tmp;
float min,max;
TH1F* ahist;
auto BranchList = (TObjArray *) aTree->GetListOfBranches();
auto nentries= BranchList->GetEntries();
for (int i=0;i<nentries;i++)
{
branchName=BranchList->At(i)->GetName();
std::cout<<" Ploting "<< branchName<<" "<<i<<" / "<<nentries<<"\n";
tmp=branchName+" >> th1_tmp";
aTree->Draw( tmp.c_str() );
auto hist_raw=(TH1*) gROOT->FindObject("th1_tmp");
hist_raw->GetQuantiles(nq,yq,xq);
delete hist_raw;
min = yq[0]> 0 ? yq[0]*0.80 : yq[0]*1.20;
max = yq[1]> 0 ? yq[1]*1.20 : yq[1]*0.80;
ahist = new TH1F(branchName.c_str(),branchName.c_str(),NBINS,min,max);
aTree->Project(ahist->GetName(),branchName.c_str());
if (ahist==nullptr) return;
c1->Clear();
ahist->SetTitle(";; Arb. Unit");
//ahist->GetXaxis()->SetRangeUser(0., maxX);
//ahist->Scale(1.0/ahist->Integral());
auto maxY=ahist->GetMaximum()*1.3;
addLegend(c1,&alegend,ahist,branchName.c_str(),0.15,0.83,0.8,0.88);
plotHist(c1,ahist,"HIST",kBlue,2,1,1,maxY);
alegend->Draw();
saveCanvas(c1,ahist->GetName(),prefix,".png");
saveCanvas(c1,ahist->GetName(),prefix,".pdf");
delete alegend;alegend=nullptr;
}
return;
}
/// PLOTING MACROS ///
void plotHist(TCanvas * c1,TH1* ahist,TString opts,EColor col=kBlue,int lwidth=2,bool putStats=0,bool clear=1,float maximum=1.15)
{
c1->cd();
ahist->SetLineWidth(lwidth);
ahist->SetLineColor(col);
if(maximum >-1e10) ahist->SetMaximum(maximum);
if(not putStats) ahist->SetStats(0);
if(clear) ahist->Draw(opts);
else ahist->Draw("same");
if(putStats){
TPaveStats *st = (TPaveStats*)gROOT->FindObject("stats");
if( st){
st->SetX1NDC(0.1); //new x start position
st->SetY1NDC(0.1);}
}
setCanvasStyle(c1);
putCMStags(c1);
}
//Related to the Plotting style
void setGlobalStyles()
{
gStyle->SetLineWidth(2);
/*
kWhite = 0, kBlack = 1, kGray = 920, kRed = 632, kGreen = 416,
kBlue = 600, kYellow = 400, kMagenta = 616, kCyan = 432, kOrange = 800,
kSpring = 820, kTeal = 840, kAzure = 860, kViolet = 880, kPink = 900
*/
Int_t palette[6];
palette[0] = 600;
palette[1] = 632;
palette[2] = 416;
palette[3] = 432;
palette[4] = 616;
palette[5] = 1;
gStyle->SetPalette(6,palette);
gStyle->SetOptStat("eou");
gStyle->SetStatX(0.93);
gStyle->SetStatY(0.91);
}
void setCanvasStyle(TCanvas *c)
{
//Canvas size according to the FTR
c->SetCanvasSize(800,727);
c->Range(-0.1,-0.1,50.0,1.2);
c->SetFillColor(0);
c->SetBorderMode(0);
c->SetBorderSize(2);
c->SetGridx();
c->SetGridy();
c->SetTickx(1);
c->SetTicky(1);
c->SetLeftMargin(0.12);
c->SetRightMargin(0.05);
c->SetTopMargin(0.08);
c->SetBottomMargin(0.08);
c->SetFrameLineWidth(2);
c->SetFrameBorderMode(0);
c->SetFrameLineWidth(2);
c->SetFrameBorderMode(0);
}
void addText(TCanvas *c,string text="sample text",float x=0.16,float y =0.72,EColor col=kBlack,float fontSize=0.03,int font=42)
{
c->cd();
// Definit of Trigger name //
TLatex * text_cms_trig = new TLatex(x,y,text.c_str());
text_cms_trig->SetNDC();
text_cms_trig->SetTextFont(font);
text_cms_trig->SetTextSize(fontSize);
text_cms_trig->SetTextColor(col);
text_cms_trig->Draw("same");
}
void putCMStags(TCanvas *c)
{
addText(c,"#bf{CMS RUN2} #it{Simulation Preliminary} ",0.125,0.94,kBlack,0.04,42);
addText(c,"#bf{#sqrt{s} = 13 TeV}",0.75,0.94,kBlack,0.04,42);
// addText(c,"#it{Simulation Preliminary}",0.16,0.84,kBlack,0.04,42);
return;
// CMS Name Label on top bar//
}
void addLegend(TCanvas *c,TLegend ** alegend=nullptr,TH1* hist=nullptr,string label="labelX",float x1=0.55,float y1=0.82,float x2=0.88, float y2=0.88, string options="lp")
{
c->cd();
//Legend definiation//
if(hist==nullptr) return ;
if (*alegend==nullptr)
*alegend = new TLegend(x1,y1,x2,y2,"","NDC");
auto legend_cms= *alegend;
legend_cms->AddEntry(hist,label.c_str() , options.c_str());
legend_cms->SetFillStyle(0);
legend_cms->SetTextFont(42);
legend_cms->SetTextSize(0.04);
legend_cms->SetFillColor(0);
legend_cms->SetBorderSize(0);
legend_cms->Draw("same");
}
void saveCanvas(TCanvas *c1, string name="sample",string prefix="plots/", string type=".png")
{
c1->Update();
c1->SaveAs((prefix+name+type).c_str());
}
| 29.861905
| 174
| 0.629884
|
ats2008
|
ba003456b04fcbabeabae4b93f913d582df43de2
| 10,900
|
cxx
|
C++
|
arrows/klv/tests/test_klv_0104.cxx
|
chetnieter/kwiver
|
cebc8156b5109d423ffac34f6e4bb442d36c24ab
|
[
"BSD-3-Clause"
] | null | null | null |
arrows/klv/tests/test_klv_0104.cxx
|
chetnieter/kwiver
|
cebc8156b5109d423ffac34f6e4bb442d36c24ab
|
[
"BSD-3-Clause"
] | null | null | null |
arrows/klv/tests/test_klv_0104.cxx
|
chetnieter/kwiver
|
cebc8156b5109d423ffac34f6e4bb442d36c24ab
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/// \file
/// \brief Test KLV 0104 read / write.
#include "data_format.h"
#include <arrows/klv/klv_0104_new.h>
#include <arrows/klv/klv_packet.h>
// ----------------------------------------------------------------------------
int
main( int argc, char** argv )
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
// ----------------------------------------------------------------------------
void
test_read_write( klv_value const& expected_result,
klv_bytes_t const& input_bytes )
{
using format_t = klv_0104_universal_set_format;
test_read_write_format< format_t >( expected_result, input_bytes );
}
// ----------------------------------------------------------------------------
klv_uds_key
to_key( klv_0104_tag tag )
{
return klv_0104_traits_lookup().by_tag( tag ).uds_key();
}
auto const input_bytes = klv_bytes_t{
// KLV_0104_DEVICE_DESIGNATION
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00,
0x05,
'M', 'Q', '1', '-', 'B',
// KLV_0104_EPISODE_NUMBER
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04,
0x3F, 0x80, 0x00, 0x00,
// KLV_0104_IMAGE_SOURCE_DEVICE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x04, 0x20, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00,
0x02,
'E', 'O',
// KLV_0104_HORIZONTAL_FOV
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x02,
0x04, 0x20, 0x02, 0x01, 0x01, 0x08, 0x00, 0x00,
0x04,
0x43, 0x10, 0x92, 0x41,
// KLV_0104_VERTICAL_FOV
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x07,
0x04, 0x20, 0x02, 0x01, 0x01, 0x0A, 0x01, 0x00,
0x04,
0x43, 0x18, 0xA4, 0xC5,
// KLV_0104_IMAGE_COORDINATE_SYSTEM
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x03,
'U', 'T', 'M',
// KLV_0104_DEVICE_ALTITUDE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x02, 0x01, 0x02, 0x02, 0x00, 0x00,
0x04,
0x46, 0x5D, 0xBA, 0xE1,
// KLV_0104_DEVICE_LATITUDE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x02, 0x04, 0x02, 0x00,
0x08,
0x40, 0x4E, 0x16, 0xA2, 0x22, 0x8E, 0x2D, 0x44,
// KLV_0104_DEVICE_LONGITUDE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x02, 0x06, 0x02, 0x00,
0x08,
0x40, 0x60, 0x0D, 0xA8, 0x02, 0x94, 0x1B, 0x50,
// KLV_0104_FRAME_CENTER_LATITUDE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x02, 0x01, 0x03, 0x02, 0x00, 0x00,
0x08,
0xC0, 0x25, 0x15, 0xB3, 0xF6, 0x82, 0x2B, 0x68,
// KLV_0104_FRAME_CENTER_LONGITUDE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x02, 0x01, 0x03, 0x04, 0x00, 0x00,
0x08,
0x40, 0x3D, 0x28, 0x6B, 0x7C, 0xB2, 0x50, 0xD6,
// KLV_0104_CORNER_LATITUDE_POINT_1
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x07, 0x01, 0x00,
0x08,
0xC0, 0x25, 0x28, 0xC6, 0x4F, 0xDB, 0x09, 0xA6,
// KLV_0104_CORNER_LATITUDE_POINT_2
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x08, 0x01, 0x00,
0x08,
0xC0, 0x25, 0x21, 0xE2, 0x8D, 0xFF, 0x31, 0xA4,
// KLV_0104_CORNER_LATITUDE_POINT_3
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x09, 0x01, 0x00,
0x08,
0xC0, 0x25, 0x1A, 0xFF, 0x19, 0x50, 0x33, 0x1E,
// KLV_0104_CORNER_LATITUDE_POINT_4
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x0A, 0x01, 0x00,
0x08,
0xC0, 0x25, 0x14, 0x1B, 0x5A, 0xCF, 0x59, 0x6F,
// KLV_0104_CORNER_LONGITUDE_POINT_1
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x0B, 0x01, 0x00,
0x08,
0x40, 0x3D, 0x20, 0x9B, 0x2D, 0x17, 0x90, 0x3F,
// KLV_0104_CORNER_LONGITUDE_POINT_2
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x0C, 0x01, 0x00,
0x08,
0x40, 0x3D, 0x24, 0x0D, 0x0E, 0x05, 0x7C, 0x41,
// KLV_0104_CORNER_LONGITUDE_POINT_3
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x0D, 0x01, 0x00,
0x08,
0x40, 0x3D, 0x27, 0x7E, 0xC8, 0x5C, 0xFB, 0x84,
// KLV_0104_CORNER_LONGITUDE_POINT_4
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x01, 0x02, 0x01, 0x03, 0x0E, 0x01, 0x00,
0x08,
0x40, 0x3D, 0x2A, 0xF0, 0xA7, 0x9D, 0x68, 0x5B,
// KLV_0104_FRAME_CENTER_ELEVATION
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x0A,
0x07, 0x01, 0x02, 0x01, 0x03, 0x16, 0x00, 0x00,
0x04,
0x45, 0x49, 0x00, 0x98,
// KLV_0104_SLANT_RANGE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x08, 0x01, 0x01, 0x00, 0x00, 0x00,
0x04,
0x47, 0x85, 0xF7, 0x7E,
// KLV_0104_TARGET_WIDTH
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x09, 0x02, 0x01, 0x00, 0x00, 0x00,
0x04,
0x44, 0x34, 0xB4, 0x79,
// KLV_0104_SENSOR_ROLL_ANGLE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x10, 0x01, 0x01, 0x00, 0x00, 0x00,
0x04,
0x43, 0x30, 0xDD, 0x8D,
// KLV_0104_ANGLE_TO_NORTH
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x10, 0x01, 0x02, 0x00, 0x00, 0x00,
0x04,
0x43, 0x20, 0xB8, 0x1E,
// KLV_0104_OBLIQUITY_ANGLE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x01, 0x10, 0x01, 0x03, 0x00, 0x00, 0x00,
0x04,
0x43, 0xAE, 0x65, 0x6B,
// KLV_0104_PLATFORM_ROLL_ANGLE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x07,
0x07, 0x01, 0x10, 0x01, 0x04, 0x00, 0x00, 0x00,
0x04,
0x40, 0x59, 0xF9, 0xB4,
// KLV_0104_PLATFORM_PITCH_ANGLE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x07,
0x07, 0x01, 0x10, 0x01, 0x05, 0x00, 0x00, 0x00,
0x04,
0xBE, 0xDC, 0xF1, 0xBA,
// KLV_0104_PLATFORM_HEADING_ANGLE
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x07,
0x07, 0x01, 0x10, 0x01, 0x06, 0x00, 0x00, 0x00,
0x04,
0x43, 0x1F, 0xF9, 0x70,
// KLV_0104_USER_DEFINED_TIMESTAMP
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x03,
0x07, 0x02, 0x01, 0x01, 0x01, 0x05, 0x00, 0x00,
0x08,
0x00, 0x04, 0x59, 0xF4, 0xA6, 0xAA, 0x4A, 0xA8,
// KLV_0104_START_DATETIME
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x02, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00,
0x0F,
'1', '9', '9', '5', '0', '4', '1', '6', 'T', '1', '3', '4', '4', '5', '4',
// KLV_0104_EVENT_START_DATETIME
0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x07, 0x02, 0x01, 0x02, 0x07, 0x01, 0x00, 0x00,
0x0F,
'1', '9', '9', '5', '0', '4', '1', '6', 'T', '1', '3', '4', '4', '5', '4',
// KLV_0104_SECURITY_LOCAL_SET
0x06, 0x0E, 0x2B, 0x34, 0x02, 0x03, 0x01, 0x01,
0x0E, 0x01, 0x03, 0x03, 0x02, 0x00, 0x00, 0x00,
0x00, };
auto const expected_result = klv_universal_set{
{ to_key( KLV_0104_FRAME_CENTER_LATITUDE ), -10.542388633146132 },
{ to_key( KLV_0104_FRAME_CENTER_LONGITUDE ), 29.157890122923014 },
{ to_key( KLV_0104_FRAME_CENTER_ELEVATION ), double{ 3216.03723f } },
{ to_key( KLV_0104_IMAGE_COORDINATE_SYSTEM ), std::string{ "UTM" } },
{ to_key( KLV_0104_TARGET_WIDTH ), double{ 722.819867f } },
{ to_key( KLV_0104_START_DATETIME ),
std::string{ "19950416T134454" } },
{ to_key( KLV_0104_EVENT_START_DATETIME ),
std::string{ "19950416T134454" } },
{ to_key( KLV_0104_USER_DEFINED_TIMESTAMP ),
uint64_t{ 0x000459F4A6AA4AA8 } },
{ to_key( KLV_0104_CORNER_LATITUDE_POINT_1 ), -10.5796380 },
{ to_key( KLV_0104_CORNER_LATITUDE_POINT_2 ), -10.5661816 },
{ to_key( KLV_0104_CORNER_LATITUDE_POINT_3 ), -10.5527275 },
{ to_key( KLV_0104_CORNER_LATITUDE_POINT_4 ), -10.5392712 },
{ to_key( KLV_0104_CORNER_LONGITUDE_POINT_1 ), 29.1273678 },
{ to_key( KLV_0104_CORNER_LONGITUDE_POINT_2 ), 29.1408242 },
{ to_key( KLV_0104_CORNER_LONGITUDE_POINT_3 ), 29.1542783 },
{ to_key( KLV_0104_CORNER_LONGITUDE_POINT_4 ), 29.1677346 },
{ to_key( KLV_0104_SLANT_RANGE ), double{ 68590.9832f } },
{ to_key( KLV_0104_SENSOR_ROLL_ANGLE ), double{ 176.865437f } },
{ to_key( KLV_0104_ANGLE_TO_NORTH ), double{ 160.719211f } },
{ to_key( KLV_0104_OBLIQUITY_ANGLE ), double{ 348.792324f } },
{ to_key( KLV_0104_PLATFORM_ROLL_ANGLE ), double{ 3.40586566f } },
{ to_key( KLV_0104_PLATFORM_PITCH_ANGLE ), double{ -0.431531724f } },
{ to_key( KLV_0104_PLATFORM_HEADING_ANGLE ), double{ 159.974365f } },
{ to_key( KLV_0104_HORIZONTAL_FOV ), double{ 144.571298f } },
{ to_key( KLV_0104_VERTICAL_FOV ), double{ 152.643626f } },
{ to_key( KLV_0104_DEVICE_ALTITUDE ), double{ 14190.7195f } },
{ to_key( KLV_0104_DEVICE_LATITUDE ), 60.176822966978335 },
{ to_key( KLV_0104_DEVICE_LONGITUDE ), 128.42675904204452 },
{ to_key( KLV_0104_IMAGE_SOURCE_DEVICE ), std::string{ "EO" } },
{ to_key( KLV_0104_EPISODE_NUMBER ), double{ 1.0f } },
{ to_key( KLV_0104_DEVICE_DESIGNATION ), std::string{ "MQ1-B" } },
{ to_key( KLV_0104_SECURITY_LOCAL_SET ), {} }, };
// ----------------------------------------------------------------------------
TEST ( klv, read_write_0104 )
{
CALL_TEST( test_read_write, {}, {} );
CALL_TEST( test_read_write, expected_result, input_bytes );
}
// ----------------------------------------------------------------------------
TEST ( klv, read_write_0104_packet )
{
auto const packet_header = klv_bytes_t{
0x06, 0x0E, 0x2B, 0x34, 0x02, 0x01, 0x01, 0x01,
0x0E, 0x01, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00,
0x82, 0x02, 0xE4 };
auto const packet_footer = klv_bytes_t{};
// Assemble the target packet's serialized form
auto packet_bytes =
klv_bytes_t( packet_header.size() +
input_bytes.size() +
packet_footer.size() );
auto bytes_it = packet_bytes.begin();
bytes_it = std::copy( packet_header.cbegin(), packet_header.cend(),
bytes_it );
bytes_it = std::copy( input_bytes.cbegin(), input_bytes.cend(),
bytes_it );
bytes_it = std::copy( packet_footer.cbegin(), packet_footer.cend(),
bytes_it );
// Assemble the target packet's unserialized form
auto const test_packet = klv_packet{ klv_0104_key(), expected_result };
// Deserialize
auto read_it = packet_bytes.cbegin();
auto const read_packet = klv_read_packet( read_it, packet_bytes.size() );
EXPECT_EQ( packet_bytes.cend(), read_it );
EXPECT_EQ( test_packet, read_packet );
// Reserialize
klv_bytes_t written_bytes( klv_packet_length( read_packet ) );
auto write_it = written_bytes.begin();
klv_write_packet( read_packet, write_it, written_bytes.size() );
EXPECT_EQ( written_bytes.end(), write_it );
EXPECT_EQ( packet_bytes, written_bytes );
}
| 35.048232
| 79
| 0.638991
|
chetnieter
|
ba01b4fda0f7d7daab727d72f63850318184f9cb
| 3,325
|
hh
|
C++
|
uuv_simulator/uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/FinPlugin.hh
|
dsor-isr/medusa_gazebo
|
7066d2e3fe77d6bc1fdb6cd36a1f8a92539a5a72
|
[
"MIT"
] | null | null | null |
uuv_simulator/uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/FinPlugin.hh
|
dsor-isr/medusa_gazebo
|
7066d2e3fe77d6bc1fdb6cd36a1f8a92539a5a72
|
[
"MIT"
] | null | null | null |
uuv_simulator/uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/FinPlugin.hh
|
dsor-isr/medusa_gazebo
|
7066d2e3fe77d6bc1fdb6cd36a1f8a92539a5a72
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2016 The UUV Simulator 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.
/// \file FinPlugin.hh
/// \brief Model plugin for description of a submarine's fin.
#ifndef __UUV_GAZEBO_PLUGINS_FIN_PLUGIN_HH__
#define __UUV_GAZEBO_PLUGINS_FIN_PLUGIN_HH__
#include <boost/scoped_ptr.hpp>
#include <gazebo/gazebo.hh>
#include <sdf/sdf.hh>
#include <gazebo/msgs/msgs.hh>
#include <uuv_gazebo_plugins/Dynamics.hh>
#include <uuv_gazebo_plugins/LiftDragModel.hh>
#include "Double.pb.h"
namespace gazebo {
/// \brief Definition of a pointer to the floating point message
typedef const boost::shared_ptr<const uuv_gazebo_plugins_msgs::msgs::Double> ConstDoublePtr;
class FinPlugin : public ModelPlugin {
/// \brief Constructor
public: FinPlugin();
/// \brief Destructor
public: virtual ~FinPlugin();
// Documentation inherited.
public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);
// Documentation inherited.
public: virtual void Init();
/// \brief Update the simulation state.
/// \param[in] _info Information used in the update event.
public: void OnUpdate(const common::UpdateInfo &_info);
/// \brief Callback for the input topic subscriber
protected: void UpdateInput(ConstDoublePtr &_msg);
/// \brief Reads current velocity topic
protected: void UpdateCurrentVelocity(ConstVector3dPtr &_msg);
/// \brief Fin dynamic model
protected: std::shared_ptr<Dynamics> dynamics;
/// \brief Lift&Drag model
protected: std::shared_ptr<LiftDrag> liftdrag;
/// \brief Update event
protected: event::ConnectionPtr updateConnection;
/// \brief Gazebo node
protected: transport::NodePtr node;
/// \brief The fin joint
protected: physics::JointPtr joint;
/// \brief The fin link
protected: physics::LinkPtr link;
/// \brief Subscriber to the reference signal topic.
protected: transport::SubscriberPtr commandSubscriber;
/// \brief Publisher to the output thrust topic
protected: transport::PublisherPtr anglePublisher;
/// \brief Force component calculated from the lift and drag module
protected: ignition::math::Vector3d finForce;
/// \brief Latest input command.
protected: double inputCommand;
/// \brief Fin ID
protected: int finID;
/// \brief Topic prefix
protected: std::string topicPrefix;
/// \brief Latest fin angle in [rad].
protected: double angle;
/// \brief Time stamp of latest thrust force
protected: common::Time angleStamp;
/// \brief Subcriber to current message
protected: transport::SubscriberPtr currentSubscriber;
/// \brief Current velocity vector read from topic
protected: ignition::math::Vector3d currentVelocity;
};
}
#endif
| 29.954955
| 92
| 0.719699
|
dsor-isr
|
ba01c11aa73a164597705f35cafc1d31b3a72af1
| 815
|
cpp
|
C++
|
Strings/pairs_with_concatenation_equal_to_target.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
Strings/pairs_with_concatenation_equal_to_target.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
Strings/pairs_with_concatenation_equal_to_target.cpp
|
khushisinha20/Data-Structures-and-Algorithms
|
114d365d03f7ba7175eefeace281972820a7fc76
|
[
"Apache-2.0"
] | null | null | null |
//leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
class Solution {
public:
int numOfPairs(vector<string>& nums, string target) {
int pairs = 0;
unordered_map<string, int> mp;
for (int i = 0; i < nums.size(); ++i) {
++mp[nums[i]];
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target.substr(0, nums[i].size())) {
string remaining = target.substr(nums[i].size());
if (mp.find(remaining) != mp.end()) {
pairs += mp[remaining];
if (remaining == nums[i])
--pairs;
}
}
}
return pairs;
}
};
| 30.185185
| 85
| 0.484663
|
khushisinha20
|
ba027caa83a6e0634cde84d640ea368b334b5172
| 2,896
|
cpp
|
C++
|
s32v234_sdk/libs/apex/llrt/src/utilities_desc.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/libs/apex/llrt/src/utilities_desc.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/libs/apex/llrt/src/utilities_desc.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | 2
|
2021-01-21T02:06:16.000Z
|
2021-01-28T10:47:37.000Z
|
/*****************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright (c) 2018 NXP Semiconductor;
* All Rights Reserved
*
*****************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP 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 <stdint.h>
#include <common.hpp>
#include <data_desc.hpp>
#include <tiling_desc.hpp>
#include <tile_vectorization_desc.hpp>
#include <vector_map_desc.hpp>
int32_t CalcNumTileInDim(DataDesc* lpDataDesc, TilingDesc* lpTilingDesc, int32_t lDim)
{
return ((lpDataDesc->mSize[lDim] - lpTilingDesc->mSize[lDim]) / lpTilingDesc->mStepSize[lDim]) + 1;
}
int32_t CalcNumVchunkInDim(int32_t lTileSizeInDim, TileVectorizationDesc* lpTileVectorizationDesc, int32_t lDim)
{
return ((lTileSizeInDim - lpTileVectorizationDesc->mSize[lDim]) / lpTileVectorizationDesc->mStepSize[lDim]) + 1;
}
int32_t CalcNumTileTotal(DataDesc* lpDataDesc, TilingDesc* lpTilingDesc)
{
int32_t lNumTile = 0;
lNumTile = 1;
for (int32_t i = 0; i < lpDataDesc->mNumDim; i++)
{
lNumTile *= CalcNumTileInDim(lpDataDesc, lpTilingDesc, i);
}
return lNumTile;
}
int32_t CalcNumVchunkTotal(int32_t lTileSize[], TileVectorizationDesc* lpTileVectorizationDesc)
{
int32_t lNumVchunk = 0;
lNumVchunk = 1;
for (int32_t i = 0; i < lpTileVectorizationDesc->mNumDim; i++)
{
lNumVchunk *= CalcNumVchunkInDim(lTileSize[i], lpTileVectorizationDesc, i);
}
return lNumVchunk;
}
int32_t CalcNumVchunkTotal(TilingDesc* lpTilingDesc, TileVectorizationDesc* lpTileVectorizationDesc)
{
return (CalcNumVchunkTotal(lpTilingDesc->mSize, lpTileVectorizationDesc));
}
/*
int32_t CalcTileWrapCnt(TilingDesc* lpTilingDesc, TileVectorizationDesc* lpTileVectorizationDesc, VectorMapDesc* lpVectorMapDesc)
{
int lWrapCnt = 0;
int lNumVchunkInTile = CalcNumVchunkTotal(lpTilingDesc, lpTileVectorizationDesc);
int lReqVchunkInclVecPad = lNumVchunkInTile + lpVectorMapDesc->mVecPad[0] + lpVectorMapDesc->mVecPad[1];
lWrapCnt = (lReqVchunkInclVecPad - 1) / lpVectorMapDesc->mPhysVecSize;
return lWrapCnt;
}
*/
| 35.317073
| 129
| 0.703039
|
intesight
|
ba03ae0a18cc852aa31ca6d267c7a470232dd7ff
| 917
|
hpp
|
C++
|
experimental/Pomdog.Experimental/ImageEffects/SepiaToneEffect.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/ImageEffects/SepiaToneEffect.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
experimental/Pomdog.Experimental/ImageEffects/SepiaToneEffect.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_SEPIATONEEFFECT_BD1A4ABD_HPP
#define POMDOG_SEPIATONEEFFECT_BD1A4ABD_HPP
#include "ImageEffectBase.hpp"
#include "Pomdog/Content/AssetManager.hpp"
#include "Pomdog/Graphics/detail/ForwardDeclarations.hpp"
#include <memory>
namespace Pomdog {
class SepiaToneEffect final: public ImageEffectBase {
public:
SepiaToneEffect(
std::shared_ptr<GraphicsDevice> const& graphicsDevice,
AssetManager & assets);
void Apply(
GraphicsCommandList & commandList,
std::shared_ptr<RenderTarget2D> const& source,
std::shared_ptr<ConstantBuffer> const& constantBuffer) override;
private:
std::shared_ptr<SamplerState> samplerLinear;
std::shared_ptr<PipelineState> pipelineState;
};
} // namespace Pomdog
#endif // POMDOG_SEPIATONEEFFECT_BD1A4ABD_HPP
| 27.787879
| 72
| 0.764449
|
bis83
|
ba0615216a7dbc0b59e385f207aebd423a6eac24
| 1,098
|
cpp
|
C++
|
test/rpc_tests.cpp
|
FissionAndFusion/FnFnMvWallet-Pre
|
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
|
[
"MIT"
] | 22
|
2018-08-17T07:05:56.000Z
|
2019-09-16T09:22:32.000Z
|
test/rpc_tests.cpp
|
FissionAndFusion/FnFnMvWallet-Pre
|
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
|
[
"MIT"
] | 23
|
2018-08-18T11:09:42.000Z
|
2019-04-22T10:02:02.000Z
|
test/rpc_tests.cpp
|
FissionAndFusion/FnFnMvWallet-Pre
|
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
|
[
"MIT"
] | 13
|
2018-08-17T01:12:58.000Z
|
2019-09-16T09:05:31.000Z
|
// Copyright (c) 2017-2019 The Multiverse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//#include "rpcmod.h"
#include "test_fnfn.h"
#include <boost/test/unit_test.hpp>
using namespace boost;
struct RPCSetup
{
// multiverse::CRPCMod rpcmdl;
RPCSetup()
{
// rpcmdl.WalleveInitialize();
}
~RPCSetup()
{
// rpcmdl.WalleveDeinitialize();
}
void CallRPCAPI(const std::string& params)
{
/* walleve::CWalleveEventHttpReq eventHttpReq((uint64)0);
try
{
bool ret = rpcmdl.HandleEvent(eventHttpReq);
}
catch(...)
{
throw std::runtime_error("error occured!");
}*/
}
};
BOOST_FIXTURE_TEST_SUITE(rpc_tests, RPCSetup)
BOOST_AUTO_TEST_CASE(rpc_listkey)
{
// BOOST_CHECK_THROW(CallRPCAPI("listkey xxx"), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_getblock)
{
// BOOST_CHECK_THROW(CallRPCAPI("getblock"), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
| 21.96
| 71
| 0.657559
|
FissionAndFusion
|
61311db4cd89321df15698bf359c261a681db502
| 22,260
|
cpp
|
C++
|
Source/cursor.cpp
|
codemaster/devilution
|
5772426a7cf5cf54b0b70c186ac5097a32f82e5c
|
[
"Unlicense"
] | 1
|
2019-06-27T11:26:56.000Z
|
2019-06-27T11:26:56.000Z
|
Source/cursor.cpp
|
Sun4oyZ/devilution
|
fb10d2e7b28c69d50f1c0da8e551b2e1862a5c39
|
[
"Unlicense"
] | null | null | null |
Source/cursor.cpp
|
Sun4oyZ/devilution
|
fb10d2e7b28c69d50f1c0da8e551b2e1862a5c39
|
[
"Unlicense"
] | 1
|
2018-08-30T15:55:33.000Z
|
2018-08-30T15:55:33.000Z
|
//HEADER_GOES_HERE
#include "../types.h"
int cursH; // weak
int icursH28; // idb
int cursW; // idb
int pcursmonst; // idb
int icursW28; // idb
void *pCursCels;
int icursH; // weak
char pcursinvitem; // weak
int icursW; // weak
char pcursitem; // weak
char pcursobj; // weak
char pcursplr; // weak
int cursmx;
int cursmy;
int dword_4B8CCC; // weak
int pcurs; // idb
/* data */
int InvItemWidth[180] =
{
0,
33,
32,
32,
32,
32,
32,
32,
32,
32,
32,
23,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56
};
int InvItemHeight[180] =
{
0,
29,
32,
32,
32,
32,
32,
32,
32,
32,
32,
35,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
28,
56,
56,
56,
56,
56,
56,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
56,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84,
84
};
//----- (0040740A) --------------------------------------------------------
void __cdecl InitCursor()
{
pCursCels = LoadFileInMem("Data\\Inv\\Objcurs.CEL", 0);
ClearCursor();
}
//----- (00407420) --------------------------------------------------------
void __cdecl FreeCursor()
{
void *v0; // ecx
v0 = pCursCels;
pCursCels = 0;
mem_free_dbg(v0);
ClearCursor();
}
//----- (00407437) --------------------------------------------------------
void __fastcall SetICursor(int i)
{
int v1; // ecx
v1 = i;
icursW = InvItemWidth[v1];
icursH = InvItemHeight[v1];
icursW28 = icursW / 28;
icursH28 = icursH / 28;
}
// 4B8CB4: using guessed type int icursH;
// 4B8CBC: using guessed type int icursW;
//----- (0040746B) --------------------------------------------------------
void __fastcall SetCursor(int i)
{
int v1; // eax
v1 = InvItemWidth[i];
pcurs = i;
cursW = v1;
cursH = InvItemHeight[i];
SetICursor(i);
}
// 4B8C9C: using guessed type int cursH;
//----- (00407493) --------------------------------------------------------
void __cdecl InitLevelCursor()
{
SetCursor(CURSOR_HAND);
cursmx = ViewX;
cursmy = ViewY;
dword_4B8CCC = -1;
pcursmonst = -1;
pcursobj = -1;
pcursitem = -1;
pcursplr = -1;
ClearCursor();
}
// 4B8CC0: using guessed type char pcursitem;
// 4B8CC1: using guessed type char pcursobj;
// 4B8CC2: using guessed type char pcursplr;
// 4B8CCC: using guessed type int dword_4B8CCC;
//----- (004074D0) --------------------------------------------------------
void __cdecl CheckTown()
{
int v0; // ecx
int v1; // eax
int v2; // esi
int v3; // edx
int v4; // ebx
int v5; // [esp+0h] [ebp-4h]
v5 = 0;
if ( nummissiles > 0 )
{
v0 = cursmx;
v1 = cursmy;
do
{
v2 = missileactive[v5];
if ( missile[v2]._mitype == MIS_TOWN )
{
if ( (v3 = missile[v2]._mix, v4 = v3 - 1, v0 == v3 - 1) && v1 == missile[v2]._miy
|| v0 == v3 && v1 == missile[v2]._miy - 1
|| v0 == v4 && v1 == missile[v2]._miy - 1
|| v0 == v3 - 2 && (v1 == missile[v2]._miy - 1 || v0 == v3 - 2 && v1 == missile[v2]._miy - 2)
|| v0 == v4 && v1 == missile[v2]._miy - 2
|| v0 == v3 && v1 == missile[v2]._miy )
{
trigflag[3] = 1;
ClearPanel();
strcpy(infostr, "Town Portal");
sprintf(tempstr, "from %s", plr[missile[v2]._misource]._pName);
AddPanelString(tempstr, 1);
v0 = missile[v2]._mix;
v1 = missile[v2]._miy;
cursmx = missile[v2]._mix;
cursmy = v1;
}
}
++v5;
}
while ( v5 < nummissiles );
}
}
//----- (004075FD) --------------------------------------------------------
void __cdecl CheckRportal()
{
int v0; // ecx
int v1; // eax
int v2; // esi
int v3; // edx
int v4; // ebx
int v5; // [esp+0h] [ebp-4h]
v5 = 0;
if ( nummissiles > 0 )
{
v0 = cursmx;
v1 = cursmy;
do
{
v2 = missileactive[v5];
if ( missile[v2]._mitype == MIS_RPORTAL )
{
if ( (v3 = missile[v2]._mix, v4 = v3 - 1, v0 == v3 - 1) && v1 == missile[v2]._miy
|| v0 == v3 && v1 == missile[v2]._miy - 1
|| v0 == v4 && v1 == missile[v2]._miy - 1
|| v0 == v3 - 2 && (v1 == missile[v2]._miy - 1 || v0 == v3 - 2 && v1 == missile[v2]._miy - 2)
|| v0 == v4 && v1 == missile[v2]._miy - 2
|| v0 == v3 && v1 == missile[v2]._miy )
{
trigflag[3] = 1;
ClearPanel();
strcpy(infostr, "Portal to");
if ( setlevel )
strcpy(tempstr, "level 15");
else
strcpy(tempstr, "The Unholy Altar");
AddPanelString(tempstr, 1);
v0 = missile[v2]._mix;
v1 = missile[v2]._miy;
cursmx = missile[v2]._mix;
cursmy = v1;
}
}
++v5;
}
while ( v5 < nummissiles );
}
}
// 5CF31D: using guessed type char setlevel;
//----- (00407729) --------------------------------------------------------
void __cdecl CheckCursMove()
{
int v0; // esi
signed int v1; // edi
int v2; // esi
int v3; // edi
int v4; // edx
int v5; // ebx
int v6; // edi
int v7; // eax
int v8; // esi
BOOL v9; // eax
int v10; // ecx
int v11; // edx
int v12; // ecx
int v13; // ebx
int v14; // ebx
int v15; // eax
bool v16; // zf
int v17; // ecx
int v18; // eax
int v19; // ecx
int v20; // eax
int v21; // ecx
int v22; // eax
int v23; // eax
int v24; // ecx
int v25; // eax
int v26; // ecx
int v27; // ebx
int v28; // edx
int v29; // eax
int v30; // ecx
int v31; // eax
int v32; // eax
int v33; // eax
int v34; // ecx
int v35; // eax
int v36; // ecx
int v37; // eax
int v38; // eax
int v39; // ecx
int v40; // eax
int v41; // ecx
signed int v42; // eax
int v43; // ecx
int v44; // eax
int v45; // eax
int v46; // eax
int v47; // eax
char v48; // al
char v49; // cl
char v50; // al
char v51; // al
char v52; // cl
int v53; // ecx
int *v54; // eax
int v55; // edx
int *v56; // ecx
char v57; // al
char v58; // cl
signed int v59; // edx
char v60; // al
char v61; // cl
char v62; // al
char v63; // al
char v64; // cl
char v65; // al
char v66; // al
char v67; // cl
char v68; // al
char v69; // al
char v70; // al
char v71; // al
char v72; // al
char v73; // cl
char v74; // al
char v75; // al
int v76; // [esp+Ch] [ebp-18h]
char *v77; // [esp+Ch] [ebp-18h]
int v78; // [esp+10h] [ebp-14h]
signed int v79; // [esp+14h] [ebp-10h]
signed int v80; // [esp+18h] [ebp-Ch]
int v81; // [esp+1Ch] [ebp-8h]
int v82; // [esp+1Ch] [ebp-8h]
signed int v83; // [esp+20h] [ebp-4h]
v0 = MouseX;
v1 = MouseY;
if ( chrflag || questlog )
{
if ( MouseX >= 160 )
{
v0 = MouseX - 160;
goto LABEL_10;
}
goto LABEL_9;
}
if ( invflag || sbookflag )
{
if ( MouseX <= 320 )
{
v0 = MouseX + 160;
goto LABEL_10;
}
LABEL_9:
v0 = 0;
}
LABEL_10:
if ( MouseY > 351 && track_isscrolling() )
v1 = 351;
if ( !zoomflag )
{
v0 >>= 1;
v1 >>= 1;
}
v2 = v0 - ScrollInfo._sxoff;
v3 = v1 - ScrollInfo._syoff;
if ( ScrollInfo._sdir )
{
v2 += ((plr[myplr]._pVar6 + plr[myplr]._pxvel) >> 8) - (plr[myplr]._pVar6 >> 8);
v3 += ((plr[myplr]._pVar7 + plr[myplr]._pyvel) >> 8) - (plr[myplr]._pVar7 >> 8);
}
if ( v2 < 0 )
v2 = 0;
if ( v2 >= 640 )
v2 = 640;
if ( v3 < 0 )
v3 = 0;
if ( v3 >= 480 )
v3 = 480;
v4 = v3 >> 5;
v5 = v3 & 0x1F;
v76 = v2 & 0x3F;
v6 = (v2 >> 6) + (v3 >> 5) + ViewX - (zoomflag != 0 ? 10 : 5);
v7 = v76 >> 1;
v8 = v4 + ViewY - (v2 >> 6);
if ( v5 < v76 >> 1 )
--v8;
v9 = v5 >= 32 - v7;
if ( v9 )
++v6;
if ( v6 < 0 )
v6 = 0;
if ( v6 >= 112 )
v6 = 111;
if ( v8 < 0 )
v8 = 0;
if ( v8 >= 112 )
v8 = 111;
if ( v5 >= v76 >> 1 )
{
if ( !v9 )
goto LABEL_49;
goto LABEL_48;
}
if ( !v9 )
{
LABEL_48:
if ( v76 < 32 )
goto LABEL_39;
LABEL_49:
v83 = 0;
goto LABEL_40;
}
LABEL_39:
v83 = 1;
LABEL_40:
v10 = pcursmonst;
pcursobj = -1;
pcursitem = -1;
v11 = -1;
dword_4B8CCC = pcursmonst;
pcursmonst = -1;
if ( pcursinvitem != -1 )
drawsbarflag = 1;
pcursinvitem = -1;
pcursplr = -1;
v16 = plr[myplr]._pInvincible == 0;
uitemflag = 0;
panelflag = 0;
trigflag[3] = 0;
if ( !v16 )
return;
if ( pcurs >= CURSOR_FIRSTITEM || spselflag )
{
cursmx = v6;
cursmy = v8;
return;
}
if ( MouseY > 352 )
{
CheckPanelInfo();
return;
}
if ( doomflag )
return;
if ( invflag && MouseX > 320 )
{
pcursinvitem = CheckInvHLight();
return;
}
if ( sbookflag && MouseX > 320 || (chrflag || questlog) && MouseX < 320 )
return;
if ( !leveltype )
{
if ( v83 )
{
v27 = 112 * v6;
v78 = 112 * v6;
v43 = 112 * v6 + v8;
v45 = dMonster[0][v43 + 1];
if ( v45 <= 0 )
goto LABEL_200;
v11 = v45 - 1;
cursmx = v6;
cursmy = v8 + 1;
}
else
{
v27 = 112 * v6;
v78 = 112 * v6;
v43 = 112 * v6 + v8;
v44 = dMonster[1][v43];
if ( v44 <= 0 )
goto LABEL_200;
v11 = v44 - 1;
cursmx = v6 + 1;
cursmy = v8;
}
pcursmonst = v11;
LABEL_200:
v46 = dMonster[0][v43];
if ( v46 > 0 )
{
v11 = v46 - 1;
cursmx = v6;
pcursmonst = v46 - 1;
cursmy = v8;
}
v47 = dMonster[1][v43 + 1];
if ( v47 > 0 )
{
v11 = v47 - 1;
cursmx = v6 + 1;
pcursmonst = v47 - 1;
cursmy = v8 + 1;
}
if ( !towner[v11]._tSelFlag )
LABEL_205:
pcursmonst = -1;
LABEL_206:
if ( pcursmonst != -1 )
{
LABEL_305:
v59 = pcursmonst;
goto LABEL_306;
}
LABEL_207:
if ( v83 )
{
v50 = dPlayer[0][v27 + 1 + v8];
if ( v50 )
{
v49 = v50 <= 0 ? -1 - v50 : v50 - 1;
if ( v49 != myplr && plr[v49]._pHitPoints )
{
cursmx = v6;
cursmy = v8 + 1;
goto LABEL_222;
}
}
}
else
{
v48 = dPlayer[1][v27 + v8];
if ( v48 )
{
v49 = v48 <= 0 ? -1 - v48 : v48 - 1;
if ( v49 != myplr && plr[v49]._pHitPoints )
{
cursmy = v8;
cursmx = v6 + 1;
LABEL_222:
pcursplr = v49;
goto LABEL_223;
}
}
}
LABEL_223:
v51 = dPlayer[0][v27 + v8];
if ( v51 )
{
v52 = v51 <= 0 ? -1 - v51 : v51 - 1;
if ( v52 != myplr )
{
cursmx = v6;
cursmy = v8;
pcursplr = v52;
}
}
if ( dFlags[0][v27 + v8] & 4 )
{
v53 = 0;
v54 = &plr[0].WorldY;
do
{
if ( *(v54 - 1) == v6 && *v54 == v8 && v53 != myplr )
{
cursmx = v6;
cursmy = v8;
pcursplr = v53;
}
v54 += 5430;
++v53;
}
while ( (signed int)v54 < (signed int)&plr[4].WorldY );
}
if ( pcurs == CURSOR_RESURRECT )
{
v79 = -1;
v77 = &nBlockTable[v27 + 1944 + v8];
do
{
v80 = -1;
v55 = v8 - 1;
do
{
if ( v77[v80] & 4 )
{
v82 = 0;
v56 = &plr[0].WorldY;
do
{
if ( *(v56 - 1) == v6 + v79 && *v56 == v55 && v82 != myplr )
{
cursmx = v6 + v79;
cursmy = v55;
pcursplr = v82;
}
++v82;
v56 += 5430;
}
while ( (signed int)v56 < (signed int)&plr[4].WorldY );
}
++v80;
++v55;
}
while ( v80 < 2 );
++v79;
v77 += 112;
}
while ( v79 < 2 );
v27 = v78;
}
v57 = dPlayer[1][v27 + 1 + v8];
if ( v57 )
{
v58 = v57 <= 0 ? -1 - v57 : v57 - 1;
if ( v58 != myplr && plr[v58]._pHitPoints )
{
pcursplr = v58;
cursmx = v6 + 1;
cursmy = v8 + 1;
}
}
v59 = pcursmonst;
if ( pcursmonst != -1 )
{
LABEL_285:
if ( pcursplr == -1 )
goto LABEL_286;
LABEL_306:
if ( pcurs == CURSOR_IDENTIFY )
{
pcursobj = -1;
v59 = -1;
pcursitem = -1;
pcursmonst = -1;
cursmx = v6;
cursmy = v8;
}
if ( v59 != -1 )
{
if ( monster[v59]._mFlags & 0x20 )
pcursmonst = -1;
}
return;
}
if ( pcursplr != pcursmonst ) /* check in future */
goto LABEL_306;
if ( v83 )
{
v62 = dObject[0][v27 + 1 + v8];
if ( !v62 )
goto LABEL_272;
v61 = v62 <= 0 ? -1 - v62 : v62 - 1;
if ( SLOBYTE(object[v61]._oSelFlag) < 2 )
goto LABEL_272;
cursmx = v6;
cursmy = v8 + 1;
}
else
{
v60 = dObject[1][v27 + v8];
if ( !v60 )
goto LABEL_272;
v61 = v60 <= 0 ? -1 - v60 : v60 - 1;
if ( SLOBYTE(object[v61]._oSelFlag) < 2 )
goto LABEL_272;
cursmy = v8;
cursmx = v6 + 1;
}
pcursobj = v61;
LABEL_272:
v63 = dObject[0][v27 + v8];
if ( v63 )
{
v64 = v63 <= 0 ? -1 - v63 : v63 - 1;
v65 = object[v64]._oSelFlag;
if ( v65 == 1 || v65 == 3 )
{
cursmx = v6;
cursmy = v8;
pcursobj = v64;
}
}
v66 = dObject[1][v27 + 1 + v8];
if ( !v66 || (v66 <= 0 ? (v67 = -1 - v66) : (v67 = v66 - 1), SLOBYTE(object[v67]._oSelFlag) < 2) )
{
LABEL_286:
if ( pcursobj != -1 || pcursmonst != -1 )
goto LABEL_306;
if ( v83 )
{
v70 = dItem[0][v27 + 1 + v8];
if ( v70 <= 0 )
goto LABEL_296;
v69 = v70 - 1;
if ( item[v69]._iSelFlag < 2 )
goto LABEL_296;
cursmx = v6;
cursmy = v8 + 1;
}
else
{
v68 = dItem[1][v27 + v8];
if ( v68 <= 0 )
goto LABEL_296;
v69 = v68 - 1;
if ( item[v69]._iSelFlag < 2 )
goto LABEL_296;
cursmy = v8;
cursmx = v6 + 1;
}
pcursitem = v69;
LABEL_296:
v71 = dItem[0][v27 + v8];
if ( v71 > 0 )
{
v72 = v71 - 1;
v73 = item[v72]._iSelFlag;
if ( v73 == 1 || v73 == 3 )
{
cursmx = v6;
cursmy = v8;
pcursitem = v72;
}
}
v74 = dItem[1][v27 + 1 + v8];
if ( v74 > 0 )
{
v75 = v74 - 1;
if ( item[v75]._iSelFlag >= 2 )
{
pcursitem = v75;
cursmx = v6 + 1;
cursmy = v8 + 1;
}
}
if ( pcursitem != -1 )
goto LABEL_306;
cursmx = v6;
cursmy = v8;
CheckTrigForce();
CheckTown();
CheckRportal();
goto LABEL_305;
}
pcursobj = v67;
cursmx = v6 + 1;
cursmy = v8 + 1;
goto LABEL_285;
}
if ( v10 == -1 )
goto LABEL_128;
v12 = 112 * v6 + v8;
v81 = 112 * v6 + v8;
v13 = 112 * v6 + v8;
if ( v83 )
{
v14 = v13;
v15 = dMonster[1][v14 + 2];
if ( !v15 )
goto LABEL_74;
v16 = (dFlags[1][v12 + 2] & 0x40) == 0;
}
else
{
v14 = v13;
v15 = dMonster[2][v14 + 1];
if ( !v15 )
goto LABEL_74;
v16 = (dFlags[2][v12 + 1] & 0x40) == 0;
}
if ( !v16 )
{
v17 = v15 <= 0 ? -1 - v15 : v15 - 1;
if ( v17 == dword_4B8CCC
&& (signed int)(monster[v17]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v17].MData->mSelFlag & 4 )
{
v11 = v17;
cursmx = v6 + 1;
cursmy = v8 + 2;
pcursmonst = v17;
}
}
LABEL_74:
v18 = dMonster[2][v14 + 2];
if ( v18 && dFlags[2][v81 + 2] & 0x40 )
{
v19 = v18 <= 0 ? -1 - v18 : v18 - 1;
if ( v19 == dword_4B8CCC
&& (signed int)(monster[v19]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v19].MData->mSelFlag & 4 )
{
v11 = v19;
cursmx = v6 + 2;
cursmy = v8 + 2;
pcursmonst = v19;
}
}
if ( v83 )
{
v22 = dMonster[0][v14 + 1];
if ( v22 && dFlags[0][v81 + 1] & 0x40 )
{
v21 = v22 <= 0 ? -1 - v22 : v22 - 1;
if ( v21 == dword_4B8CCC
&& (signed int)(monster[v21]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v21].MData->mSelFlag & 2 )
{
cursmx = v6;
cursmy = v8 + 1;
goto LABEL_102;
}
}
}
else
{
v20 = dMonster[1][v14];
if ( v20 && dFlags[1][v81] & 0x40 )
{
v21 = v20 <= 0 ? -1 - v20 : v20 - 1;
if ( v21 == dword_4B8CCC
&& (signed int)(monster[v21]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v21].MData->mSelFlag & 2 )
{
cursmy = v8;
cursmx = v6 + 1;
LABEL_102:
v11 = v21;
pcursmonst = v21;
goto LABEL_103;
}
}
}
LABEL_103:
v23 = dMonster[0][v14];
if ( v23 && dFlags[0][v81] & 0x40 )
{
v24 = v23 <= 0 ? -1 - v23 : v23 - 1;
if ( v24 == dword_4B8CCC
&& (signed int)(monster[v24]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v24].MData->mSelFlag & 1 )
{
v11 = v24;
cursmx = v6;
cursmy = v8;
pcursmonst = v24;
}
}
v25 = dMonster[1][v14 + 1];
if ( v25 && dFlags[1][v81 + 1] & 0x40 )
{
v26 = v25 <= 0 ? -1 - v25 : v25 - 1;
if ( v26 == dword_4B8CCC
&& (signed int)(monster[v26]._mhitpoints & 0xFFFFFFC0) > 0
&& monster[v26].MData->mSelFlag & 2 )
{
v11 = v26;
cursmx = v6 + 1;
cursmy = v8 + 1;
pcursmonst = v26;
}
}
if ( v11 == -1 )
goto LABEL_128;
if ( monster[v11]._mFlags & 1 )
{
v11 = -1;
cursmx = v6;
pcursmonst = -1;
cursmy = v8;
}
if ( v11 == -1 )
goto LABEL_128;
if ( monster[v11]._mFlags & 0x20 )
{
v11 = -1;
pcursmonst = -1;
}
if ( v11 == -1 )
{
LABEL_128:
v27 = 112 * v6;
v78 = 112 * v6;
if ( v83 )
{
v28 = v27 + v8;
v32 = dMonster[1][v28 + 2];
if ( v32 && dFlags[1][v27 + 2 + v8] & 0x40 )
{
v30 = v32 <= 0 ? -1 - v32 : v32 - 1;
if ( (signed int)(monster[v30]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v30].MData->mSelFlag & 4 )
{
cursmx = v6 + 1;
v31 = v8 + 2;
goto LABEL_145;
}
}
}
else
{
v28 = v27 + v8;
v29 = dMonster[2][v28 + 1];
if ( v29 && dFlags[2][v27 + 1 + v8] & 0x40 )
{
v30 = v29 <= 0 ? -1 - v29 : v29 - 1;
if ( (signed int)(monster[v30]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v30].MData->mSelFlag & 4 )
{
cursmx = v6 + 2;
v31 = v8 + 1;
LABEL_145:
cursmy = v31;
pcursmonst = v30;
goto LABEL_146;
}
}
}
LABEL_146:
v33 = dMonster[2][v28 + 2];
if ( v33 && dFlags[2][v27 + 2 + v8] & 0x40 )
{
v34 = v33 <= 0 ? -1 - v33 : v33 - 1;
if ( (signed int)(monster[v34]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v34].MData->mSelFlag & 4 )
{
pcursmonst = v34;
cursmx = v6 + 2;
cursmy = v8 + 2;
}
}
if ( v83 )
{
v37 = dMonster[0][v28 + 1];
if ( v37 && dFlags[0][v27 + 1 + v8] & 0x40 )
{
v36 = v37 <= 0 ? -1 - v37 : v37 - 1;
if ( (signed int)(monster[v36]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v36].MData->mSelFlag & 2 )
{
cursmx = v6;
cursmy = v8 + 1;
goto LABEL_171;
}
}
}
else
{
v35 = dMonster[1][v28];
if ( v35 && dFlags[1][v27 + v8] & 0x40 )
{
v36 = v35 <= 0 ? -1 - v35 : v35 - 1;
if ( (signed int)(monster[v36]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v36].MData->mSelFlag & 2 )
{
cursmy = v8;
cursmx = v6 + 1;
LABEL_171:
pcursmonst = v36;
goto LABEL_172;
}
}
}
LABEL_172:
v38 = dMonster[0][v28];
if ( v38 && dFlags[0][v27 + v8] & 0x40 )
{
v39 = v38 <= 0 ? -1 - v38 : v38 - 1;
if ( (signed int)(monster[v39]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v39].MData->mSelFlag & 1 )
{
cursmx = v6;
cursmy = v8;
pcursmonst = v39;
}
}
v40 = dMonster[1][v28 + 1];
if ( v40 && dFlags[1][v27 + 1 + v8] & 0x40 )
{
v41 = v40 <= 0 ? -1 - v40 : v40 - 1;
if ( (signed int)(monster[v41]._mhitpoints & 0xFFFFFFC0) > 0 && monster[v41].MData->mSelFlag & 2 )
{
pcursmonst = v41;
cursmx = v6 + 1;
cursmy = v8 + 1;
}
}
v42 = pcursmonst;
if ( pcursmonst == -1 )
goto LABEL_207;
if ( monster[pcursmonst]._mFlags & 1 )
{
v42 = -1;
cursmx = v6;
pcursmonst = -1;
cursmy = v8;
}
if ( v42 == -1 )
goto LABEL_207;
if ( monster[v42]._mFlags & 0x20 )
goto LABEL_205;
goto LABEL_206;
}
}
// 4B8968: using guessed type int sbookflag;
// 4B8B84: using guessed type int panelflag;
// 4B8C98: using guessed type int spselflag;
// 4B8CB8: using guessed type char pcursinvitem;
// 4B8CC0: using guessed type char pcursitem;
// 4B8CC1: using guessed type char pcursobj;
// 4B8CC2: using guessed type char pcursplr;
// 4B8CCC: using guessed type int dword_4B8CCC;
// 52569C: using guessed type int zoomflag;
// 52575C: using guessed type int doomflag;
// 5BB1ED: using guessed type char leveltype;
// 69BD04: using guessed type int questlog;
| 17.096774
| 103
| 0.457682
|
codemaster
|
614044a6922e8af5f07399244208328f621b7fb8
| 22
|
cpp
|
C++
|
GBE/cpu/gb_cpu.cpp
|
OnyxFlames/GBE
|
6189f02b482f15ad59748f8739fc9d9c36390953
|
[
"MIT"
] | 1
|
2020-08-14T13:51:11.000Z
|
2020-08-14T13:51:11.000Z
|
GBE/cpu/gb_cpu.cpp
|
OnyxFlames/GBE
|
6189f02b482f15ad59748f8739fc9d9c36390953
|
[
"MIT"
] | null | null | null |
GBE/cpu/gb_cpu.cpp
|
OnyxFlames/GBE
|
6189f02b482f15ad59748f8739fc9d9c36390953
|
[
"MIT"
] | null | null | null |
#include "gb_cpu.hpp"
| 11
| 21
| 0.727273
|
OnyxFlames
|
6140e3ccf5f7cd20118def127da6670c27741c37
| 1,697
|
cpp
|
C++
|
week_03/05_manySines/src/ofApp.cpp
|
bschorr/OFAnimation_Spring2015
|
869ededa36bf0bd432129e5a551db5d19d1f5d35
|
[
"MIT"
] | 37
|
2015-01-28T13:20:19.000Z
|
2021-04-02T02:50:35.000Z
|
week_03/05_manySines/src/ofApp.cpp
|
bschorr/OFAnimation_Spring2015
|
869ededa36bf0bd432129e5a551db5d19d1f5d35
|
[
"MIT"
] | null | null | null |
week_03/05_manySines/src/ofApp.cpp
|
bschorr/OFAnimation_Spring2015
|
869ededa36bf0bd432129e5a551db5d19d1f5d35
|
[
"MIT"
] | 13
|
2015-02-06T23:16:22.000Z
|
2018-02-03T14:44:06.000Z
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(0);
ofNoFill();
ofSetCircleResolution(60);
for (float i = 0; i < 10; i++) {
customCircle myCirc;
myCirc.setup(i/5);
circleList.push_back(myCirc);
}
}
//--------------------------------------------------------------
void ofApp::update(){
for (int i = 0; i < circleList.size(); i++) {
circleList[i].update();
}
}
//--------------------------------------------------------------
void ofApp::draw(){
for (int i = 0; i < circleList.size(); i++) {
circleList[i].draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 21.2125
| 64
| 0.317619
|
bschorr
|
61410a3b5c8b68e167e87b55016d9865c2d58454
| 1,165
|
hpp
|
C++
|
include/frg/hash.hpp
|
czapek1337/frigg
|
ad1b6947047f492ed42b189fb208e600d9ec6915
|
[
"MIT"
] | 37
|
2018-11-05T19:15:46.000Z
|
2022-03-09T10:16:28.000Z
|
include/frg/hash.hpp
|
czapek1337/frigg
|
ad1b6947047f492ed42b189fb208e600d9ec6915
|
[
"MIT"
] | 13
|
2020-01-05T13:32:27.000Z
|
2022-03-09T17:21:07.000Z
|
include/frg/hash.hpp
|
czapek1337/frigg
|
ad1b6947047f492ed42b189fb208e600d9ec6915
|
[
"MIT"
] | 16
|
2020-01-01T15:45:02.000Z
|
2022-03-06T22:19:58.000Z
|
#ifndef FRG_HASH_HPP
#define FRG_HASH_HPP
#include <stdint.h>
#include <frg/macros.hpp>
namespace frg FRG_VISIBILITY {
template<typename T>
class hash;
template<>
class hash<uint64_t> {
public:
unsigned int operator() (uint64_t v) const {
static_assert(sizeof(unsigned int) == 4, "Expected sizeof(int) == 4");
return (unsigned int)(v ^ (v >> 32));
}
};
template<>
class hash<int64_t> {
public:
unsigned int operator() (int64_t v) const {
static_assert(sizeof(unsigned int) == 4, "Expected sizeof(int) == 4");
return (unsigned int)(v ^ (v >> 32));
}
};
template<>
class hash<int> {
public:
unsigned int operator() (int v) const {
return v;
}
};
template<>
class hash<unsigned int> {
public:
unsigned int operator() (int v) const {
return v;
}
};
template<typename T>
class hash<T *> {
public:
unsigned int operator() (T *p) const {
return reinterpret_cast<uintptr_t>(p);
}
};
class CStringHash {
public:
unsigned int operator() (const char *str) const {
unsigned int value = 0;
while(*str != 0) {
value = (value << 8) | (value >> 24);
value += *str++;
}
return value;
}
};
} // namespace frg
#endif // FRG_HASH_HPP
| 16.884058
| 72
| 0.650644
|
czapek1337
|
6141ac6be3fa1473965bfe0e106e9917a1f1fb1c
| 1,386
|
hpp
|
C++
|
include/bucket.hpp
|
SimonRussia/COURSEWORK
|
03846c649ff202dfdd7e69b0a639f69f737d1614
|
[
"MIT"
] | null | null | null |
include/bucket.hpp
|
SimonRussia/COURSEWORK
|
03846c649ff202dfdd7e69b0a639f69f737d1614
|
[
"MIT"
] | 1
|
2017-12-25T06:33:57.000Z
|
2018-01-31T21:50:53.000Z
|
include/bucket.hpp
|
SimonRussia/COURSEWORK
|
03846c649ff202dfdd7e69b0a639f69f737d1614
|
[
"MIT"
] | null | null | null |
// "Copyright [2017] <MGTU IU8-33>"
// BUCKET.HPP
/*!
\file
\brief bucket_sort
\details В данном файле реализован шаблонный алгоритм устойчивой сортировки BUCKET.
\author Овчаров Анисим
\date 20/12/2017
*/
#ifndef _BUCKET_HPP_
#define _BUCKET_HPP_
#include <iostream>
#include <algorithm>
#include <chrono>
#include <vector>
#include "message.hpp"
/*!
Функция bucket_sort.
Реализует сортировку массива используя алгоритм устойчивой сортировки BUCKET.
\param[in] arr[] - Массив, который необходимо отсортировать.
\param[in] size - Размер передаваемого массива.
\param[in] rad - Параметр для получения n-го порядка числа.
\snippet bucket.cpp bucket_sort_example
*/
template <typename T>
void bucket_sort(T arr[], int size, int rad) {
// 1) Создаем корзину
std::vector<T> bucket[size];
// 2) Распределяем массив в различные корзины
// (по n разряду) 256 -> [2]56
for (int i = 0; i < size; i++) {
int bi = arr[i] / rad;
bucket[bi].push_back(arr[i]);
}
// 3) Отдельно сортируем каждую корзину
for (int i = 0; i < size; i++)
std::sort(bucket[i].begin(), bucket[i].end());
// 4) Сливаем отсортированные части в исходный массив
int index = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < bucket[i].size(); j++)
arr[index++] = bucket[i][j];
}
#endif // _BUCKET_HPP_
| 24.315789
| 87
| 0.642857
|
SimonRussia
|
614337c61bcb0c280d1a7ec3e9e6b0e3c8760b68
| 13,610
|
cpp
|
C++
|
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableColElement.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | 1
|
2021-05-27T07:29:31.000Z
|
2021-05-27T07:29:31.000Z
|
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableColElement.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | null | null | null |
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMHTMLTableColElement.cpp
|
mlcldh/appleWebKit2
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
[
"MIT"
] | null | null | null |
/*
* This file is part of the WebKit open source project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "WebKitDOMHTMLTableColElement.h"
#include <WebCore/CSSImportRule.h>
#include "DOMObjectCache.h"
#include <WebCore/Document.h>
#include <WebCore/ExceptionCode.h>
#include <WebCore/ExceptionCodeDescription.h>
#include "GObjectEventListener.h"
#include <WebCore/HTMLNames.h>
#include <WebCore/JSMainThreadExecState.h>
#include "WebKitDOMEventPrivate.h"
#include "WebKitDOMEventTarget.h"
#include "WebKitDOMHTMLTableColElementPrivate.h"
#include "WebKitDOMNodePrivate.h"
#include "WebKitDOMPrivate.h"
#include "ConvertToUTF8String.h"
#include <wtf/GetPtr.h>
#include <wtf/RefPtr.h>
namespace WebKit {
WebKitDOMHTMLTableColElement* kit(WebCore::HTMLTableColElement* obj)
{
return WEBKIT_DOM_HTML_TABLE_COL_ELEMENT(kit(static_cast<WebCore::Node*>(obj)));
}
WebCore::HTMLTableColElement* core(WebKitDOMHTMLTableColElement* request)
{
return request ? static_cast<WebCore::HTMLTableColElement*>(WEBKIT_DOM_OBJECT(request)->coreObject) : 0;
}
WebKitDOMHTMLTableColElement* wrapHTMLTableColElement(WebCore::HTMLTableColElement* coreObject)
{
ASSERT(coreObject);
return WEBKIT_DOM_HTML_TABLE_COL_ELEMENT(g_object_new(WEBKIT_DOM_TYPE_HTML_TABLE_COL_ELEMENT, "core-object", coreObject, nullptr));
}
} // namespace WebKit
static gboolean webkit_dom_html_table_col_element_dispatch_event(WebKitDOMEventTarget* target, WebKitDOMEvent* event, GError** error)
{
WebCore::Event* coreEvent = WebKit::core(event);
if (!coreEvent)
return false;
WebCore::HTMLTableColElement* coreTarget = static_cast<WebCore::HTMLTableColElement*>(WEBKIT_DOM_OBJECT(target)->coreObject);
auto result = coreTarget->dispatchEventForBindings(*coreEvent);
if (result.hasException()) {
WebCore::ExceptionCodeDescription description(result.releaseException().code());
g_set_error_literal(error, g_quark_from_string("WEBKIT_DOM"), description.code, description.name);
return false;
}
return result.releaseReturnValue();
}
static gboolean webkit_dom_html_table_col_element_add_event_listener(WebKitDOMEventTarget* target, const char* eventName, GClosure* handler, gboolean useCapture)
{
WebCore::HTMLTableColElement* coreTarget = static_cast<WebCore::HTMLTableColElement*>(WEBKIT_DOM_OBJECT(target)->coreObject);
return WebKit::GObjectEventListener::addEventListener(G_OBJECT(target), coreTarget, eventName, handler, useCapture);
}
static gboolean webkit_dom_html_table_col_element_remove_event_listener(WebKitDOMEventTarget* target, const char* eventName, GClosure* handler, gboolean useCapture)
{
WebCore::HTMLTableColElement* coreTarget = static_cast<WebCore::HTMLTableColElement*>(WEBKIT_DOM_OBJECT(target)->coreObject);
return WebKit::GObjectEventListener::removeEventListener(G_OBJECT(target), coreTarget, eventName, handler, useCapture);
}
static void webkit_dom_event_target_init(WebKitDOMEventTargetIface* iface)
{
iface->dispatch_event = webkit_dom_html_table_col_element_dispatch_event;
iface->add_event_listener = webkit_dom_html_table_col_element_add_event_listener;
iface->remove_event_listener = webkit_dom_html_table_col_element_remove_event_listener;
}
G_DEFINE_TYPE_WITH_CODE(WebKitDOMHTMLTableColElement, webkit_dom_html_table_col_element, WEBKIT_DOM_TYPE_HTML_ELEMENT, G_IMPLEMENT_INTERFACE(WEBKIT_DOM_TYPE_EVENT_TARGET, webkit_dom_event_target_init))
enum {
PROP_0,
PROP_ALIGN,
PROP_CH,
PROP_CH_OFF,
PROP_SPAN,
PROP_V_ALIGN,
PROP_WIDTH,
};
static void webkit_dom_html_table_col_element_set_property(GObject* object, guint propertyId, const GValue* value, GParamSpec* pspec)
{
WebKitDOMHTMLTableColElement* self = WEBKIT_DOM_HTML_TABLE_COL_ELEMENT(object);
switch (propertyId) {
case PROP_ALIGN:
webkit_dom_html_table_col_element_set_align(self, g_value_get_string(value));
break;
case PROP_CH:
webkit_dom_html_table_col_element_set_ch(self, g_value_get_string(value));
break;
case PROP_CH_OFF:
webkit_dom_html_table_col_element_set_ch_off(self, g_value_get_string(value));
break;
case PROP_SPAN:
webkit_dom_html_table_col_element_set_span(self, g_value_get_long(value));
break;
case PROP_V_ALIGN:
webkit_dom_html_table_col_element_set_v_align(self, g_value_get_string(value));
break;
case PROP_WIDTH:
webkit_dom_html_table_col_element_set_width(self, g_value_get_string(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
static void webkit_dom_html_table_col_element_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec)
{
WebKitDOMHTMLTableColElement* self = WEBKIT_DOM_HTML_TABLE_COL_ELEMENT(object);
switch (propertyId) {
case PROP_ALIGN:
g_value_take_string(value, webkit_dom_html_table_col_element_get_align(self));
break;
case PROP_CH:
g_value_take_string(value, webkit_dom_html_table_col_element_get_ch(self));
break;
case PROP_CH_OFF:
g_value_take_string(value, webkit_dom_html_table_col_element_get_ch_off(self));
break;
case PROP_SPAN:
g_value_set_long(value, webkit_dom_html_table_col_element_get_span(self));
break;
case PROP_V_ALIGN:
g_value_take_string(value, webkit_dom_html_table_col_element_get_v_align(self));
break;
case PROP_WIDTH:
g_value_take_string(value, webkit_dom_html_table_col_element_get_width(self));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
static void webkit_dom_html_table_col_element_class_init(WebKitDOMHTMLTableColElementClass* requestClass)
{
GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass);
gobjectClass->set_property = webkit_dom_html_table_col_element_set_property;
gobjectClass->get_property = webkit_dom_html_table_col_element_get_property;
g_object_class_install_property(
gobjectClass,
PROP_ALIGN,
g_param_spec_string(
"align",
"HTMLTableColElement:align",
"read-write gchar* HTMLTableColElement:align",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
PROP_CH,
g_param_spec_string(
"ch",
"HTMLTableColElement:ch",
"read-write gchar* HTMLTableColElement:ch",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
PROP_CH_OFF,
g_param_spec_string(
"ch-off",
"HTMLTableColElement:ch-off",
"read-write gchar* HTMLTableColElement:ch-off",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
PROP_SPAN,
g_param_spec_long(
"span",
"HTMLTableColElement:span",
"read-write glong HTMLTableColElement:span",
G_MINLONG, G_MAXLONG, 0,
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
PROP_V_ALIGN,
g_param_spec_string(
"v-align",
"HTMLTableColElement:v-align",
"read-write gchar* HTMLTableColElement:v-align",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
PROP_WIDTH,
g_param_spec_string(
"width",
"HTMLTableColElement:width",
"read-write gchar* HTMLTableColElement:width",
"",
WEBKIT_PARAM_READWRITE));
}
static void webkit_dom_html_table_col_element_init(WebKitDOMHTMLTableColElement* request)
{
UNUSED_PARAM(request);
}
gchar* webkit_dom_html_table_col_element_get_align(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->attributeWithoutSynchronization(WebCore::HTMLNames::alignAttr));
return result;
}
void webkit_dom_html_table_col_element_set_align(WebKitDOMHTMLTableColElement* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
g_return_if_fail(value);
WebCore::HTMLTableColElement* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAttributeWithoutSynchronization(WebCore::HTMLNames::alignAttr, convertedValue);
}
gchar* webkit_dom_html_table_col_element_get_ch(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->attributeWithoutSynchronization(WebCore::HTMLNames::charAttr));
return result;
}
void webkit_dom_html_table_col_element_set_ch(WebKitDOMHTMLTableColElement* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
g_return_if_fail(value);
WebCore::HTMLTableColElement* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAttributeWithoutSynchronization(WebCore::HTMLNames::charAttr, convertedValue);
}
gchar* webkit_dom_html_table_col_element_get_ch_off(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->attributeWithoutSynchronization(WebCore::HTMLNames::charoffAttr));
return result;
}
void webkit_dom_html_table_col_element_set_ch_off(WebKitDOMHTMLTableColElement* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
g_return_if_fail(value);
WebCore::HTMLTableColElement* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAttributeWithoutSynchronization(WebCore::HTMLNames::charoffAttr, convertedValue);
}
glong webkit_dom_html_table_col_element_get_span(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
glong result = item->span();
return result;
}
void webkit_dom_html_table_col_element_set_span(WebKitDOMHTMLTableColElement* self, glong value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
WebCore::HTMLTableColElement* item = WebKit::core(self);
item->setSpan(value);
}
gchar* webkit_dom_html_table_col_element_get_v_align(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->attributeWithoutSynchronization(WebCore::HTMLNames::valignAttr));
return result;
}
void webkit_dom_html_table_col_element_set_v_align(WebKitDOMHTMLTableColElement* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
g_return_if_fail(value);
WebCore::HTMLTableColElement* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAttributeWithoutSynchronization(WebCore::HTMLNames::valignAttr, convertedValue);
}
gchar* webkit_dom_html_table_col_element_get_width(WebKitDOMHTMLTableColElement* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self), 0);
WebCore::HTMLTableColElement* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->attributeWithoutSynchronization(WebCore::HTMLNames::widthAttr));
return result;
}
void webkit_dom_html_table_col_element_set_width(WebKitDOMHTMLTableColElement* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_TABLE_COL_ELEMENT(self));
g_return_if_fail(value);
WebCore::HTMLTableColElement* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAttributeWithoutSynchronization(WebCore::HTMLNames::widthAttr, convertedValue);
}
| 38.885714
| 201
| 0.759589
|
mlcldh
|
61450b6c9744cc3bcafe9ee8a3851080d876d641
| 2,164
|
hh
|
C++
|
arm-linux-ulibc-4.8.5/usr/arm-nuvoton-linux-uclibcgnueabi/sysroot/usr/include/log4cpp/SyslogAppender.hh
|
next-generate/armv5TE-toolchain
|
8f107ce06fdc6d7f6e56f3b1b1c9f0f13cfa6727
|
[
"Apache-2.0"
] | 26
|
2019-06-02T15:22:01.000Z
|
2022-03-11T06:54:23.000Z
|
arm-linux-ulibc-4.8.5/usr/arm-nuvoton-linux-uclibcgnueabi/sysroot/usr/include/log4cpp/SyslogAppender.hh
|
next-generate/armv5TE-toolchain
|
8f107ce06fdc6d7f6e56f3b1b1c9f0f13cfa6727
|
[
"Apache-2.0"
] | 26
|
2019-09-20T06:46:05.000Z
|
2022-03-11T08:07:14.000Z
|
arm-linux-ulibc-4.8.5/usr/arm-nuvoton-linux-uclibcgnueabi/sysroot/usr/include/log4cpp/SyslogAppender.hh
|
next-generate/armv5TE-toolchain
|
8f107ce06fdc6d7f6e56f3b1b1c9f0f13cfa6727
|
[
"Apache-2.0"
] | 18
|
2019-06-02T13:00:17.000Z
|
2022-01-21T13:12:29.000Z
|
/*
* SyslogAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_SYSLOGAPPENDER_HH
#define _LOG4CPP_SYSLOGAPPENDER_HH
#include <log4cpp/Portability.hh>
#include <string>
#include <stdarg.h>
#include <syslog.h>
#include <log4cpp/LayoutAppender.hh>
#include <log4cpp/Priority.hh>
namespace log4cpp {
/**
* SyslogAppender sends LoggingEvents to the local syslog system.
**/
class SyslogAppender : public LayoutAppender {
public:
/**
* Translates a log4cpp priority to a syslog priority
* @param priority The log4cpp priority.
* @returns the syslog priority.
**/
static int toSyslogPriority(Priority::Value priority);
/**
* Instantiate a SyslogAppender with given name and name and facility
* for syslog. Note that the C syslog API is process global, so
* instantion of a second SyslogAppender will 'overwrite' the
* syslog name of the first.
* @param name The name of the Appender
* @param syslogName The ident parameter in the openlog(3) call.
* @param facility The syslog facility to log to. Defaults to LOG_USER.
**/
SyslogAppender(const std::string& name, const std::string& syslogName,
int facility = LOG_USER);
virtual ~SyslogAppender();
/**
* Calls closelog(3) and openlog(3).
**/
virtual bool reopen();
/**
* Calls closelog(3) to close the syslog file descriptor.
**/
virtual void close();
protected:
/**
* Calls openlog(3).
**/
virtual void open();
/**
* Sends a LoggingEvent to syslog.
* @param event the LoggingEvent to log.
**/
virtual void _append(const LoggingEvent& event);
const std::string _syslogName;
int _facility;
};
}
#endif // _LOG4CPP_SYSLOGAPPENDER_HH
| 28.103896
| 79
| 0.610444
|
next-generate
|
61489422b315a12fd5b36740808512f936cb5291
| 9,568
|
cpp
|
C++
|
orion_protocol/test/test_orion_major.cpp
|
ros-ukraine/orion
|
050d9df15c2b8e58d42a2b1aa467f08a14da099f
|
[
"MIT"
] | null | null | null |
orion_protocol/test/test_orion_major.cpp
|
ros-ukraine/orion
|
050d9df15c2b8e58d42a2b1aa467f08a14da099f
|
[
"MIT"
] | null | null | null |
orion_protocol/test/test_orion_major.cpp
|
ros-ukraine/orion
|
050d9df15c2b8e58d42a2b1aa467f08a14da099f
|
[
"MIT"
] | null | null | null |
/**
* Copyright 2021 ROS Ukraine
*
* 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 <gtest/gtest.h>
#include <gmock/gmock.h>
#include "gmock-global/gmock-global.h"
#include "orion_protocol/orion_transport.hpp"
#include "orion_protocol/orion_communication.hpp"
#include "orion_protocol/orion_header.hpp"
#include "orion_protocol/orion_major.hpp"
using ::testing::Eq;
using ::testing::Gt;
using ::testing::Le;
using ::testing::_;
using ::testing::NotNull;
using ::testing::Invoke;
using ::testing::Return;
#pragma pack(push, 1)
struct HandshakeCommand
{
orion::CommandHeader header =
{
.frame = { .crc = 0 },
.common = { .message_id = 2, .version = 1, .oldest_compatible_version = 1, .sequence_id = 0 }
};
};
struct HandshakeResult
{
orion::ResultHeader header =
{
.frame = { .crc = 0 },
.common = { .message_id = 2, .version = 1, .oldest_compatible_version = 1, .sequence_id = 0 },
.error_code = 0
};
};
#pragma pack(pop)
MOCK_GLOBAL_FUNC1(orion_communication_new, orion_communication_error_t(orion_communication_t ** me));
MOCK_GLOBAL_FUNC1(orion_communication_delete, orion_communication_error_t(const orion_communication_t * me));
class MockCommunication: public orion::Communication
{
public:
MOCK_METHOD2(receiveAvailableBuffer, ssize_t(uint8_t *buffer, uint32_t size));
MOCK_METHOD3(receiveBuffer, ssize_t(uint8_t *buffer, uint32_t size, uint32_t timeout));
MOCK_METHOD0(hasAvailableBuffer, bool());
MOCK_METHOD3(sendBuffer, orion_communication_error_t(uint8_t *buffer, uint32_t size, uint32_t timeout));
};
MOCK_GLOBAL_FUNC2(orion_transport_new, orion_transport_error_t(orion_transport_t ** me,
orion_communication_t * communication));
MOCK_GLOBAL_FUNC1(orion_transport_delete, orion_transport_error_t(const orion_transport_t * me));
class MockTransport: public orion::Transport
{
public:
explicit MockTransport(orion::Communication * communication) : orion::Transport(communication) {}
MOCK_METHOD3(sendPacket, orion_transport_error_t(uint8_t *input_buffer, uint32_t input_size, uint32_t timeout));
MOCK_METHOD3(receivePacket, ssize_t(uint8_t *output_buffer, uint32_t output_size, uint32_t timeout));
MOCK_METHOD0(hasReceivedPacket, bool());
};
TEST(TestSuite, sendPacketTimeoutExpiredException)
{
EXPECT_GLOBAL_CALL(orion_communication_new, orion_communication_new(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_communication_delete, orion_communication_delete(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
MockCommunication mock_communication;
EXPECT_GLOBAL_CALL(orion_transport_new, orion_transport_new(_, _)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_transport_delete, orion_transport_delete(_)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
MockTransport mock_transport(&mock_communication);
orion::Major main(&mock_transport);
HandshakeCommand command;
HandshakeResult result;
uint8_t retry_count = 3;
uint32_t retry_timeout = orion::Major::Interval::Microsecond * 200;
EXPECT_CALL(mock_transport, sendPacket(NotNull(), Gt(0), Eq(retry_timeout))).WillRepeatedly(Return(
ORION_TRAN_ERROR_TIMEOUT));
EXPECT_CALL(mock_transport, hasReceivedPacket()).Times(0);
EXPECT_CALL(mock_transport, receivePacket(NotNull(), Gt(0), Le(retry_timeout))).Times(0);
orion_major_error_t status = main.invoke(command, &result, retry_timeout, retry_count);
EXPECT_EQ(ORION_MAJOR_ERROR_TIMEOUT, status);
}
TEST(TestSuite, happyPath)
{
EXPECT_GLOBAL_CALL(orion_communication_new, orion_communication_new(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_communication_delete, orion_communication_delete(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
MockCommunication mock_communication;
EXPECT_GLOBAL_CALL(orion_transport_new, orion_transport_new(_, _)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_transport_delete, orion_transport_delete(_)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
MockTransport mock_transport(&mock_communication);
orion::Major main(&mock_transport);
HandshakeCommand command;
HandshakeResult result;
uint8_t retry_count = 5;
uint32_t retry_timeout = orion::Major::Interval::Microsecond * 400;
EXPECT_CALL(mock_transport, sendPacket(NotNull(), Gt(0), Le(retry_timeout))).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_CALL(mock_transport, hasReceivedPacket()).Times(0);
auto mock_receive_packet = [](uint8_t *output_buffer, uint32_t output_size, uint32_t timeout)
{
size_t size = sizeof(HandshakeResult);
HandshakeResult reply_result;
reply_result.header.common.sequence_id = 1;
std::memcpy(output_buffer, reinterpret_cast<const uint8_t*>(&reply_result), size);
return size;
};
EXPECT_CALL(mock_transport, receivePacket(NotNull(), Gt(0), Le(retry_timeout))).WillOnce(Invoke(mock_receive_packet));
main.invoke(command, &result, retry_timeout, retry_count);
}
TEST(TestSuite, incompatibleVersion)
{
EXPECT_GLOBAL_CALL(orion_communication_new, orion_communication_new(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_communication_delete, orion_communication_delete(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
MockCommunication mock_communication;
EXPECT_GLOBAL_CALL(orion_transport_new, orion_transport_new(_, _)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_transport_delete, orion_transport_delete(_)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
MockTransport mock_transport(&mock_communication);
orion::Major main(&mock_transport);
HandshakeCommand command;
HandshakeResult result;
result.header.common.version = 1;
result.header.common.oldest_compatible_version = 1;
uint8_t retry_count = 2;
uint32_t retry_timeout = orion::Major::Interval::Microsecond * 300;
EXPECT_CALL(mock_transport, sendPacket(NotNull(), Gt(0), Le(retry_timeout))).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_CALL(mock_transport, hasReceivedPacket()).Times(0);
auto mock_receive_packet = [](uint8_t *output_buffer, uint32_t output_size, uint32_t timeout)
{
size_t size = sizeof(HandshakeResult);
HandshakeResult reply_result;
reply_result.header.common.sequence_id = 1;
reply_result.header.common.version = 2;
reply_result.header.common.oldest_compatible_version = 2;
std::memcpy(output_buffer, reinterpret_cast<const uint8_t*>(&reply_result), size);
return size;
};
EXPECT_CALL(mock_transport, receivePacket(NotNull(), Gt(0), Le(retry_timeout))).WillOnce(Invoke(mock_receive_packet));
orion_major_error_t status = main.invoke(command, &result, retry_timeout, retry_count);
EXPECT_EQ(ORION_MAJOR_ERROR_NOT_COMPATIBLE_PACKET_VERSION, status);
}
TEST(TestSuite, errorInReply)
{
EXPECT_GLOBAL_CALL(orion_communication_new, orion_communication_new(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_communication_delete, orion_communication_delete(_)).WillOnce(Return(ORION_COM_ERROR_NONE));
MockCommunication mock_communication;
EXPECT_GLOBAL_CALL(orion_transport_new, orion_transport_new(_, _)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_GLOBAL_CALL(orion_transport_delete, orion_transport_delete(_)).WillOnce(Return(ORION_TRAN_ERROR_NONE));
MockTransport mock_transport(&mock_communication);
orion::Major main(&mock_transport);
HandshakeCommand command;
HandshakeResult result;
uint8_t retry_count = 2;
uint32_t retry_timeout = orion::Major::Interval::Microsecond * 500;
EXPECT_CALL(mock_transport, sendPacket(NotNull(), Gt(0), Eq(retry_timeout))).WillOnce(Return(ORION_TRAN_ERROR_NONE));
EXPECT_CALL(mock_transport, hasReceivedPacket()).Times(0);
auto mock_receive_packet = [](uint8_t *output_buffer, uint32_t output_size, uint32_t timeout)
{
size_t size = sizeof(HandshakeResult);
HandshakeResult reply_result;
reply_result.header.common.sequence_id = 1;
reply_result.header.error_code = 12;
std::memcpy(output_buffer, reinterpret_cast<const uint8_t*>(&reply_result), size);
return size;
};
EXPECT_CALL(mock_transport, receivePacket(NotNull(), Gt(0), Le(retry_timeout))).WillOnce(Invoke(mock_receive_packet));
orion_major_error_t status = main.invoke(command, &result, retry_timeout, retry_count);
EXPECT_EQ(ORION_MAJOR_ERROR_APPLICATION_ERROR_RECEIVED, status);
// TODO(Andriy): How to pass error code?
// EXPECT_EQ(12, result.header.error_code);
}
int main(int argc, char **argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
| 41.781659
| 120
| 0.78449
|
ros-ukraine
|
614c4bb25c8a30d9512643ee5fbfa7a1c4072002
| 586
|
cpp
|
C++
|
03-Making Decisions/Program_4-30.cpp
|
ringosimonchen0820/How-to-C--
|
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
|
[
"MIT"
] | null | null | null |
03-Making Decisions/Program_4-30.cpp
|
ringosimonchen0820/How-to-C--
|
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
|
[
"MIT"
] | 1
|
2020-10-11T18:39:08.000Z
|
2020-10-11T18:39:17.000Z
|
03-Making Decisions/Program_4-30.cpp
|
ringosimonchen0820/How-to-C--
|
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
|
[
"MIT"
] | 2
|
2020-10-12T20:33:32.000Z
|
2020-10-12T20:34:00.000Z
|
// This program uses two variables with the name number.
#include <iostream>
using namespace std;
int main()
{
// Define a variable named number.
int number;
cout << "Enter a number greater than 0: ";
cin >> number;
if (number > 0)
{
int number; // Another variable named number.
cout << "Now enter another number: ";
cin >> number;
cout << "The second number you entered was "
<< number
<< endl;
}
cout << "Your first number was "
<< number
<< endl;
return 0;
}
| 20.206897
| 56
| 0.535836
|
ringosimonchen0820
|
614cd7748f25e025682cad3a3ee08a10af5249cf
| 1,225
|
cpp
|
C++
|
test/environment_self.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | 14
|
2020-12-22T21:20:10.000Z
|
2022-03-15T21:27:51.000Z
|
test/environment_self.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | 11
|
2020-05-09T20:57:21.000Z
|
2020-06-10T00:00:17.000Z
|
test/environment_self.cpp
|
correaa/b-mpi3
|
161e52a28ab9043be9ef33acd8f31dbeae483b61
|
[
"BSL-1.0"
] | null | null | null |
#if COMPILATION_INSTRUCTIONS
mpicxx -O3 -std=c++14 `#-Wfatal-errors` $0 -o $0x.x && time mpirun -np 4 -H localhost,localhost,localhost,localhost,localhost $0x.x $@ && rm -f $0x.x; exit
#endif
// (C) Copyright Alfredo A. Correa 2018.
#include "../../mpi3/environment.hpp"
using std::cout;
namespace mpi3 = boost::mpi3;
int main(){
mpi3::environment env;
cout << "us " << env.get_world_instance().get_attribute_as<int>(mpi3::universe_size) << std::endl;
return 0;
auto self = env.self();
assert( self.size() == 1 );
assert( self.rank() == 0 );
cout << "I am process " << self.rank() << " in communicator " << self.name() << std::endl;
auto world = env.world();
world.barrier();
assert( world.size() == 4 );
assert( world.rank() < 4 );
cout << "I am process " << world.rank() << " in communicator " << world.name() << std::endl;
/* output:
I am process 0 in communicator MPI_COMM_SELF
I am process 0 in communicator MPI_COMM_SELF
I am process 0 in communicator MPI_COMM_SELF
I am process 0 in communicator MPI_COMM_SELF
I am process 3 in communicator MPI_COMM_WORLD
I am process 0 in communicator MPI_COMM_WORLD
I am process 1 in communicator MPI_COMM_WORLD
I am process 2 in communicator MPI_COMM_WORLD
*/
}
| 32.236842
| 155
| 0.691429
|
correaa
|
61546a609099e35573897c7d5f9e9196aefa32f0
| 21,190
|
cpp
|
C++
|
src/Leddar/LdLjrRecorder.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | null | null | null |
src/Leddar/LdLjrRecorder.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | null | null | null |
src/Leddar/LdLjrRecorder.cpp
|
deucedrone/LeddarSDK
|
c1deb6621e8ad845341e0185763c4a7706ecb788
|
[
"BSD-3-Clause"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file Leddar/LdLjrRecorder.cpp
///
/// \brief Implements the LdLjrRecorder class
/// A recorder using json lines format
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "LdLjrRecorder.h"
#include "LdLjrDefines.h"
#include "LdPropertyIds.h"
#include "LtStringUtils.h"
#include "LtSystemUtils.h"
#include "rapidjson/writer.h"
#include <ctime>
#include <cerrno>
#include <iostream>
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn LeddarRecord::LdLjrRecorder::LdLjrRecorder( LeddarDevice::LdSensor *aSensor )
///
/// \brief Constructor
///
/// \param [in] aSensor The sensor to record from.
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
LeddarRecord::LdLjrRecorder::LdLjrRecorder( LeddarDevice::LdSensor *aSensor ) : LdRecorder( aSensor ),
mOutStream( nullptr ),
mFile( nullptr ),
mLastTimestamp( 0 )
{
mStringBuffer = new rapidjson::StringBuffer;
mWriter = new rapidjson::Writer<rapidjson::StringBuffer, rapidjson::UTF8<char>, rapidjson::UTF8<char>, rapidjson::CrtAllocator, 0>( *mStringBuffer );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn LeddarRecord::LdLjrRecorder::~LdLjrRecorder()
///
/// \brief Destructor
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
LeddarRecord::LdLjrRecorder::~LdLjrRecorder()
{
LdLjrRecorder::StopRecording();
if( mStringBuffer != nullptr )
{
delete mStringBuffer;
mStringBuffer = nullptr;
}
if( mWriter != nullptr )
{
delete mWriter;
mWriter = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn std::string LeddarRecord::LdLjrRecorder::StartRecording( const std::string &aPath )
///
/// \brief Starts recording data from the sensor Create file headers / properties
///
/// \exception std::invalid_argument Raised when the file already exist.
/// \exception std::logic_error Raised when a a recording is already running.
/// \exception std::runtime_error Raised when a the file could not be created.
///
/// \param aPath (optional) Pathname of the record. - "stdout" to write to standard output
///
/// \return Pathname of the record.
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
std::string LeddarRecord::LdLjrRecorder::StartRecording( const std::string &aPath )
{
if( mOutStream != nullptr )
{
throw std::logic_error( "Already recording" );
}
std::string lPath = aPath;
bool lIsDir = LeddarUtils::LtSystemUtils::DirectoryExists( lPath );
if( lIsDir )
{
#ifdef _WIN32
if( lPath.back() != '\\' )
{
lPath.push_back( '\\' );
}
#else
if( lPath.back() != '/' )
{
lPath.push_back( '/' );
}
#endif
}
if( aPath == "" || lIsDir )
{
std::time_t lTime = std::time( nullptr );
char lStr[100];
std::strftime( lStr, sizeof( lStr ), "%Y-%m-%d_%H-%M-%S", std::localtime( &lTime ) );
if( mSensor->GetProperties()->FindProperty( LeddarCore::LdPropertyIds::ID_DEVICE_NAME ) != nullptr &&
mSensor->GetProperties()->FindProperty( LeddarCore::LdPropertyIds::ID_DEVICE_NAME )->Count() > 0 )
lPath = mSensor->GetProperties()->GetTextProperty( LeddarCore::LdPropertyIds::ID_DEVICE_NAME )->GetStringValue() + "_" + std::string( lStr );
else
lPath += "UnknownDevice_" + std::string( lStr );
}
if( LeddarUtils::LtStringUtils::ToLower( aPath ) != "stdout" &&
( ( lPath.length() >= 4 && LeddarUtils::LtStringUtils::ToLower( lPath ).compare( lPath.length() - 4, 4, ".ljr" ) ) ||
lPath.length() < 4 ) )
{
lPath += ".ljr";
}
std::streambuf *lStreamBuffer;
if( LeddarUtils::LtStringUtils::ToLower( aPath ) == "stdout" )
{
lStreamBuffer = std::cout.rdbuf();
}
else
{
std::ifstream infile( aPath.c_str() );
if( infile.good() )
{
throw std::invalid_argument( "File already exist" );
}
mFile = new std::ofstream;
mFile->open( lPath.c_str(), std::ios_base::out ); //c_str for c++98
if( !mFile->is_open() )
{
throw std::logic_error( "Could not create file - Error code: " + LeddarUtils::LtSystemUtils::ErrnoToString( errno ) );
}
lStreamBuffer = mFile->rdbuf();
}
mOutStream = new std::ostream( lStreamBuffer );
AddFileHeader();
AddAllProperties();
return lPath;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::StopRecording()
///
/// \brief Stops the recording (if any) - Called automatically when the object is destroyed
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::StopRecording()
{
if( !mWriter->IsComplete() && mStringBuffer->GetSize() != 0 ) //Last frame should still be open - Need to check size, because a reset mWriter is not complete
{
mWriter->EndObject(); //frame
mWriter->EndObject(); //main object
*mOutStream << mStringBuffer->GetString() << std::endl;
}
if( mFile->is_open() )
{
mFile->close();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::AddFileHeader()
///
/// \brief Adds file header (first line of the file)
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::AddFileHeader()
{
mWriter->StartObject(); //Main object
mWriter->Key( "header" );
mWriter->StartObject(); //header object
mWriter->Key( "prot_version" );
mWriter->Uint( LeddarRecord::LJR_PROT_VERSION );
mWriter->Key( "devicetype" );
mWriter->Uint( mSensor->GetConnection()->GetDeviceType() );
mWriter->Key( "protocol" );
mWriter->Uint( mSensor->GetProperties()->GetIntegerProperty( LeddarCore::LdPropertyIds::ID_CONNECTION_TYPE )->ValueT<uint16_t>( 0 ) );
mWriter->Key( "timestamp" );
mWriter->Uint64( std::time( nullptr ) );
mWriter->EndObject();//header object
mWriter->EndObject(); //Main object
if( !mWriter->IsComplete() )
{
throw std::logic_error( "invalid json" );
}
*mOutStream << mStringBuffer->GetString() << std::endl;
mStringBuffer->Clear();
mWriter->Reset( *mStringBuffer );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::AddAllProperties()
///
/// \brief Adds all properties to the record. It should be the second line of the file
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::AddAllProperties()
{
mWriter->StartObject(); //Main object
mWriter->Key( "prop" );
mWriter->StartArray(); //Prop array
std::vector<LeddarCore::LdProperty *> lProperties = mSensor->GetProperties()->FindPropertiesByFeature( LeddarCore::LdProperty::F_SAVE );
for( std::vector<LeddarCore::LdProperty *>::iterator lIter = lProperties.begin(); lIter != lProperties.end(); ++lIter )
{
LeddarCore::LdProperty *lProp = *lIter;
if( lProp->Count() == 0 )
continue;
mWriter->StartObject(); // a single property
mWriter->Key( "id" );
mWriter->Uint( lProp->GetId() );
if( lProp->GetType() == LeddarCore::LdProperty::TYPE_FLOAT )
{
mWriter->Key( "limits" );
mWriter->StartArray();
mWriter->Double( dynamic_cast<LeddarCore::LdFloatProperty *>( lProp )->MinValue() );
mWriter->Double( dynamic_cast<LeddarCore::LdFloatProperty *>( lProp )->MaxValue() );
mWriter->EndArray();
}
else if( lProp->GetType() == LeddarCore::LdProperty::TYPE_INTEGER )
{
mWriter->Key( "signed" );
mWriter->Bool( dynamic_cast<LeddarCore::LdIntegerProperty *>( lProp )->Signed() );
mWriter->Key( "limits" );
mWriter->StartArray();
if( dynamic_cast<const LeddarCore::LdIntegerProperty *>( lProp )->Signed() )
{
mWriter->Int64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( lProp )->MinValue() );
mWriter->Int64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( lProp )->MaxValue() );
}
else
{
mWriter->Uint64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( lProp )->MinValueT<uint64_t>() );
mWriter->Uint64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( lProp )->MaxValueT<uint64_t>() );
}
mWriter->EndArray();
}
else if( lProp->GetType() == LeddarCore::LdProperty::TYPE_ENUM )
{
LeddarCore::LdEnumProperty *lEnumProp = dynamic_cast<LeddarCore::LdEnumProperty *>( lProp );
mWriter->Key( "enum" );
mWriter->StartObject();
for( size_t i = 0; i < lEnumProp->EnumSize(); ++i )
{
mWriter->Key( lEnumProp->EnumText( i ).c_str() );
mWriter->Uint64( lEnumProp->EnumValue( i ) );
}
mWriter->EndObject();
}
AddPropertyValues( lProp );
mWriter->EndObject(); // a single property
}
mWriter->EndArray(); //Prop array
mWriter->EndObject(); //Main object
if( !mWriter->IsComplete() )
{
throw std::logic_error( "invalid json" );
}
*mOutStream << mStringBuffer->GetString() << std::endl;
mStringBuffer->Clear();
mWriter->Reset( *mStringBuffer );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::AddPropertyValues( const LeddarCore::LdProperty *aProperty, rapidjson::Writer<rapidjson::StringBuffer> &aWriter )
///
/// \brief Adds a property values to the current json line
///
/// \exception std::logic_error Raised when there is an unhandled property type.
///
/// \param aProperty The property to write to the Json. \param [in,out] aWriter The Json writer.
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::AddPropertyValues( const LeddarCore::LdProperty *aProperty )
{
if( aProperty->Count() == 0 )
return;
mWriter->Key( "val" );
if( aProperty->Count() > 1 )
{
mWriter->StartArray();
}
switch( aProperty->GetType() )
{
case LeddarCore::LdProperty::TYPE_BITFIELD:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->Uint64( dynamic_cast<const LeddarCore::LdBitFieldProperty *>( aProperty )->Value( i ) );
}
break;
case LeddarCore::LdProperty::TYPE_BOOL:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->Bool( dynamic_cast<const LeddarCore::LdBoolProperty *>( aProperty )->Value( i ) );
}
break;
case LeddarCore::LdProperty::TYPE_ENUM:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->Uint64( dynamic_cast<const LeddarCore::LdEnumProperty *>( aProperty )->Value( i ) );
}
break;
case LeddarCore::LdProperty::TYPE_FLOAT:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->Double( dynamic_cast<const LeddarCore::LdFloatProperty *>( aProperty )->Value( i ) );
}
break;
case LeddarCore::LdProperty::TYPE_INTEGER:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
if( dynamic_cast<const LeddarCore::LdIntegerProperty *>( aProperty )->Signed() )
{
mWriter->Int64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( aProperty )->ValueT<int32_t>( i ) );
}
else
{
mWriter->Uint64( dynamic_cast<const LeddarCore::LdIntegerProperty *>( aProperty )->ValueT<uint64_t>( i ) );
}
}
break;
case LeddarCore::LdProperty::TYPE_TEXT:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->String( dynamic_cast<const LeddarCore::LdTextProperty *>( aProperty )->GetStringValue( i ).c_str() );
}
break;
case LeddarCore::LdProperty::TYPE_BUFFER:
for( size_t i = 0; i < aProperty->Count(); ++i )
{
mWriter->String( dynamic_cast<const LeddarCore::LdBufferProperty *>( aProperty )->GetStringValue( i ).c_str() );
}
break;
default:
throw std::logic_error( "Unhandled property type" );
}
if( aProperty->Count() > 1 )
{
mWriter->EndArray();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::AddProperty( const LeddarCore::LdProperty *aProperty, rapidjson::Writer<rapidjson::StringBuffer> &aWriter )
///
/// \brief Adds a single property to the Json writer as an object
///
/// \param aProperty The property to save.
/// \param [in,out] aWriter The writer.
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::AddProperty( const LeddarCore::LdProperty *aProperty )
{
mWriter->StartObject(); //a single property
mWriter->Key( "id" );
mWriter->Uint( aProperty->GetId() );
AddPropertyValues( aProperty );
mWriter->EndObject();//a single property
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::Callback( LdObject *aSender, const SIGNALS aSignal, void * )
///
/// \brief Callback function that handle new data or property change
///
/// \param [in] aSender The sender.
/// \param aSignal The type of the callback.
/// \param [in,out] parameter3 If non-null, additional parameters.
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::Callback( LdObject *aSender, const SIGNALS aSignal, void * )
{
if( mOutStream == nullptr )
return;
if( aSignal == LeddarCore::LdObject::NEW_DATA )
{
if( aSender == mStates )
{
if( mStates->GetTimestamp() != mLastTimestamp )
{
if( mLastTimestamp != 0 )
{
EndFrame();
}
StartFrame( mStates );
}
StatesCallback();
mLastTimestamp = mStates->GetTimestamp();
}
else if( aSender == mEchoes )
{
if( mEchoes->GetTimestamp() != mLastTimestamp )
{
if( mLastTimestamp != 0 )
{
EndFrame();
}
StartFrame( mEchoes );
}
EchoesCallback();
mLastTimestamp = mEchoes->GetTimestamp();
}
}
else if( aSignal == LeddarCore::LdObject::VALUE_CHANGED && dynamic_cast<LeddarCore::LdProperty *>( aSender ) != nullptr )
{
if( mLastTimestamp != 0 )
{
EndFrame();
}
PropertyCallback( dynamic_cast<LeddarCore::LdProperty *>( aSender ) );
mLastTimestamp = 0; //To be sure we start a new frame without closing one
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::StartFrame( LeddarConnection::LdResultProvider *aResults )
///
/// \brief Starts a frame record
///
/// \param [in,out] aResults Result provider for the timestamp
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::StartFrame( LeddarConnection::LdResultProvider *aResults )
{
mWriter->StartObject(); //main object
mWriter->Key( "frame" );
mWriter->StartObject(); //frame
mWriter->Key( "ts" );
mWriter->Uint( aResults->GetTimestamp() );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::EndFrame()
///
/// \brief Ends a frame record and output it to the file
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::EndFrame()
{
mWriter->EndObject(); //frame
mWriter->EndObject(); //main object
*mOutStream << mStringBuffer->GetString() << std::endl;
mStringBuffer->Clear();
mWriter->Reset( *mStringBuffer );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::StatesCallback()
///
/// \brief Callback, called when there is new states
/// Append states to the record
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::StatesCallback()
{
mWriter->Key( "states" );
mWriter->StartArray(); //states
std::vector<LeddarCore::LdProperty *> lProperties = mStates->GetProperties()->FindPropertiesByFeature( LeddarCore::LdProperty::F_SAVE );
for( std::vector<LeddarCore::LdProperty *>::iterator lIter = lProperties.begin(); lIter != lProperties.end(); ++lIter )
{
if( ( *lIter )->Count() > 0 )
AddProperty( *lIter );
}
mWriter->EndArray(); //states
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::EchoesCallback()
///
/// \brief Callback, called when there is new echoes
/// Append echoes to the record
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::EchoesCallback()
{
mWriter->Key( "echoes" );
mWriter->StartArray(); //echoes
mEchoes->Lock( LeddarConnection::B_GET );
std::vector<LeddarConnection::LdEcho> &lEchoes = *( mEchoes->GetEchoes( LeddarConnection::B_GET ) );
double lAmpScale = static_cast<double>( mEchoes->GetAmplitudeScale() );
double lDistScale = static_cast<double>( mEchoes->GetDistanceScale() );
for( size_t i = 0; i < mEchoes->GetEchoCount( LeddarConnection::B_GET ); ++i )
{
mWriter->StartArray(); //echo
mWriter->Uint( lEchoes[i].mChannelIndex );
mWriter->Double( lEchoes[i].mDistance / lDistScale );
mWriter->Double( lEchoes[i].mAmplitude / lAmpScale );
mWriter->Uint( lEchoes[i].mFlag );
mWriter->EndArray(); //echo
}
mEchoes->UnLock( LeddarConnection::B_GET );
mWriter->EndArray(); //echoes
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// \fn void LeddarRecord::LdLjrRecorder::PropertyCallback()
///
/// \brief Callback, called when a property is changed
///
/// \author David Levy
/// \date October 2018
////////////////////////////////////////////////////////////////////////////////////////////////////
void LeddarRecord::LdLjrRecorder::PropertyCallback( LeddarCore::LdProperty *aProperty )
{
mWriter->StartObject(); //Main object
mWriter->Key( "prop" );
mWriter->StartArray(); //Prop array
AddProperty( aProperty );
mWriter->EndArray(); //Prop array
mWriter->EndObject(); //Main object
*mOutStream << mStringBuffer->GetString() << std::endl;
mStringBuffer->Clear();
mWriter->Reset( *mStringBuffer );
}
| 34.5677
| 161
| 0.512978
|
deucedrone
|
6157ba65a6fa0532e52c9f91104c726ab2c6430c
| 4,765
|
cpp
|
C++
|
src/Plugins/TTFPlugin/TTFDataflow.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
src/Plugins/TTFPlugin/TTFDataflow.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
src/Plugins/TTFPlugin/TTFDataflow.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
#include "TTFDataflow.h"
#include "TTFData.h"
#include "Kernel/ThreadMutexScope.h"
#include "Kernel/ResourceImage.h"
#include "Kernel/FactoryPool.h"
#include "Kernel/AssertionFactory.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/Stream.h"
#include "Kernel/MemoryStreamHelper.h"
#include "Kernel/Logger.h"
#include "Kernel/ConstStringHelper.h"
//////////////////////////////////////////////////////////////////////////
static const char * FT_error_message( FT_Error err )
{
#undef __FTERRORS_H__
#define FT_ERRORDEF( e, v, s ) case e: return s;
#define FT_ERROR_START_LIST switch (err) {
#define FT_ERROR_END_LIST }
#include FT_ERRORS_H
return "(Unknown error)";
}
//////////////////////////////////////////////////////////////////////////
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
TTFDataflow::TTFDataflow()
: m_library( nullptr )
{
}
//////////////////////////////////////////////////////////////////////////
TTFDataflow::~TTFDataflow()
{
}
//////////////////////////////////////////////////////////////////////////
void TTFDataflow::setFTLibrary( FT_Library _library )
{
m_library = _library;
}
//////////////////////////////////////////////////////////////////////////
FT_Library TTFDataflow::getFTLibrary() const
{
return m_library;
}
//////////////////////////////////////////////////////////////////////////
void TTFDataflow::setMutex( const ThreadMutexInterfacePtr & _mutex )
{
m_mutex = _mutex;
}
//////////////////////////////////////////////////////////////////////////
const ThreadMutexInterfacePtr & TTFDataflow::getMutex() const
{
return m_mutex;
}
//////////////////////////////////////////////////////////////////////////
bool TTFDataflow::initialize()
{
m_factoryTTFData = Helper::makeFactoryPool<TTFData, 128>( MENGINE_DOCUMENT_FACTORABLE );
return true;
}
//////////////////////////////////////////////////////////////////////////
void TTFDataflow::finalize()
{
m_mutex = nullptr;
MENGINE_ASSERTION_FACTORY_EMPTY( m_factoryTTFData );
m_factoryTTFData = nullptr;
}
//////////////////////////////////////////////////////////////////////////
bool TTFDataflow::isThreadFlow() const
{
return true;
}
//////////////////////////////////////////////////////////////////////////
DataInterfacePtr TTFDataflow::create( const DocumentPtr & _doc )
{
TTFDataPtr data = m_factoryTTFData->createObject( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( data );
return data;
}
//////////////////////////////////////////////////////////////////////////
MemoryInterfacePtr TTFDataflow::load( const InputStreamInterfacePtr & _stream, const DocumentPtr & _doc )
{
MemoryInterfacePtr memory = Helper::createMemoryStream( _stream, _doc );
MENGINE_ASSERTION_MEMORY_PANIC( memory );
return memory;
}
//////////////////////////////////////////////////////////////////////////
bool TTFDataflow::flow( const DataInterfacePtr & _data, const MemoryInterfacePtr & _memory, const DataflowContext * _context, const DocumentPtr & _doc )
{
MENGINE_UNUSED( _context );
MENGINE_UNUSED( _doc );
TTFData * data = stdex::intrusive_get<TTFData *>( _data );
data->setTTFMemory( _memory );
FT_Byte * memory_byte = _memory->getBuffer();
size_t memory_size = _memory->getSize();
MENGINE_ASSERTION_MEMORY_PANIC( memory_byte );
MENGINE_THREAD_MUTEX_SCOPE( m_mutex );
FT_Face face;
FT_Error err_code_memory_face = FT_New_Memory_Face( m_library, memory_byte, (FT_Long)memory_size, 0, &face );
if( err_code_memory_face != FT_Err_Ok )
{
LOGGER_ERROR( "FT_New_Memory_Face font error: %s [%d] (doc: %s)"
, FT_error_message( err_code_memory_face )
, err_code_memory_face
, MENGINE_DOCUMENT_STR( _doc )
);
return false;
}
FT_Error err_code_select_charmap = FT_Select_Charmap( face, FT_ENCODING_UNICODE );
if( err_code_select_charmap != FT_Err_Ok )
{
LOGGER_ERROR( "FT_Select_Charmap font error: %s [%d] (doc: %s)"
, FT_error_message( err_code_memory_face )
, err_code_memory_face
, MENGINE_DOCUMENT_STR( _doc )
);
return false;
}
data->setFTFace( face );
return true;
}
//////////////////////////////////////////////////////////////////////////
}
| 32.862069
| 156
| 0.480797
|
Terryhata6
|
61586465d501b30319347f775a0bab512ac85261
| 892
|
hh
|
C++
|
pelitehdas.hh
|
WhiteDeathFIN/Labyrinttipeli
|
f89b62d17f6b4bddd5a5df4729c157649b8f64b4
|
[
"Apache-2.0"
] | null | null | null |
pelitehdas.hh
|
WhiteDeathFIN/Labyrinttipeli
|
f89b62d17f6b4bddd5a5df4729c157649b8f64b4
|
[
"Apache-2.0"
] | null | null | null |
pelitehdas.hh
|
WhiteDeathFIN/Labyrinttipeli
|
f89b62d17f6b4bddd5a5df4729c157649b8f64b4
|
[
"Apache-2.0"
] | null | null | null |
#ifndef JULKINEN_PELITEHDAS_HH
#define JULKINEN_PELITEHDAS_HH
/**
* \version $Id: pelitehdas.hh 2660 2013-02-15 10:27:37Z bitti $
* \file pelitehdas.hh
* \brief Rajapinta pelin luomiseksi
* \author ©2010 Eero Salonen <eero.j.salonen@tut.fi>
*
**/
#include "pelirajapinta.hh"
#include <memory>
/// \namespace Julkinen
namespace
Julkinen
{
/**
* \brief Luo instanssi pelirajapinnasta.
*
* Pääohjelma kutsuu tätä funktiota saadakseen itselleen instanssin
* oliosta, joka toteuttaa pelirajapinnan.
* Funktion toteutus on tehtävä omaan koodiin.
*
* \post Luodun peli-instanssin tuhoamisvastuu siirtyi pääohjelmalle.
* Luotu olio on alustustilassa.
* \return Dynaamisesti luotu instanssi luokasta, joka toteuttaa
* Labyrintti-pelin.
*/
std::unique_ptr<Pelirajapinta> luoPeli();
}
#endif // JULKINEN_PELITEHDAS_HH
| 25.485714
| 74
| 0.701794
|
WhiteDeathFIN
|
61593bd24d093cacf2099e408e72ed9e7c4e43d1
| 27,628
|
cpp
|
C++
|
Libraries/Geometry/Mesh/Delaunay.cpp
|
pat-sweeney/Caustic
|
0bef667dd3fb77de4b8e8b02a341760ab869d1fe
|
[
"MIT"
] | 1
|
2021-05-19T14:58:46.000Z
|
2021-05-19T14:58:46.000Z
|
Libraries/Geometry/Mesh/Delaunay.cpp
|
pat-sweeney/Caustic
|
0bef667dd3fb77de4b8e8b02a341760ab869d1fe
|
[
"MIT"
] | 2
|
2019-09-28T17:29:47.000Z
|
2019-09-28T17:46:37.000Z
|
Libraries/Geometry/Mesh/Delaunay.cpp
|
pat-sweeney/Caustic
|
0bef667dd3fb77de4b8e8b02a341760ab869d1fe
|
[
"MIT"
] | null | null | null |
//**********************************************************************
// Copyright Patrick Sweeney 2015-2021
// Licensed under the MIT license.
// See file LICENSE for details.
//**********************************************************************
import Base.Core.Core;
import Base.Core.Error;
import Base.Math.BBox;
import Base.Math.Helper;
import Imaging.Image.IImage;
import Geometry.Mesh.Delaunay;
import Geometry.Mesh.Mesh;
#include <map>
#include <stack>
#include <Windows.h>
namespace Caustic
{
CDelaunay2::CDelaunay2(BBox2 &bb)
{
// First add the super triangle
Vector2 v0(bb.minPt.x, bb.minPt.y);
Vector2 v1(bb.maxPt.x, bb.minPt.y);
Vector2 v2(bb.minPt.x, bb.maxPt.y);
Vector2 v3(bb.maxPt.x, bb.maxPt.y);
Vector2 uv(0.0f, 0.0f);
m_points.push_back(Vertex(v0, uv, c_SuperTriangleVertex));
m_points.push_back(Vertex(v1, uv, c_SuperTriangleVertex));
m_points.push_back(Vertex(v2, uv, c_SuperTriangleVertex));
m_points.push_back(Vertex(v3, uv, c_SuperTriangleVertex));
int e0 = FindOrAddEdge(0, 2, 0, false);
int e1 = FindOrAddEdge(2, 1, 0, false);
int e2 = FindOrAddEdge(1, 0, 0, false);
int e3 = FindOrAddEdge(1, 2, 1, false);
int e4 = FindOrAddEdge(2, 3, 1, false);
int e5 = FindOrAddEdge(3, 1, 1, false);
m_triangles.push_back(Triangle(0, 1, 2, e0, e1, e2, c_ExteriorTriangle));
m_triangles.push_back(Triangle(1, 3, 2, e3, e4, e5, c_ExteriorTriangle));
m_numTriangles = 2;
}
#if 0
const int c_ShowEdges_BigPoint = 0;
const int c_ShowRemovedTriangles = 1;
const int c_ShowEdges_SmallPoint = 2;
const int c_ShowExteriorTriangles = 3;
const int c_ShowOutline = 4;
const int c_ShowPointInTriangle = 5;
static int frame = 0;
void CDelaunay2::DrawTriangulation(int type, int currentTri, int currentPoint)
{
CRefObj<IImage> spImage;
CreateImage(1024, 1024, &spImage);
uint8 blue[4] = { 0, 0, 255, 255 };
uint8 red[4] = { 255, 0, 0, 255 };
uint8 orange[4] = { 255, 127, 39, 255 };
// Draw current triangle in green and boundary edge in yellow
uint8 green[4] = { 0, 255, 0, 255 };
uint8 yellow[4] = { 255, 255, 0, 255 };
uint8 cyan[4] = { 0, 255, 255, 255 };
uint8 grey[4] = { 0, 0, 0, 255 };
for (int i = 0; i < (int)m_triangles.size(); i++)
{
if (type == c_ShowExteriorTriangles)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (m_triangles[i].flags & c_ExteriorTriangle)
continue;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e0].v0].pos,
m_points[m_edges[m_triangles[i].e0].v1].pos,
(m_edges[m_triangles[i].e0].t0 == -1 || m_edges[m_triangles[i].e0].t1 == -1) ? green : red);
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e1].v0].pos,
m_points[m_edges[m_triangles[i].e1].v1].pos,
(m_edges[m_triangles[i].e1].t0 == -1 || m_edges[m_triangles[i].e1].t1 == -1) ? green : red);
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e2].v0].pos,
m_points[m_edges[m_triangles[i].e2].v1].pos,
(m_edges[m_triangles[i].e2].t0 == -1 || m_edges[m_triangles[i].e2].t1 == -1) ? green : red);
if (currentPoint >= 0)
spImage->SetPixel((int)m_points[currentPoint].pos.x, (int)m_points[currentPoint].pos.y, yellow);
}
else if (type == c_ShowOutline)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (m_triangles[i].flags & c_RemovedTriangle)
continue;
uint8 *color;
if (m_edges[m_triangles[i].e0].flags & c_OutlineEdge)
color = yellow;
else if (m_edges[m_triangles[i].e0].t0 == -1 || m_edges[m_triangles[i].e0].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e0].v0].pos,
m_points[m_edges[m_triangles[i].e0].v1].pos,
color);
if (m_edges[m_triangles[i].e1].flags & c_OutlineEdge)
color = yellow;
else if (m_edges[m_triangles[i].e1].t0 == -1 || m_edges[m_triangles[i].e1].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e1].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e1].v0].pos,
m_points[m_edges[m_triangles[i].e1].v1].pos,
color);
if (m_edges[m_triangles[i].e2].flags & c_OutlineEdge)
color = yellow;
else if (m_edges[m_triangles[i].e2].t0 == -1 || m_edges[m_triangles[i].e2].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e2].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e2].v0].pos,
m_points[m_edges[m_triangles[i].e2].v1].pos,
color);
spImage->SetPixel((int)m_points[currentPoint].pos.x, (int)m_points[currentPoint].pos.y, yellow);
}
else if (type == c_ShowRemovedTriangles)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
uint8 *color;
if (m_triangles[i].flags & c_RemovedTriangle)
color = grey;
else if (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e0].v0].pos,
m_points[m_edges[m_triangles[i].e0].v1].pos,
color);
if (m_triangles[i].flags & c_RemovedTriangle)
color = grey;
else if (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e1].v0].pos,
m_points[m_edges[m_triangles[i].e1].v1].pos,
color);
if (m_triangles[i].flags & c_RemovedTriangle)
color = grey;
else if (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e2].v0].pos,
m_points[m_edges[m_triangles[i].e2].v1].pos,
color);
spImage->SetPixel((int)m_points[currentPoint].pos.x, (int)m_points[currentPoint].pos.y, yellow);
for (int j = -3; j < 3; j++)
for (int k = -3; k < 3; k++)
spImage->SetPixel((int)m_points[currentPoint].pos.x + j, (int)m_points[currentPoint].pos.y + k, yellow);
m_triangles[i].flags &= ~c_RemovedTriangle;
}
else if (type == c_ShowPointInTriangle)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (m_triangles[i].flags & c_RemovedTriangle)
continue;
if (i == currentTri)
continue;
uint8 *color;
if (m_edges[m_triangles[i].e0].t0 == -1 || m_edges[m_triangles[i].e0].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e0].v0].pos,
m_points[m_edges[m_triangles[i].e0].v1].pos,
color);
if (m_edges[m_triangles[i].e1].t0 == -1 || m_edges[m_triangles[i].e1].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e1].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e1].v0].pos,
m_points[m_edges[m_triangles[i].e1].v1].pos,
color);
if (m_edges[m_triangles[i].e2].t0 == -1 || m_edges[m_triangles[i].e2].t1 == -1)
color = green;
else if (m_edges[m_triangles[i].e2].flags & c_BoundaryEdge)
color = blue;
else
color = red;
spImage->DrawLine(
m_points[m_edges[m_triangles[i].e2].v0].pos,
m_points[m_edges[m_triangles[i].e2].v1].pos,
color);
}
}
if (type == c_ShowPointInTriangle && currentTri >= 0)
{
spImage->DrawLine(
m_points[m_edges[m_triangles[currentTri].e0].v0].pos,
m_points[m_edges[m_triangles[currentTri].e0].v1].pos,
orange);
spImage->DrawLine(
m_points[m_edges[m_triangles[currentTri].e1].v0].pos,
m_points[m_edges[m_triangles[currentTri].e1].v1].pos,
orange);
spImage->DrawLine(
m_points[m_edges[m_triangles[currentTri].e2].v0].pos,
m_points[m_edges[m_triangles[currentTri].e2].v1].pos,
orange);
Caustic::Vector2 center;
float radius;
CircumCircle(m_points[m_triangles[currentTri].v0].pos, m_points[m_triangles[currentTri].v1].pos, m_points[m_triangles[currentTri].v2].pos,
¢er, &radius);
spImage->DrawCircle(center, (uint32)radius, grey);
for (int j = -3; j < 3; j++)
for (int k = -3; k < 3; k++)
spImage->SetPixel((int)m_points[currentPoint].pos.x + j, (int)m_points[currentPoint].pos.y + k, yellow);
}
wchar_t fn[1024];
swprintf_s(fn, L"d:\\images\\frame-%d.png", frame++);
StoreImage(fn, spImage);
}
#endif
//**********************************************************************
// Method: FindOrAddEdge
// Adds a new edge to our mesh
//
// Adds a new edge to our mesh. Each edge is directed from v0=>v1.
// Each face is oriented so that edges go in counter-clockwise order.
//
// v0
// +-------------+
// | /
// t1|t0 /
// | /
// | /
// +
// v1
//**********************************************************************
int CDelaunay2::FindOrAddEdge(int v0, int v1, int tri, bool isBoundaryEdge)
{
int ei0;
std::map<std::tuple<int, int>, int>::iterator it = m_edgeMap.find(std::make_tuple(v0, v1));
if (it != m_edgeMap.end())
{
ei0 = it->second;
if (m_edges[ei0].v0 == v0)
m_edges[ei0].t0 = tri;
else
m_edges[ei0].t1 = tri;
}
else
{
m_edges.push_back(Edge(v0, v1, tri, -1));
ei0 = (int)m_edges.size() - 1;
m_edgeMap.insert(std::make_pair(std::make_tuple(v0, v1), ei0));
m_edgeMap.insert(std::make_pair(std::make_tuple(v1, v0), ei0));
}
if (isBoundaryEdge)
m_edges[ei0].flags |= c_BoundaryEdge;
return ei0;
}
//**********************************************************************
// Method: AddPoint
// Adds a new point to our current Delaunay triangulation using
// the Bowyer-Watson algorithm.
//**********************************************************************
void CDelaunay2::AddPoint(Vector2 &pt, Vector2 &uv, bool isBoundary)
{
m_points.push_back(Vertex(pt, uv, (isBoundary) ? c_BoundaryVertex : c_InteriorVertex));
}
//**********************************************************************
// Method: CreateBoundaryEdges
// Pre-allocates all the edges that form our meshes boundary.
// We assume that boundary edges are added in counter-clockwise order
// around the mesh.
//**********************************************************************
void CDelaunay2::CreateBoundaryEdges()
{
int firstBoundaryVertex = -1;
int lastBoundaryVertex = -1;
for (int i = 0; i < (int)m_points.size(); i++)
{
if (m_points[i].flags & c_BoundaryVertex)
{
if (lastBoundaryVertex != -1)
FindOrAddEdge(lastBoundaryVertex, i, -1, true);
else
firstBoundaryVertex = i;
lastBoundaryVertex = i;
}
}
if (firstBoundaryVertex != -1 && lastBoundaryVertex != -1 && firstBoundaryVertex != lastBoundaryVertex)
FindOrAddEdge(lastBoundaryVertex, firstBoundaryVertex, -1, true);
}
//**********************************************************************
// Method: ComputeTriangulation
// Computes the Delaunay triangulation of our mesh. We first compute
// a triangulation based on the boundary vertices. We then remove the exterior
// triangles (super triangles) and then add the interior vertices.
//**********************************************************************
void CDelaunay2::ComputeTriangulation()
{
CreateBoundaryEdges();
TriangulatePoints(c_InteriorVertex);
TriangulatePoints(c_BoundaryVertex);
RemoveExteriorTriangles();
}
//**********************************************************************
// Method: TriangulePoints
// Adds the set of vertex points that match the specified vertex
// flag to the current triangulation.
//**********************************************************************
void CDelaunay2::TriangulatePoints(uint8 flag)
{
//**********************************************************************
// Next add each of our points to the triangulation
//**********************************************************************
for (int ptIndex = 0; ptIndex < (int)m_points.size(); ptIndex++)
{
if (!(m_points[ptIndex].flags & flag))
continue;
//**********************************************************************
// First determine which triangles now fail the Delaunay property
// when the new point is added
//**********************************************************************
std::vector<int> badTriangles;
for (int i = 0; i < m_triangles.size(); i++)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (PointInTriangleCircumcircle(m_points[m_triangles[i].v0].pos, m_points[m_triangles[i].v1].pos, m_points[m_triangles[i].v2].pos, m_points[ptIndex].pos))
{
// Next make sure that all three vertices of the triangle are not boundary vertices.
// This can happen when two of the triangle edges are inside the boundary and one edge
// is on the boundary. Alternatively, it can happen if two edges are boundary edges and
// the third edge is a non-boundary edge. For instance, if edge e0 is a boundary edge,
// and e1 & e2 are interior (non-boundary) edges, but vertex v2 is on the boundary, we can
// end up classifying the triangle as bad, and incorrectly remove it.
//
// v0 e0 v1
// ---X-------X-----
// \ /
// e1 \ / e2
// \ /
// --------X----------
// v2
int numBoundaryEdges = 0;
numBoundaryEdges += (m_edges[m_triangles[i].e0].flags & c_BoundaryEdge) ? 1 : 0;
numBoundaryEdges += (m_edges[m_triangles[i].e1].flags & c_BoundaryEdge) ? 1 : 0;
numBoundaryEdges += (m_edges[m_triangles[i].e2].flags & c_BoundaryEdge) ? 1 : 0;
if (numBoundaryEdges < 3)
{
badTriangles.push_back(i);
m_triangles[i].flags |= c_RemovedTriangle;
}
}
}
//**********************************************************************
// Next determine which edges make up the polygon defining the hole
// caused by removing the bad triangles
//**********************************************************************
std::vector<int> edgeUseCount;
edgeUseCount.resize(m_edges.size(), 0);
for (int i = 0; i < (int)badTriangles.size(); i++)
{
int triIndex = badTriangles[i];
Triangle &t = m_triangles[triIndex];
edgeUseCount[t.e0]++;
edgeUseCount[t.e1]++;
edgeUseCount[t.e2]++;
t.flags |= c_TriangleBad;
if (m_edges[t.e0].t0 == triIndex)
m_edges[t.e0].t0 = -1;
else
{
_ASSERT(m_edges[t.e0].t1 == -1 || m_edges[t.e0].t1 == triIndex);
m_edges[t.e0].t1 = -1;
}
if (m_edges[t.e1].t0 == triIndex)
m_edges[t.e1].t0 = -1;
else
{
_ASSERT(m_edges[t.e1].t1 == -1 || m_edges[t.e1].t1 == triIndex);
m_edges[t.e1].t1 = -1;
}
if (m_edges[t.e2].t0 == triIndex)
m_edges[t.e2].t0 = -1;
else
{
_ASSERT(m_edges[t.e2].t1 == -1 || m_edges[t.e2].t1 == triIndex);
m_edges[t.e2].t1 = -1;
}
m_numTriangles--;
}
//for (int i = 0; i < (int)edgeUseCount.size(); i++)
//{
// if (edgeUseCount[i] == 1)
// m_edges[i].flags |= c_OutlineEdge;
// else
// m_edges[i].flags &= ~c_OutlineEdge;
//}
//**********************************************************************
// Now find all the edges whose count == 1, that is they are used by only
// 1 "bad" triangle. These edges define the boundary of our hole (created
// by removing the bad triangles)
//**********************************************************************
for (int i = 0; i < (int)edgeUseCount.size(); i++)
{
if (edgeUseCount[i] == 1)
{
// First determine if we are to left or right of edge m_edges[i].v0=>m_edges[i].v1
// We need to make sure that all our triangles are created in counter clockwise manner.
Vector2 edge0 = m_points[m_edges[i].v1].pos - m_points[m_edges[i].v0].pos;
Vector2 edge1 = m_points[ptIndex].pos - m_points[m_edges[i].v0].pos;
float dir = edge0.Cross(edge1);
int v0, v1;
if (IsLess(dir, 0.0f))
{
// Point to left of edge
v0 = m_edges[i].v0;
v1 = m_edges[i].v1;
}
else
{
// Point to right of edge
v1 = m_edges[i].v0;
v0 = m_edges[i].v1;
}
// Create a new triangle between each edge and new point
int triIndex = (int)m_triangles.size();
int ei0 = FindOrAddEdge(ptIndex, v0, triIndex, false);
int ei1 = FindOrAddEdge(v1, ptIndex, triIndex, false);
if (IsLess(dir, 0.0f))
m_edges[i].t0 = triIndex;
else
m_edges[i].t1 = triIndex;
m_triangles.push_back(Triangle(v0, v1, ptIndex, i, ei1, ei0, 0));
m_numTriangles++;
}
}
}
}
//**********************************************************************
// Method: RemoveExteriorTriangles
// Removes the exterior triangles (ones connected to the super triangle vertices)
//**********************************************************************
void CDelaunay2::RemoveExteriorTriangles()
{
std::stack<int> exteriorTriangles;
// Place each triangle that is part of the super triangles into our
// exterior triangle stack.
for (int i = 0; i < (int)m_triangles.size(); i++)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (m_triangles[i].v0 <= 3 || m_triangles[i].v1 <= 3 || m_triangles[i].v2 <= 3) // Part of super triangle
{
m_triangles[i].flags |= c_ExteriorTriangle | c_TriangleBad;
exteriorTriangles.push(i);
}
}
// While there are exterior triangles, walk their edges and add any additional
// exterior triangles to the stack
while (!exteriorTriangles.empty())
{
int tri = exteriorTriangles.top();
exteriorTriangles.pop();
// Check each of our edges.
auto CheckEdge = [&](int edge)
{
if (!(m_edges[edge].flags & c_BoundaryEdge))
{
int nextTri = (m_edges[edge].t0 != tri) ? m_edges[edge].t0 : m_edges[edge].t1;
if (nextTri != -1)
{
#ifdef DEBUGGING_AIDS
{
wchar_t buf[1024];
swprintf_s(buf, L"Stepping across edge: %d into Triangle: %d\n", edge, nextTri);
OutputDebugString(buf);
}
#endif
if (!(m_triangles[nextTri].flags & c_ExteriorTriangle) &&
!(m_points[m_triangles[nextTri].v0].flags & c_BoundaryVertex) &&
!(m_points[m_triangles[nextTri].v1].flags & c_BoundaryVertex) &&
!(m_points[m_triangles[nextTri].v2].flags & c_BoundaryVertex))
{
m_triangles[nextTri].flags |= c_ExteriorTriangle | c_TriangleBad;
exteriorTriangles.push(nextTri);
}
}
}
};
CheckEdge(m_triangles[tri].e0);
CheckEdge(m_triangles[tri].e1);
CheckEdge(m_triangles[tri].e2);
}
}
//**********************************************************************
// Method: Close
// Performs the triangulation step after the points have all been added
// to the mesh.
//**********************************************************************
void CDelaunay2::Close()
{
ComputeTriangulation();
int j = 0;
for (int i = 0; i < (int)m_triangles.size(); i++)
{
if (m_triangles[i].flags & c_TriangleBad)
continue;
if (m_triangles[i].flags & c_ExteriorTriangle)
continue;
if (m_triangles[i].v0 <= 3 || m_triangles[i].v1 <= 3 || m_triangles[i].v2 <= 3) // Part of super triangle
continue;
if (i != j)
m_triangles[j++] = m_triangles[i];
}
m_triangles.resize(j);
m_numTriangles = (uint32)m_triangles.size();
}
//**********************************************************************
// Method: WriteString
// Writes a string to the specified stream using vsprintf_s()
//**********************************************************************
static void WriteString(HANDLE h, const char *pData, ...)
{
va_list args;
va_start(args, pData);
char buffer[1024];
vsprintf_s(buffer, pData, args);
va_end(args);
DWORD bytesWritten;
WriteFile(h, buffer, (DWORD)strlen(buffer), &bytesWritten, nullptr);
}
// This is a complete hack. I just needed a temporary way to export this as a mesh
void CDelaunay2::WritePLY()
{
const wchar_t *pFilename = L"c:\\users\\patri\\output.ply";
HANDLE h = CreateFile(pFilename, FILE_GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr);
if (h == INVALID_HANDLE_VALUE)
CT(HRESULT_FROM_WIN32(GetLastError()));
WriteString(h, "ply\n");
WriteString(h, "format ascii 1.0\n");
WriteString(h, "element vertex %d\n", 3 * m_numTriangles);
WriteString(h, "property float x\n");
WriteString(h, "property float y\n");
WriteString(h, "property float z\n");
WriteString(h, "property float tx\n");
WriteString(h, "property float ty\n");
WriteString(h, "element face %d\n", m_numTriangles);
WriteString(h, "property list uchar int vertex_indices\n");
WriteString(h, "end_header\n");
for (int i = 0; i < (int)m_numTriangles; i++)
{
WriteString(h, "%f %f %f %f %f\n", m_points[m_triangles[i].v0].pos.x, m_points[m_triangles[i].v0].pos.y, 0.0f,
m_points[m_triangles[i].v0].uv.x, m_points[m_triangles[i].v0].uv.y);
WriteString(h, "%f %f %f %f %f\n", m_points[m_triangles[i].v1].pos.x, m_points[m_triangles[i].v1].pos.y, 0.0f,
m_points[m_triangles[i].v1].uv.x, m_points[m_triangles[i].v1].uv.y);
WriteString(h, "%f %f %f %f %f\n", m_points[m_triangles[i].v2].pos.x, m_points[m_triangles[i].v2].pos.y, 0.0f,
m_points[m_triangles[i].v2].uv.x, m_points[m_triangles[i].v2].uv.y);
}
for (int i = 0; i < (int)m_numTriangles; i++)
{
WriteString(h, "3 %d %d %d\n", i * 3 + 0, i * 3 + 1, i * 3 + 2);
}
CloseHandle(h);
}
//**********************************************************************
// Method: CreateDelaunay2
// Creates a Delaunay triangulation
//**********************************************************************
CRefObj<IDelaunay2> CreateDelaunay2(BBox2 &bb)
{
return CRefObj<IDelaunay2>(new CDelaunay2(bb));
}
}
| 44.56129
| 170
| 0.46319
|
pat-sweeney
|
6160bc578ead9cf7a0ac959326382c797adf40ae
| 1,773
|
hpp
|
C++
|
esl/economics/markets/indication.hpp
|
rht/ESL
|
f883155a167d3c48e5ecdca91c8302fefc901c22
|
[
"Apache-2.0"
] | 37
|
2019-10-13T12:23:32.000Z
|
2022-03-19T10:40:29.000Z
|
esl/economics/markets/indication.hpp
|
rht/ESL
|
f883155a167d3c48e5ecdca91c8302fefc901c22
|
[
"Apache-2.0"
] | 3
|
2020-03-20T04:44:06.000Z
|
2021-01-12T06:18:33.000Z
|
esl/economics/markets/indication.hpp
|
vishalbelsare/ESL
|
cea6feda1e588d5f441742dbb1e4c5479b47d357
|
[
"Apache-2.0"
] | 10
|
2019-11-06T15:59:06.000Z
|
2021-08-09T17:28:24.000Z
|
/// \file indication.hpp
///
/// \brief
///
/// \authors Maarten P. Scholl
/// \date 2019-10-08
/// \copyright Copyright 2017-2019 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// 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.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#ifndef ESL_INDICATION_HPP
#define ESL_INDICATION_HPP
#include <cstdint>
namespace esl::economics::markets {
///
/// \brief Denotes whether or not a quote that is sent is binding for
/// the sender, meaning that the sender must deliver at the quote
/// if the recipient accepts the offer.
///
enum indication
: std::uint8_t
{
firm,
indicative
};
} // namespace esl::economics::markets
#ifdef WITH_MPI
#include <boost/mpi/datatype.hpp>
namespace boost::mpi {
template<>
struct is_mpi_datatype<esl::economics::markets::indication>
: public mpl::true_
{
};
} // namespace boost::mpi
#endif // WITH_MPI
#endif // ESL_INDICATION_HPP
| 30.050847
| 80
| 0.624365
|
rht
|
61632c447a9b8aad61cf7be3847351b0be3619de
| 1,241
|
cc
|
C++
|
lib/trie-factory.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/trie-factory.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/trie-factory.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
#include <taiju/trie-factory.h>
#include <taiju/pods-trie.h>
#include <taiju/lob-trie.h>
#include <taiju/louds-trie.h>
#include <taiju/plouds-trie.h>
#include <taiju/bp-trie.h>
#include <taiju/dfuds-trie.h>
#include <memory>
namespace taiju {
TrieBase *TrieFactory::Create(TrieType type)
{
try
{
switch (type)
{
case PODS_TRIE:
return new PodsTrie;
case LOB_TRIE:
return new LobTrie;
case LOUDS_TRIE:
return new LoudsTrie;
case PLOUDS_TRIE:
return new PloudsTrie;
case BP_TRIE:
return new BpTrie;
case DFUDS_TRIE:
return new DfudsTrie;
default:
TAIJU_THROW("failed to create trie: invalid TrieType");
}
}
catch (const std::bad_alloc &)
{
TAIJU_THROW("failed to create trie: std::bad_alloc");
}
}
TrieBase *TrieFactory::map(Mapper mapper, const void **address_ptr)
{
TrieType type = *mapper.map<TrieType>();
std::auto_ptr<TrieBase> trie(Create(type));
const void *address = trie->map(mapper, false);
if (address_ptr != NULL)
*address_ptr = address;
return trie.release();
}
TrieBase *TrieFactory::read(Reader reader)
{
TrieType type;
reader.read(&type);
std::auto_ptr<TrieBase> trie(Create(type));
trie->read(reader, false);
return trie.release();
}
} // namespace taiju
| 19.390625
| 67
| 0.701048
|
rockeet
|
6163497f16940e99d513e99f10ac07289f18675a
| 1,583
|
hpp
|
C++
|
include/System/Threading/PlatformHelper.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Threading/PlatformHelper.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Threading/PlatformHelper.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Type namespace: System.Threading
namespace System::Threading {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: System.Threading.PlatformHelper
class PlatformHelper : public ::Il2CppObject {
public:
// Creating value type constructor for type: PlatformHelper
PlatformHelper() noexcept {}
// Get static field: static private System.Int32 s_processorCount
static int _get_s_processorCount();
// Set static field: static private System.Int32 s_processorCount
static void _set_s_processorCount(int value);
// Get static field: static private System.Int32 s_lastProcessorCountRefreshTicks
static int _get_s_lastProcessorCountRefreshTicks();
// Set static field: static private System.Int32 s_lastProcessorCountRefreshTicks
static void _set_s_lastProcessorCountRefreshTicks(int value);
// static System.Int32 get_ProcessorCount()
// Offset: 0x1892C90
static int get_ProcessorCount();
// static System.Boolean get_IsSingleProcessor()
// Offset: 0x18952E0
static bool get_IsSingleProcessor();
}; // System.Threading.PlatformHelper
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::Threading::PlatformHelper*, "System.Threading", "PlatformHelper");
| 43.972222
| 98
| 0.711308
|
darknight1050
|
61641d490d72922c8bd819b02160b7e6a5584d35
| 63,624
|
cxx
|
C++
|
Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx
|
bartholmberg/VTK
|
e047cec7cffdcd8b134809c6fe97f7c7f7360603
|
[
"BSD-3-Clause"
] | null | null | null |
Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx
|
bartholmberg/VTK
|
e047cec7cffdcd8b134809c6fe97f7c7f7360603
|
[
"BSD-3-Clause"
] | null | null | null |
Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx
|
bartholmberg/VTK
|
e047cec7cffdcd8b134809c6fe97f7c7f7360603
|
[
"BSD-3-Clause"
] | null | null | null |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLRenderWindow.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLRenderWindow.h"
#include "vtk_glew.h"
#include "vtkOpenGLHelper.h"
#include <cassert>
#include "vtkFloatArray.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLActor.h"
#include "vtkOpenGLBufferObject.h"
#include "vtkOpenGLCamera.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLFramebufferObject.h"
#include "vtkOpenGLLight.h"
#include "vtkOpenGLProperty.h"
#include "vtkOpenGLQuadHelper.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLResourceFreeCallback.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLState.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkOpenGLVertexBufferObjectCache.h"
#include "vtkOutputWindow.h"
#include "vtkPerlinNoise.h"
#include "vtkRenderTimerLog.h"
#include "vtkRendererCollection.h"
#include "vtkShaderProgram.h"
#include "vtkStdString.h"
#include "vtkStringOutputWindow.h"
#include "vtkTextureObject.h"
#include "vtkTextureUnitManager.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedCharArray.h"
#include "vtkTextureObjectVS.h" // a pass through shader
#include <sstream>
using std::ostringstream;
#include <cassert>
// Initialize static member that controls global maximum number of multisamples
// (off by default on Apple because it causes problems on some Mac models).
#if defined(__APPLE__)
static int vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples = 0;
#else
static int vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples = 8;
#endif
const char* defaultWindowName = "Visualization Toolkit - OpenGL";
const char* ResolveShader =
R"***(
//VTK::System::Dec
in vec2 texCoord;
uniform sampler2DMS tex;
uniform int samplecount;
//VTK::Output::Dec
void main()
{
float gamma = 2.2;
// for each sample in the multi sample buffer...
ivec2 itexcoords = ivec2(floor(textureSize(tex) * texCoord));
vec3 accumulate;
float alpha = 0.0;
for (int i = 0; i < samplecount; i++)
{
vec4 sample = texelFetch(tex, itexcoords, i);
// apply gamma correction and sum
accumulate += pow(sample.rgb, vec3(gamma));
alpha += sample.a;
}
// divide and reverse gamma correction
accumulate /= float(samplecount);
gl_FragData[0] = vec4(pow(accumulate, vec3(1.0/gamma)), alpha/float(samplecount));
}
)***";
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::SetGlobalMaximumNumberOfMultiSamples(int val)
{
if (val == vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples)
{
return;
}
vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples = val;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetGlobalMaximumNumberOfMultiSamples()
{
return vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples;
}
//------------------------------------------------------------------------------
const char* vtkOpenGLRenderWindow::GetRenderingBackend()
{
return "OpenGL2";
}
//------------------------------------------------------------------------------
vtkOpenGLRenderWindow::vtkOpenGLRenderWindow()
{
this->State = vtkOpenGLState::New();
this->FrameBlitMode = BlitToHardware;
this->ResolveQuad = nullptr;
this->Initialized = false;
this->GlewInitValid = false;
this->MultiSamples = vtkOpenGLRenderWindowGlobalMaximumNumberOfMultiSamples;
delete[] this->WindowName;
this->WindowName = new char[strlen(defaultWindowName) + 1];
strcpy(this->WindowName, defaultWindowName);
this->RenderFramebuffer = vtkOpenGLFramebufferObject::New();
this->RenderFramebuffer->SetContext(this);
this->DisplayFramebuffer = vtkOpenGLFramebufferObject::New();
this->DisplayFramebuffer->SetContext(this);
this->ResolveFramebuffer = vtkOpenGLFramebufferObject::New();
this->ResolveFramebuffer->SetContext(this);
this->DrawPixelsTextureObject = nullptr;
this->OwnContext = 1;
this->MaximumHardwareLineWidth = 1.0;
this->OpenGLSupportTested = false;
this->OpenGLSupportResult = 0;
this->OpenGLSupportMessage = "Not tested yet";
// this->NumberOfFrameBuffers = 0;
// this->DepthRenderBufferObject = 0;
this->AlphaBitPlanes = 8;
this->Capabilities = nullptr;
this->TQuad2DVBO = nullptr;
this->NoiseTextureObject = nullptr;
this->FirstRenderTime = -1;
this->LastMultiSamples = -1;
this->ScreenSize[0] = 0;
this->ScreenSize[1] = 0;
}
// free up memory & close the window
//------------------------------------------------------------------------------
vtkOpenGLRenderWindow::~vtkOpenGLRenderWindow()
{
if (this->RenderFramebuffer)
{
this->RenderFramebuffer->Delete();
this->RenderFramebuffer = nullptr;
}
if (this->DisplayFramebuffer)
{
this->DisplayFramebuffer->Delete();
this->DisplayFramebuffer = nullptr;
}
if (this->ResolveFramebuffer)
{
this->ResolveFramebuffer->Delete();
this->ResolveFramebuffer = nullptr;
}
if (this->DrawPixelsTextureObject != nullptr)
{
this->DrawPixelsTextureObject->UnRegister(this);
this->DrawPixelsTextureObject = nullptr;
}
this->GLStateIntegers.clear();
if (this->TQuad2DVBO)
{
this->TQuad2DVBO->Delete();
this->TQuad2DVBO = nullptr;
}
if (this->NoiseTextureObject)
{
this->NoiseTextureObject->Delete();
}
delete[] this->Capabilities;
this->Capabilities = nullptr;
this->State->Delete();
}
//------------------------------------------------------------------------------
const char* vtkOpenGLRenderWindow::ReportCapabilities()
{
this->MakeCurrent();
const char* glVendor = (const char*)glGetString(GL_VENDOR);
const char* glRenderer = (const char*)glGetString(GL_RENDERER);
const char* glVersion = (const char*)glGetString(GL_VERSION);
std::ostringstream strm;
if (glVendor)
{
strm << "OpenGL vendor string: " << glVendor << endl;
}
if (glRenderer)
{
strm << "OpenGL renderer string: " << glRenderer << endl;
}
if (glVersion)
{
strm << "OpenGL version string: " << glVersion << endl;
}
strm << "OpenGL extensions: " << endl;
GLint n, i;
glGetIntegerv(GL_NUM_EXTENSIONS, &n);
for (i = 0; i < n; i++)
{
const char* ext = (const char*)glGetStringi(GL_EXTENSIONS, i);
strm << " " << ext << endl;
}
delete[] this->Capabilities;
size_t len = strm.str().length() + 1;
this->Capabilities = new char[len];
strncpy(this->Capabilities, strm.str().c_str(), len);
return this->Capabilities;
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::ReleaseGraphicsResources(vtkWindow* renWin)
{
this->PushContext();
if (this->ResolveQuad)
{
delete this->ResolveQuad;
this->ResolveQuad = nullptr;
}
this->RenderFramebuffer->ReleaseGraphicsResources(renWin);
this->DisplayFramebuffer->ReleaseGraphicsResources(renWin);
this->ResolveFramebuffer->ReleaseGraphicsResources(renWin);
// release the registered resources
if (this->NoiseTextureObject)
{
this->NoiseTextureObject->ReleaseGraphicsResources(this);
}
std::set<vtkGenericOpenGLResourceFreeCallback*>::iterator it = this->Resources.begin();
while (it != this->Resources.end())
{
(*it)->Release();
it = this->Resources.begin();
}
vtkCollectionSimpleIterator rsit;
this->Renderers->InitTraversal(rsit);
vtkRenderer* aren;
while ((aren = this->Renderers->GetNextRenderer(rsit)))
{
if (aren->GetRenderWindow() == this)
{
aren->ReleaseGraphicsResources(renWin);
}
}
if (this->DrawPixelsTextureObject != nullptr)
{
this->DrawPixelsTextureObject->ReleaseGraphicsResources(renWin);
}
this->GetShaderCache()->ReleaseGraphicsResources(renWin);
// this->VBOCache->ReleaseGraphicsResources(renWin);
this->GetState()->VerifyNoActiveTextures();
this->RenderTimer->ReleaseGraphicsResources();
if (this->TQuad2DVBO)
{
this->TQuad2DVBO->ReleaseGraphicsResources();
}
this->PopContext();
this->State->Delete();
this->State = vtkOpenGLState::New();
this->Initialized = false;
}
//------------------------------------------------------------------------------
vtkMTimeType vtkOpenGLRenderWindow::GetContextCreationTime()
{
return this->ContextCreationTime.GetMTime();
}
//------------------------------------------------------------------------------
vtkOpenGLShaderCache* vtkOpenGLRenderWindow::GetShaderCache()
{
return this->GetState()->GetShaderCache();
}
//------------------------------------------------------------------------------
vtkOpenGLVertexBufferObjectCache* vtkOpenGLRenderWindow::GetVBOCache()
{
return this->GetState()->GetVBOCache();
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetBackLeftBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetBackRightBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetFrontLeftBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetFrontRightBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetBackBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
unsigned int vtkOpenGLRenderWindow::GetFrontBuffer()
{
return 0;
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::SetSize(int width, int height)
{
if (this->Size[0] == width && this->Size[1] == height)
{
// Nothing should've happened in the superclass but one never knows...
this->Superclass::SetSize(width, height);
return;
}
this->Superclass::SetSize(width, height);
if (this->UseOffScreenBuffers && this->RenderFramebuffer)
{
// resize the framebuffers
this->RenderFramebuffer->Resize(width, height);
this->DisplayFramebuffer->Resize(width, height);
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::OpenGLInit()
{
this->OpenGLInitContext();
if (this->Initialized)
{
this->OpenGLInitState();
// This is required for some reason when using vtkSynchronizedRenderers.
// Without it, the initial render of an offscreen context will always be
// empty:
glFlush();
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::OpenGLInitState()
{
this->GetState()->Initialize(this);
#ifdef GL_FRAMEBUFFER_SRGB
if (this->UseSRGBColorSpace && this->GetUsingSRGBColorSpace())
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
#endif
// Default OpenGL is 4 bytes but it is only safe with RGBA format.
// If format is RGB, row alignment is 4 bytes only if the width is divisible
// by 4. Let's do it the safe way: 1-byte alignment.
// If an algorithm really need 4 bytes alignment, it should set it itself,
// this is the recommended way in "Avoiding 16 Common OpenGL Pitfalls",
// section 7:
// http://www.opengl.org/resources/features/KilgardTechniques/oglpitfall/
this->GetState()->vtkglPixelStorei(GL_UNPACK_ALIGNMENT, 1);
this->GetState()->vtkglPixelStorei(GL_PACK_ALIGNMENT, 1);
// Set the number of alpha bit planes used by the window
int rgba[4];
this->GetColorBufferSizes(rgba);
this->SetAlphaBitPlanes(rgba[3]);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetDefaultTextureInternalFormat(
int vtktype, int numComponents, bool needInt, bool needFloat, bool needSRGB)
{
return this->GetState()->GetDefaultTextureInternalFormat(
vtktype, numComponents, needInt, needFloat, needSRGB);
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::GetOpenGLVersion(int& major, int& minor)
{
int glMajorVersion = 2;
int glMinorVersion = 0;
if (this->Initialized)
{
this->GetState()->vtkglGetIntegerv(GL_MAJOR_VERSION, &glMajorVersion);
this->GetState()->vtkglGetIntegerv(GL_MINOR_VERSION, &glMinorVersion);
}
major = glMajorVersion;
minor = glMinorVersion;
}
//------------------------------------------------------------------------------
bool vtkOpenGLRenderWindow::InitializeFromCurrentContext()
{
this->OpenGLInit();
this->OwnContext = 0;
return true;
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::OpenGLInitContext()
{
this->ContextCreationTime.Modified();
// When a new OpenGL context is created, force an update
if (!this->Initialized)
{
#ifdef GLEW_OK
GLenum result = glewInit();
this->GlewInitValid = (result == GLEW_OK);
if (!this->GlewInitValid)
{
const char* errorMsg = reinterpret_cast<const char*>(glewGetErrorString(result));
vtkErrorMacro("GLEW could not be initialized: " << errorMsg);
return;
}
if (!GLEW_VERSION_3_2 && !GLEW_VERSION_3_1)
{
vtkErrorMacro("Unable to find a valid OpenGL 3.2 or later implementation. "
"Please update your video card driver to the latest version. "
"If you are using Mesa please make sure you have version 11.2 or "
"later and make sure your driver in Mesa supports OpenGL 3.2 such "
"as llvmpipe or openswr. If you are on windows and using Microsoft "
"remote desktop note that it only supports OpenGL 3.2 with nvidia "
"quadro cards. You can use other remoting software such as nomachine "
"to avoid this issue.");
return;
}
#else
// GLEW is not being used, so avoid false failure on GL checks later.
this->GlewInitValid = true;
#endif
this->Initialized = true;
// get this system's supported maximum line width
// we do it here and store it to avoid repeated glGet
// calls when the result should not change
GLfloat lineWidthRange[2];
this->MaximumHardwareLineWidth = 1.0;
#if defined(GL_SMOOTH_LINE_WIDTH_RANGE) && defined(GL_ALIASED_LINE_WIDTH_RANGE)
if (this->LineSmoothing)
{
glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, lineWidthRange);
if (glGetError() == GL_NO_ERROR)
{
this->MaximumHardwareLineWidth = lineWidthRange[1];
}
}
else
{
glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, lineWidthRange);
if (glGetError() == GL_NO_ERROR)
{
this->MaximumHardwareLineWidth = lineWidthRange[1];
}
}
#endif
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetDepthBufferSize()
{
GLint size;
if (this->Initialized)
{
this->MakeCurrent();
size = 0;
GLint fboBind = 0;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fboBind);
if (fboBind == 0)
{
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &size);
}
else
{
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &size);
}
return static_cast<int>(size);
}
else
{
vtkDebugMacro(<< "OpenGL is not initialized yet!");
return 24;
}
}
//------------------------------------------------------------------------------
bool vtkOpenGLRenderWindow::GetUsingSRGBColorSpace()
{
if (this->Initialized)
{
this->MakeCurrent();
GLint attachment = GL_BACK_LEFT;
#ifdef GL_DRAW_BUFFER
glGetIntegerv(GL_DRAW_BUFFER, &attachment);
#endif
// GL seems odd with its handling of left/right.
// if it says we are using GL_FRONT or GL_BACK
// then convert those to GL_FRONT_LEFT and
// GL_BACK_LEFT.
if (attachment == GL_FRONT)
{
attachment = GL_FRONT_LEFT;
// for hardware windows this query seems to not work
// and they seem to almost always honor SRGB values so return
// the setting the user requested
return this->UseSRGBColorSpace;
}
if (attachment == GL_BACK)
{
attachment = GL_BACK_LEFT;
// for hardware windows this query seems to not work
// and they seem to almost always honor SRGB values so return
// the setting the user requested
return this->UseSRGBColorSpace;
}
GLint enc = GL_LINEAR;
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &enc);
if (glGetError() == GL_NO_ERROR)
{
return (enc == GL_SRGB);
}
vtkDebugMacro(<< "Error getting color encoding!");
return false;
}
vtkDebugMacro(<< "OpenGL is not initialized yet!");
return false;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetColorBufferSizes(int* rgba)
{
GLint size;
if (rgba == nullptr)
{
return 0;
}
rgba[0] = 0;
rgba[1] = 0;
rgba[2] = 0;
rgba[3] = 0;
if (this->Initialized)
{
this->MakeCurrent();
GLint attachment = GL_BACK_LEFT;
#ifdef GL_DRAW_BUFFER
glGetIntegerv(GL_DRAW_BUFFER, &attachment);
#endif
// GL seems odd with its handling of left/right.
// if it says we are using GL_FRONT or GL_BACK
// then convert those to GL_FRONT_LEFT and
// GL_BACK_LEFT.
if (attachment == GL_FRONT)
{
attachment = GL_FRONT_LEFT;
}
if (attachment == GL_BACK)
{
attachment = GL_BACK_LEFT;
}
// make sure we clear any errors before we start
// otherwise we may get incorrect results
while (glGetError() != GL_NO_ERROR)
{
}
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, &size);
if (glGetError() == GL_NO_ERROR)
{
rgba[0] = static_cast<int>(size);
}
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, &size);
if (glGetError() == GL_NO_ERROR)
{
rgba[1] = static_cast<int>(size);
}
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, &size);
if (glGetError() == GL_NO_ERROR)
{
rgba[2] = static_cast<int>(size);
}
glGetFramebufferAttachmentParameteriv(
GL_DRAW_FRAMEBUFFER, attachment, GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, &size);
if (glGetError() == GL_NO_ERROR)
{
rgba[3] = static_cast<int>(size);
}
return rgba[0] + rgba[1] + rgba[2] + rgba[3];
}
else
{
vtkDebugMacro(<< "Window is not mapped yet!");
rgba[0] = 8;
rgba[1] = 8;
rgba[2] = 8;
rgba[3] = 8;
return 32;
}
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetColorBufferInternalFormat(int attachmentPoint)
{
int format = 0;
#ifndef GL_ES_VERSION_3_0
if (GLEW_ARB_direct_state_access)
{
int type;
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachmentPoint,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
if (type == GL_TEXTURE)
{
int texName;
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachmentPoint,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &texName);
glGetTextureLevelParameteriv(texName, 0, GL_TEXTURE_INTERNAL_FORMAT, &format);
}
else if (type == GL_RENDERBUFFER)
{
int rbName;
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachmentPoint,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &rbName);
glGetNamedRenderbufferParameteriv(rbName, GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
}
vtkOpenGLClearErrorMacro();
}
#endif
return format;
}
//------------------------------------------------------------------------------
unsigned char* vtkOpenGLRenderWindow::GetPixelData(
int x1, int y1, int x2, int y2, int front, int right)
{
int y_low, y_hi;
int x_low, x_hi;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
int width = (x_hi - x_low) + 1;
int height = (y_hi - y_low) + 1;
unsigned char* ucdata = new unsigned char[width * height * 3];
vtkRecti rect(x_low, y_low, width, height);
this->ReadPixels(rect, front, GL_RGB, GL_UNSIGNED_BYTE, ucdata, right);
return ucdata;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetPixelData(
int x1, int y1, int x2, int y2, int front, vtkUnsignedCharArray* data, int right)
{
int y_low, y_hi;
int x_low, x_hi;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
int width = abs(x_hi - x_low) + 1;
int height = abs(y_hi - y_low) + 1;
int size = 3 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkDebugMacro("Resizing array.");
data->SetNumberOfComponents(3);
data->SetNumberOfValues(size);
}
vtkRecti rect(x_low, y_low, width, height);
return this->ReadPixels(rect, front, GL_RGB, GL_UNSIGNED_BYTE, data->GetPointer(0), right);
}
//------------------------------------------------------------------------------
// does the current read buffer require resolving for reading pixels
bool vtkOpenGLRenderWindow::GetBufferNeedsResolving()
{
if (this->RenderFramebuffer->GetMultiSamples())
{
return true;
}
return false;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::ReadPixels(
const vtkRecti& rect, int front, int glformat, int gltype, void* data, int right)
{
// set the current window
this->MakeCurrent();
if (rect.GetWidth() < 0 || rect.GetHeight() < 0)
{
// invalid box
return VTK_ERROR;
}
// Must clear previous errors first.
while (glGetError() != GL_NO_ERROR)
{
;
}
this->GetState()->vtkglDisable(GL_SCISSOR_TEST);
// Calling pack alignment ensures that we can grab the any size window
this->GetState()->vtkglPixelStorei(GL_PACK_ALIGNMENT, 1);
this->GetState()->PushReadFramebufferBinding();
if (front)
{
this->DisplayFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateReadBuffer(right ? 1 : 0);
}
else
{
this->RenderFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->RenderFramebuffer->ActivateReadBuffer(0);
// Let's determine if we're reading from an FBO.
bool resolveMSAA = this->GetBufferNeedsResolving();
if (resolveMSAA)
{
this->GetState()->PushDrawFramebufferBinding();
int* fbsize = this->RenderFramebuffer->GetLastSize();
this->ResolveFramebuffer->Resize(fbsize[0], fbsize[1]);
this->ResolveFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
// Now blit to resolve the MSAA and get an anti-aliased rendering in
// resolvedFBO.
// Note: extents are (x-min, x-max, y-min, y-max).
const int srcExtents[4] = { rect.GetLeft(), rect.GetRight(), rect.GetBottom(),
rect.GetTop() };
vtkOpenGLFramebufferObject::Blit(srcExtents, srcExtents, GL_COLOR_BUFFER_BIT, GL_NEAREST);
this->GetState()->PopDrawFramebufferBinding();
// Now make the resolvedFBO the read buffer and read from it.
this->ResolveFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->ResolveFramebuffer->ActivateReadBuffer(0);
}
}
glReadPixels(
rect.GetLeft(), rect.GetBottom(), rect.GetWidth(), rect.GetHeight(), glformat, gltype, data);
this->GetState()->PopReadFramebufferBinding();
if (glGetError() != GL_NO_ERROR)
{
return VTK_ERROR;
}
else
{
return VTK_OK;
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::End()
{
this->GetState()->PopFramebufferBindings();
}
//------------------------------------------------------------------------------
// for crystal eyes in stereo we have to blit here as well
void vtkOpenGLRenderWindow::StereoMidpoint()
{
this->Superclass::StereoMidpoint();
if (this->SwapBuffers && this->StereoType == VTK_STEREO_CRYSTAL_EYES)
{
this->GetState()->PushFramebufferBindings();
this->DisplayFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateDrawBuffer(0);
int* fbsize = this->DisplayFramebuffer->GetLastSize();
this->GetState()->vtkglViewport(0, 0, fbsize[0], fbsize[1]);
this->GetState()->vtkglScissor(0, 0, fbsize[0], fbsize[1]);
bool copiedColor = false;
// if we have a MSAA buffer we have to resolve it using a shader as opposed to
// a normal blit due to linear/gamma colorspace issues
if (this->MultiSamples > 1 && this->RenderFramebuffer->GetColorAttachmentAsTextureObject(0))
{
if (!this->ResolveQuad)
{
this->ResolveQuad = new vtkOpenGLQuadHelper(this, nullptr, ResolveShader, "");
if (!this->ResolveQuad->Program || !this->ResolveQuad->Program->GetCompiled())
{
vtkErrorMacro("Couldn't build the shader program for resolving msaa.");
}
}
else
{
this->GetShaderCache()->ReadyShaderProgram(this->ResolveQuad->Program);
}
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
if (this->ResolveQuad->Program && this->ResolveQuad->Program->GetCompiled())
{
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
this->GetState()->vtkglDisable(GL_BLEND);
auto tex = this->RenderFramebuffer->GetColorAttachmentAsTextureObject(0);
tex->Activate();
this->ResolveQuad->Program->SetUniformi("samplecount", this->MultiSamples);
this->ResolveQuad->Program->SetUniformi("tex", tex->GetTextureUnit());
this->ResolveQuad->Render();
tex->Deactivate();
this->GetState()->vtkglEnable(GL_DEPTH_TEST);
this->GetState()->vtkglEnable(GL_BLEND);
}
}
this->RenderFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->RenderFramebuffer->ActivateReadBuffer(0);
// ON APPLE OSX you must turn off scissor test for DEPTH blits to work
auto ostate = this->GetState();
vtkOpenGLState::ScopedglEnableDisable stsaver(ostate, GL_SCISSOR_TEST);
ostate->vtkglDisable(GL_SCISSOR_TEST);
// recall Blit upper right corner is exclusive of the range
const int srcExtents[4] = { 0, fbsize[0], 0, fbsize[1] };
vtkOpenGLFramebufferObject::Blit(srcExtents, srcExtents,
(copiedColor ? 0 : GL_COLOR_BUFFER_BIT) | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
this->GetState()->PopFramebufferBindings();
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::Frame()
{
if (this->SwapBuffers)
{
bool copiedColor = false;
this->GetState()->PushFramebufferBindings();
this->DisplayFramebuffer->Bind();
this->DisplayFramebuffer->ActivateDrawBuffer(
(this->StereoRender && this->StereoType == VTK_STEREO_CRYSTAL_EYES) ? 1 : 0);
int* fbsize = this->DisplayFramebuffer->GetLastSize();
this->GetState()->vtkglViewport(0, 0, fbsize[0], fbsize[1]);
this->GetState()->vtkglScissor(0, 0, fbsize[0], fbsize[1]);
// if we have a MSAA buffer we have to resolve it using a shader as opposed to
// a normal blit due to linear/gamma colorspace issues
if (this->MultiSamples > 1 && this->RenderFramebuffer->GetColorAttachmentAsTextureObject(0))
{
if (!this->ResolveQuad)
{
this->ResolveQuad = new vtkOpenGLQuadHelper(this, nullptr, ResolveShader, "");
if (!this->ResolveQuad->Program || !this->ResolveQuad->Program->GetCompiled())
{
vtkErrorMacro("Couldn't build the shader program for resolving msaa.");
}
}
else
{
this->GetShaderCache()->ReadyShaderProgram(this->ResolveQuad->Program);
}
if (this->ResolveQuad->Program && this->ResolveQuad->Program->GetCompiled())
{
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
this->GetState()->vtkglDisable(GL_BLEND);
auto tex = this->RenderFramebuffer->GetColorAttachmentAsTextureObject(0);
tex->Activate();
this->ResolveQuad->Program->SetUniformi("samplecount", this->MultiSamples);
this->ResolveQuad->Program->SetUniformi("tex", tex->GetTextureUnit());
this->ResolveQuad->Render();
tex->Deactivate();
copiedColor = true;
this->GetState()->vtkglEnable(GL_DEPTH_TEST);
this->GetState()->vtkglEnable(GL_BLEND);
}
}
this->RenderFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->RenderFramebuffer->ActivateReadBuffer(0);
// ON APPLE OSX you must turn off scissor test for DEPTH blits to work
auto ostate = this->GetState();
vtkOpenGLState::ScopedglEnableDisable stsaver(ostate, GL_SCISSOR_TEST);
ostate->vtkglDisable(GL_SCISSOR_TEST);
// recall Blit upper right corner is exclusive of the range
const int srcExtents[4] = { 0, fbsize[0], 0, fbsize[1] };
vtkOpenGLFramebufferObject::Blit(srcExtents, srcExtents,
(copiedColor ? 0 : GL_COLOR_BUFFER_BIT) | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
this->GetState()->vtkglViewport(0, 0, this->Size[0], this->Size[1]);
this->GetState()->vtkglScissor(0, 0, this->Size[0], this->Size[1]);
this->GetState()->PopFramebufferBindings();
if (!this->UseOffScreenBuffers)
{
if (this->FrameBlitMode == BlitToHardware)
{
this->BlitDisplayFramebuffersToHardware();
}
if (this->FrameBlitMode == BlitToCurrent)
{
this->BlitDisplayFramebuffer();
}
}
}
}
void vtkOpenGLRenderWindow::BlitDisplayFramebuffersToHardware()
{
auto ostate = this->GetState();
ostate->PushFramebufferBindings();
this->DisplayFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->GetState()->vtkglViewport(0, 0, this->Size[0], this->Size[1]);
this->GetState()->vtkglScissor(0, 0, this->Size[0], this->Size[1]);
// recall Blit upper right corner is exclusive of the range
const int srcExtents[4] = { 0, this->Size[0], 0, this->Size[1] };
this->GetState()->vtkglBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
if (this->StereoRender && this->StereoType == VTK_STEREO_CRYSTAL_EYES)
{
this->DisplayFramebuffer->ActivateReadBuffer(1);
this->GetState()->vtkglDrawBuffer(this->DoubleBuffer ? GL_BACK_RIGHT : GL_FRONT_RIGHT);
vtkOpenGLFramebufferObject::Blit(
srcExtents, srcExtents, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
this->DisplayFramebuffer->ActivateReadBuffer(0);
this->GetState()->vtkglDrawBuffer(this->DoubleBuffer ? GL_BACK_LEFT : GL_FRONT_LEFT);
vtkOpenGLFramebufferObject::Blit(
srcExtents, srcExtents, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
this->GetState()->PopFramebufferBindings();
}
void vtkOpenGLRenderWindow::BlitDisplayFramebuffer()
{
this->BlitDisplayFramebuffer(0, 0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0],
this->Size[1], GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
void vtkOpenGLRenderWindow::BlitDisplayFramebuffer(int right, int srcX, int srcY, int srcWidth,
int srcHeight, int destX, int destY, int destWidth, int destHeight, int bufferMode,
int interpolation)
{
// ON APPLE OSX you must turn off scissor test for DEPTH blits to work
auto ostate = this->GetState();
vtkOpenGLState::ScopedglEnableDisable stsaver(ostate, GL_SCISSOR_TEST);
ostate->vtkglDisable(GL_SCISSOR_TEST);
this->GetState()->PushReadFramebufferBinding();
this->DisplayFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateReadBuffer(right ? 1 : 0);
const int srcExtents[4] = { srcX, srcX + srcWidth, srcY, srcY + srcHeight };
const int destExtents[4] = { destX, destX + destWidth, destY, destY + destHeight };
this->GetState()->vtkglViewport(destX, destY, destWidth, destHeight);
this->GetState()->vtkglScissor(destX, destY, destWidth, destHeight);
vtkOpenGLFramebufferObject::Blit(srcExtents, destExtents, bufferMode, interpolation);
this->GetState()->PopReadFramebufferBinding();
}
void vtkOpenGLRenderWindow::BlitToRenderFramebuffer(bool includeDepth)
{
this->BlitToRenderFramebuffer(0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0],
this->Size[1], GL_COLOR_BUFFER_BIT | (includeDepth ? GL_DEPTH_BUFFER_BIT : 0), GL_NEAREST);
}
void vtkOpenGLRenderWindow::BlitToRenderFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight,
int destX, int destY, int destWidth, int destHeight, int bufferMode, int interpolation)
{
// depending on what is current bound this can be tricky, especially between multisampled
// buffers
auto ostate = this->GetState();
ostate->PushFramebufferBindings();
const int srcExtents[4] = { srcX, srcX + srcWidth, srcY, srcY + srcHeight };
const int destExtents[4] = { destX, destX + destWidth, destY, destY + destHeight };
ostate->vtkglViewport(destX, destY, destWidth, destHeight);
ostate->vtkglScissor(destX, destY, destWidth, destHeight);
// ON APPLE OSX you must turn off scissor test for DEPTH blits to work
vtkOpenGLState::ScopedglEnableDisable stsaver(ostate, GL_SCISSOR_TEST);
ostate->vtkglDisable(GL_SCISSOR_TEST);
// if we are multisampled, then we might have a problem
if (this->MultiSamples > 1)
{
// be safe and always resolve
int* fbsize = this->RenderFramebuffer->GetLastSize();
this->ResolveFramebuffer->Resize(fbsize[0], fbsize[1]);
this->ResolveFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->ResolveFramebuffer->ActivateDrawBuffer(0);
// Note: extents are (x-min, x-max, y-min, y-max).
vtkOpenGLFramebufferObject::Blit(srcExtents, destExtents, bufferMode, interpolation);
// Now make the resolvedFBO the read buffer and read from it.
this->ResolveFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->ResolveFramebuffer->ActivateReadBuffer(0);
}
this->RenderFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->RenderFramebuffer->ActivateDrawBuffer(0);
vtkOpenGLFramebufferObject::Blit(srcExtents, destExtents, bufferMode, interpolation);
ostate->PopFramebufferBindings();
}
//------------------------------------------------------------------------------
// Begin the rendering process.
void vtkOpenGLRenderWindow::Start()
{
if (!this->Initialized)
{
this->Initialize();
}
// set the current window
this->MakeCurrent();
if (!this->OwnContext)
{
// if the context doesn't belong to us, it's unreasonable to expect that the
// OpenGL state we maintain is going to sync up between subsequent renders.
// Hence, we need to reset it.
this->GetState()->Initialize(this);
}
// default to our standard alpha blend eqn, some vtk classes rely on this
// and do not set it themselves
this->GetState()->vtkglEnable(GL_BLEND);
this->GetState()->vtkglBlendFuncSeparate(
GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// creates or resizes the framebuffer
this->Size[0] = (this->Size[0] > 0 ? this->Size[0] : 300);
this->Size[1] = (this->Size[1] > 0 ? this->Size[1] : 300);
this->CreateFramebuffers(this->Size[0], this->Size[1]);
// push and bind
this->GetState()->PushFramebufferBindings();
this->RenderFramebuffer->Bind();
this->RenderFramebuffer->ActivateDrawBuffer(0);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetPixelData(
int x1, int y1, int x2, int y2, vtkUnsignedCharArray* data, int front, int right)
{
int y_low, y_hi;
int x_low, x_hi;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
int width = abs(x_hi - x_low) + 1;
int height = abs(y_hi - y_low) + 1;
int size = 3 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkErrorMacro("Buffer is of wrong size.");
return VTK_ERROR;
}
return this->SetPixelData(x1, y1, x2, y2, data->GetPointer(0), front, right);
}
//------------------------------------------------------------------------------
// draw (and stretch as needed) the data to the current viewport
void vtkOpenGLRenderWindow::DrawPixels(
int srcWidth, int srcHeight, int numComponents, int dataType, void* data)
{
this->GetState()->vtkglDisable(GL_SCISSOR_TEST);
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
if (!this->DrawPixelsTextureObject)
{
this->DrawPixelsTextureObject = vtkTextureObject::New();
}
else
{
this->DrawPixelsTextureObject->ReleaseGraphicsResources(this);
}
this->DrawPixelsTextureObject->SetContext(this);
this->DrawPixelsTextureObject->Create2DFromRaw(
srcWidth, srcHeight, numComponents, dataType, data);
this->DrawPixelsTextureObject->CopyToFrameBuffer(nullptr, nullptr);
}
//------------------------------------------------------------------------------
// very generic call to draw pixel data to a region of the window
void vtkOpenGLRenderWindow::DrawPixels(int dstXmin, int dstYmin, int dstXmax, int dstYmax,
int srcXmin, int srcYmin, int srcXmax, int srcYmax, int srcWidth, int srcHeight,
int numComponents, int dataType, void* data)
{
this->GetState()->vtkglDisable(GL_SCISSOR_TEST);
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
if (!this->DrawPixelsTextureObject)
{
this->DrawPixelsTextureObject = vtkTextureObject::New();
}
else
{
this->DrawPixelsTextureObject->ReleaseGraphicsResources(this);
}
this->DrawPixelsTextureObject->SetContext(this);
this->DrawPixelsTextureObject->Create2DFromRaw(
srcWidth, srcHeight, numComponents, dataType, data);
this->DrawPixelsTextureObject->CopyToFrameBuffer(srcXmin, srcYmin, srcXmax, srcYmax, dstXmin,
dstYmin, dstXmax, dstYmax, this->GetSize()[0], this->GetSize()[1], nullptr, nullptr);
}
//------------------------------------------------------------------------------
// less generic version, old API
void vtkOpenGLRenderWindow::DrawPixels(
int x1, int y1, int x2, int y2, int numComponents, int dataType, void* data)
{
int y_low, y_hi;
int x_low, x_hi;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
int width = x_hi - x_low + 1;
int height = y_hi - y_low + 1;
// call the more generic version
this->DrawPixels(x_low, y_low, x_hi, y_hi, 0, 0, width - 1, height - 1, width, height,
numComponents, dataType, data);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetPixelData(
int x1, int y1, int x2, int y2, unsigned char* data, int front, int right)
{
// set the current window
this->MakeCurrent();
// Error checking
// Must clear previous errors first.
while (glGetError() != GL_NO_ERROR)
{
;
}
this->GetState()->PushDrawFramebufferBinding();
if (front)
{
this->DisplayFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateDrawBuffer(right ? 1 : 0);
}
else
{
this->RenderFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->RenderFramebuffer->ActivateDrawBuffer(0);
}
this->DrawPixels(x1, y1, x2, y2, 3, VTK_UNSIGNED_CHAR, data);
this->GetState()->PopDrawFramebufferBinding();
// This seems to be necessary for the image to show up
if (front)
{
glFlush();
}
if (glGetError() != GL_NO_ERROR)
{
return VTK_ERROR;
}
else
{
return VTK_OK;
}
}
//------------------------------------------------------------------------------
float* vtkOpenGLRenderWindow::GetRGBAPixelData(int x1, int y1, int x2, int y2, int front, int right)
{
int y_low, y_hi;
int x_low, x_hi;
int width, height;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
width = abs(x_hi - x_low) + 1;
height = abs(y_hi - y_low) + 1;
float* fdata = new float[(width * height * 4)];
vtkRecti rect(x_low, y_low, width, height);
this->ReadPixels(rect, front, GL_RGBA, GL_FLOAT, fdata, right);
return fdata;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetRGBAPixelData(
int x1, int y1, int x2, int y2, int front, vtkFloatArray* data, int right)
{
int y_low, y_hi;
int x_low, x_hi;
int width, height;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
width = abs(x_hi - x_low) + 1;
height = abs(y_hi - y_low) + 1;
int size = 4 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkDebugMacro("Resizing array.");
data->SetNumberOfComponents(4);
data->SetNumberOfValues(size);
}
vtkRecti rect(x_low, y_low, width, height);
return this->ReadPixels(rect, front, GL_RGBA, GL_FLOAT, data->GetPointer(0), right);
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::ReleaseRGBAPixelData(float* data)
{
delete[] data;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetRGBAPixelData(
int x1, int y1, int x2, int y2, vtkFloatArray* data, int front, int blend, int right)
{
int y_low, y_hi;
int x_low, x_hi;
int width, height;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
width = abs(x_hi - x_low) + 1;
height = abs(y_hi - y_low) + 1;
int size = 4 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkErrorMacro("Buffer is of wrong size.");
return VTK_ERROR;
}
return this->SetRGBAPixelData(x1, y1, x2, y2, data->GetPointer(0), front, blend, right);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetRGBAPixelData(
int x1, int y1, int x2, int y2, float* data, int front, int blend, int right)
{
// set the current window
this->MakeCurrent();
// Error checking
// Must clear previous errors first.
while (glGetError() != GL_NO_ERROR)
{
;
}
this->GetState()->PushDrawFramebufferBinding();
if (front)
{
this->DisplayFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateDrawBuffer(right ? 1 : 0);
}
else
{
this->RenderFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->RenderFramebuffer->ActivateDrawBuffer(0);
}
if (!blend)
{
this->GetState()->vtkglDisable(GL_BLEND);
this->DrawPixels(x1, y1, x2, y2, 4, VTK_FLOAT, data); // TODO replace dprecated function
this->GetState()->vtkglEnable(GL_BLEND);
}
else
{
this->DrawPixels(x1, y1, x2, y2, 4, VTK_FLOAT, data);
}
this->GetState()->PopDrawFramebufferBinding();
// This seems to be necessary for the image to show up
if (front)
{
glFlush();
}
if (glGetError() != GL_NO_ERROR)
{
return VTK_ERROR;
}
else
{
return VTK_OK;
}
}
//------------------------------------------------------------------------------
unsigned char* vtkOpenGLRenderWindow::GetRGBACharPixelData(
int x1, int y1, int x2, int y2, int front, int right)
{
int y_low, y_hi;
int x_low, x_hi;
int width, height;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
width = abs(x_hi - x_low) + 1;
height = abs(y_hi - y_low) + 1;
unsigned char* ucdata = new unsigned char[(width * height) * 4];
vtkRecti rect(x_low, y_low, width, height);
this->ReadPixels(rect, front, GL_RGBA, GL_UNSIGNED_BYTE, ucdata, right);
return ucdata;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetRGBACharPixelData(
int x1, int y1, int x2, int y2, int front, vtkUnsignedCharArray* data, int right)
{
int y_low, y_hi;
int x_low, x_hi;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
int width = abs(x_hi - x_low) + 1;
int height = abs(y_hi - y_low) + 1;
int size = 4 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkDebugMacro("Resizing array.");
data->SetNumberOfComponents(4);
data->SetNumberOfValues(size);
}
vtkRecti rect(x_low, y_low, width, height);
return this->ReadPixels(rect, front, GL_RGBA, GL_UNSIGNED_BYTE, data->GetPointer(0), right);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetRGBACharPixelData(
int x1, int y1, int x2, int y2, vtkUnsignedCharArray* data, int front, int blend, int right)
{
int y_low, y_hi;
int x_low, x_hi;
int width, height;
if (y1 < y2)
{
y_low = y1;
y_hi = y2;
}
else
{
y_low = y2;
y_hi = y1;
}
if (x1 < x2)
{
x_low = x1;
x_hi = x2;
}
else
{
x_low = x2;
x_hi = x1;
}
width = abs(x_hi - x_low) + 1;
height = abs(y_hi - y_low) + 1;
int size = 4 * width * height;
if (data->GetMaxId() + 1 != size)
{
vtkErrorMacro(
"Buffer is of wrong size. It is " << data->GetMaxId() + 1 << ", it should be: " << size);
return VTK_ERROR;
}
return this->SetRGBACharPixelData(x1, y1, x2, y2, data->GetPointer(0), front, blend, right);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetRGBACharPixelData(
int x1, int y1, int x2, int y2, unsigned char* data, int front, int blend, int right)
{
// set the current window
this->MakeCurrent();
// Error checking
// Must clear previous errors first.
while (glGetError() != GL_NO_ERROR)
{
;
}
this->GetState()->PushDrawFramebufferBinding();
if (front)
{
this->DisplayFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->DisplayFramebuffer->ActivateDrawBuffer(right ? 1 : 0);
}
else
{
this->RenderFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->RenderFramebuffer->ActivateDrawBuffer(0);
}
// Disable writing on the z-buffer.
this->GetState()->vtkglDepthMask(GL_FALSE);
this->GetState()->vtkglDisable(GL_DEPTH_TEST);
if (!blend)
{
this->GetState()->vtkglDisable(GL_BLEND);
this->DrawPixels(x1, y1, x2, y2, 4, VTK_UNSIGNED_CHAR, data);
this->GetState()->vtkglEnable(GL_BLEND);
}
else
{
this->DrawPixels(x1, y1, x2, y2, 4, VTK_UNSIGNED_CHAR, data);
}
this->GetState()->PopDrawFramebufferBinding();
// Renenable writing on the z-buffer.
this->GetState()->vtkglDepthMask(GL_TRUE);
this->GetState()->vtkglEnable(GL_DEPTH_TEST);
if (glGetError() != GL_NO_ERROR)
{
return VTK_ERROR;
}
else
{
return VTK_OK;
}
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetZbufferData(int x1, int y1, int x2, int y2, float* z_data)
{
int y_low;
int x_low;
int width, height;
// set the current window
this->MakeCurrent();
if (y1 < y2)
{
y_low = y1;
}
else
{
y_low = y2;
}
if (x1 < x2)
{
x_low = x1;
}
else
{
x_low = x2;
}
width = abs(x2 - x1) + 1;
height = abs(y2 - y1) + 1;
// Error checking
// Must clear previous errors first.
while (glGetError() != GL_NO_ERROR)
{
;
}
this->GetState()->vtkglDisable(GL_SCISSOR_TEST);
// Calling pack alignment ensures that we can grab the any size window
this->GetState()->vtkglPixelStorei(GL_PACK_ALIGNMENT, 1);
this->GetState()->PushReadFramebufferBinding();
this->RenderFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->RenderFramebuffer->ActivateReadBuffer(0);
// Let's determine if we're reading from an FBO.
bool resolveMSAA = this->GetBufferNeedsResolving();
if (resolveMSAA)
{
this->GetState()->PushDrawFramebufferBinding();
int* fbsize = this->RenderFramebuffer->GetLastSize();
this->ResolveFramebuffer->Resize(fbsize[0], fbsize[1]);
this->ResolveFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
// Now blit to resolve the MSAA and get an anti-aliased rendering in
// resolvedFBO.
// Note: extents are (x-min, x-max, y-min, y-max).
const int srcExtents[4] = { x_low, x_low + width, y_low, y_low + height };
vtkOpenGLFramebufferObject::Blit(srcExtents, srcExtents, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
this->GetState()->PopDrawFramebufferBinding();
// Now make the resolvedFBO the read buffer and read from it.
this->ResolveFramebuffer->Bind(GL_READ_FRAMEBUFFER);
this->ResolveFramebuffer->ActivateReadBuffer(0);
}
glReadPixels(x_low, y_low, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, z_data);
this->GetState()->PopReadFramebufferBinding();
if (glGetError() != GL_NO_ERROR)
{
return VTK_ERROR;
}
else
{
return VTK_OK;
}
}
//------------------------------------------------------------------------------
float* vtkOpenGLRenderWindow::GetZbufferData(int x1, int y1, int x2, int y2)
{
float* z_data;
int width, height;
width = abs(x2 - x1) + 1;
height = abs(y2 - y1) + 1;
z_data = new float[width * height];
this->GetZbufferData(x1, y1, x2, y2, z_data);
return z_data;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetZbufferData(int x1, int y1, int x2, int y2, vtkFloatArray* buffer)
{
int width, height;
width = abs(x2 - x1) + 1;
height = abs(y2 - y1) + 1;
int size = width * height;
if (buffer->GetMaxId() + 1 != size)
{
vtkDebugMacro("Resizing array.");
buffer->SetNumberOfComponents(1);
buffer->SetNumberOfValues(size);
}
return this->GetZbufferData(x1, y1, x2, y2, buffer->GetPointer(0));
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetZbufferData(int x1, int y1, int x2, int y2, vtkFloatArray* buffer)
{
int width, height;
width = abs(x2 - x1) + 1;
height = abs(y2 - y1) + 1;
int size = width * height;
if (buffer->GetMaxId() + 1 != size)
{
vtkErrorMacro("Buffer is of wrong size.");
return VTK_ERROR;
}
return this->SetZbufferData(x1, y1, x2, y2, buffer->GetPointer(0));
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SetZbufferData(int x1, int y1, int x2, int y2, float* buffer)
{
vtkOpenGLState* ostate = this->GetState();
ostate->vtkglDisable(GL_SCISSOR_TEST);
ostate->vtkglEnable(GL_DEPTH_TEST);
ostate->vtkglDepthFunc(GL_ALWAYS);
ostate->vtkglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
if (!this->DrawPixelsTextureObject)
{
this->DrawPixelsTextureObject = vtkTextureObject::New();
}
else
{
this->DrawPixelsTextureObject->ReleaseGraphicsResources(this);
}
this->DrawPixelsTextureObject->SetContext(this);
this->DrawPixelsTextureObject->CreateDepthFromRaw(
x2 - x1 + 1, y2 - y1 + 1, vtkTextureObject::Float32, VTK_FLOAT, buffer);
// compile and bind it if needed
vtkShaderProgram* program = this->GetShaderCache()->ReadyShaderProgram(vtkTextureObjectVS,
"//VTK::System::Dec\n"
"in vec2 tcoordVC;\n"
"uniform sampler2D source;\n"
"//VTK::Output::Dec\n"
"void main(void) {\n"
" gl_FragDepth = texture2D(source,tcoordVC).r; }\n",
"");
if (!program)
{
return VTK_ERROR;
}
vtkOpenGLVertexArrayObject* VAO = vtkOpenGLVertexArrayObject::New();
this->GetState()->PushDrawFramebufferBinding();
this->RenderFramebuffer->Bind(GL_DRAW_FRAMEBUFFER);
this->RenderFramebuffer->ActivateDrawBuffer(0);
// bind and activate this texture
this->DrawPixelsTextureObject->Activate();
program->SetUniformi("source", this->DrawPixelsTextureObject->GetTextureUnit());
this->DrawPixelsTextureObject->CopyToFrameBuffer(
0, 0, x2 - x1, y2 - y1, x1, y1, x2, y2, this->GetSize()[0], this->GetSize()[1], program, VAO);
this->DrawPixelsTextureObject->Deactivate();
VAO->Delete();
this->GetState()->PopDrawFramebufferBinding();
ostate->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
ostate->vtkglDepthFunc(GL_LEQUAL);
return VTK_OK;
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::ActivateTexture(vtkTextureObject* texture)
{
this->GetState()->ActivateTexture(texture);
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::DeactivateTexture(vtkTextureObject* texture)
{
this->GetState()->DeactivateTexture(texture);
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetTextureUnitForTexture(vtkTextureObject* texture)
{
return this->GetState()->GetTextureUnitForTexture(texture);
}
//------------------------------------------------------------------------------
// Description:
// Create an offScreen window based on OpenGL framebuffer extension.
// Return if the creation was successful or not.
// \pre positive_width: width>0
// \pre positive_height: height>0
// \post valid_result: (result==0 || result==1)
int vtkOpenGLRenderWindow::CreateFramebuffers(int width, int height)
{
assert("pre: positive_width" && width > 0);
assert("pre: positive_height" && height > 0);
#if defined(__APPLE__)
// make sure requested multisamples is OK with platform
// APPLE Intel systems seem to have buggy multisampled
// frambuffer blits etc that cause issues
if (this->MultiSamples > 0)
{
if (this->GetState()->GetVendor().find("Intel") != std::string::npos)
{
this->MultiSamples = 0;
}
}
#endif
if (this->LastMultiSamples != this->MultiSamples)
{
this->RenderFramebuffer->ReleaseGraphicsResources(this);
}
if (!this->RenderFramebuffer->GetFBOIndex())
{
// verify that our multisample setting doe snot exceed the hardware
if (this->MultiSamples)
{
#ifdef GL_MAX_SAMPLES
int msamples = 0;
this->GetState()->vtkglGetIntegerv(GL_MAX_SAMPLES, &msamples);
if (this->MultiSamples > msamples)
{
this->MultiSamples = msamples;
}
if (this->MultiSamples == 1)
{
this->MultiSamples = 0;
}
#else
this->MultSamples = 0;
#endif
}
this->GetState()->PushFramebufferBindings();
this->RenderFramebuffer->PopulateFramebuffer(width, height,
#ifdef GL_TEXTURE_2D_MULTISAMPLE
true, // textures
#else
this->MultiSamples ? false : true, // textures
#endif
1, VTK_UNSIGNED_CHAR, // 1 color buffer uchar
true, 32, // depth buffer
this->MultiSamples, this->StencilCapable != 0 ? true : false);
this->LastMultiSamples = this->MultiSamples;
this->GetState()->PopFramebufferBindings();
}
else
{
this->RenderFramebuffer->Resize(width, height);
}
if (!this->DisplayFramebuffer->GetFBOIndex())
{
this->GetState()->PushFramebufferBindings();
this->DisplayFramebuffer->PopulateFramebuffer(width, height,
true, // textures
2, VTK_UNSIGNED_CHAR, // 1 color buffer uchar
true, 32, // depth buffer
0, this->StencilCapable != 0 ? true : false);
this->GetState()->PopFramebufferBindings();
}
else
{
this->DisplayFramebuffer->Resize(width, height);
}
if (!this->ResolveFramebuffer->GetFBOIndex())
{
this->GetState()->PushFramebufferBindings();
this->ResolveFramebuffer->PopulateFramebuffer(width, height,
true, // textures
1, VTK_UNSIGNED_CHAR, // 1 color buffer uchar
true, 32, // depth buffer
0, this->StencilCapable != 0 ? true : false);
this->GetState()->PopFramebufferBindings();
}
return 1;
}
//------------------------------------------------------------------------------
// Description:
// Returns its texture unit manager object. A new one will be created if one
// hasn't already been set up.
vtkTextureUnitManager* vtkOpenGLRenderWindow::GetTextureUnitManager()
{
return this->GetState()->GetTextureUnitManager();
}
//------------------------------------------------------------------------------
// Description:
// Block the thread until the actual rendering is finished().
// Useful for measurement only.
void vtkOpenGLRenderWindow::WaitForCompletion()
{
glFinish();
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::SaveGLState()
{
// For now just query the active texture unit
if (this->Initialized)
{
this->MakeCurrent();
vtkOpenGLRenderUtilities::MarkDebugEvent("Saving OpenGL State");
this->GetState()->Reset();
this->GetState()->Push();
vtkOpenGLRenderUtilities::MarkDebugEvent("Saved OpenGL State");
}
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::RestoreGLState()
{
// Prevent making GL calls unless we have a valid context
if (this->Initialized)
{
vtkOpenGLRenderUtilities::MarkDebugEvent("Restoring OpenGL State");
this->GetState()->Pop();
// Unuse active shader program
this->GetShaderCache()->ReleaseCurrentShader();
vtkOpenGLRenderUtilities::MarkDebugEvent("Restored OpenGL State");
}
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::SupportsOpenGL()
{
if (this->OpenGLSupportTested)
{
return this->OpenGLSupportResult;
}
vtkOutputWindow* oldOW = vtkOutputWindow::GetInstance();
oldOW->Register(this);
vtkNew<vtkStringOutputWindow> sow;
vtkOutputWindow::SetInstance(sow);
vtkOpenGLRenderWindow* rw = this->NewInstance();
rw->SetDisplayId(this->GetGenericDisplayId());
rw->SetOffScreenRendering(1);
rw->Initialize();
if (rw->GlewInitValid == false)
{
this->OpenGLSupportMessage = "glewInit failed for this window, OpenGL not supported.";
rw->Delete();
vtkOutputWindow::SetInstance(oldOW);
oldOW->Delete();
return 0;
}
#ifdef GLEW_OK
else if (GLEW_VERSION_3_2 || GLEW_VERSION_3_1)
{
this->OpenGLSupportResult = 1;
this->OpenGLSupportMessage = "The system appears to support OpenGL 3.2/3.1";
}
#endif
if (this->OpenGLSupportResult)
{
// even if glew thinks we have support we should actually try linking a
// shader program to make sure
vtkShaderProgram* newShader = rw->GetShaderCache()->ReadyShaderProgram(
// simple vert shader
"//VTK::System::Dec\n"
"in vec4 vertexMC;\n"
"void main() { gl_Position = vertexMC; }\n",
// frag shader that used gl_PrimitiveId
"//VTK::System::Dec\n"
"//VTK::Output::Dec\n"
"void main(void) {\n"
" gl_FragData[0] = vec4(float(gl_PrimitiveID)/100.0,1.0,1.0,1.0);\n"
"}\n",
// no geom shader
"");
if (newShader == nullptr)
{
this->OpenGLSupportResult = 0;
this->OpenGLSupportMessage = "The system appeared to have OpenGL Support but a test shader "
"program failed to compile and link";
}
}
rw->Delete();
this->OpenGLSupportMessage += "vtkOutputWindow Text Folows:\n\n" + sow->GetOutput();
vtkOutputWindow::SetInstance(oldOW);
oldOW->Delete();
this->OpenGLSupportTested = true;
return this->OpenGLSupportResult;
}
//------------------------------------------------------------------------------
vtkOpenGLBufferObject* vtkOpenGLRenderWindow::GetTQuad2DVBO()
{
if (!this->TQuad2DVBO || !this->TQuad2DVBO->GetHandle())
{
if (!this->TQuad2DVBO)
{
this->TQuad2DVBO = vtkOpenGLBufferObject::New();
this->TQuad2DVBO->SetType(vtkOpenGLBufferObject::ArrayBuffer);
}
float verts[16] = { 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 0.f, 1.f, 1.f, -1.f, 1.f, 0.f, -1.f, -1.f,
0.f, 0.f };
bool res = this->TQuad2DVBO->Upload(verts, 16, vtkOpenGLBufferObject::ArrayBuffer);
if (!res)
{
vtkGenericWarningMacro("Error uploading fullscreen quad vertex data.");
}
}
return this->TQuad2DVBO;
}
//------------------------------------------------------------------------------
int vtkOpenGLRenderWindow::GetNoiseTextureUnit()
{
if (!this->NoiseTextureObject)
{
this->NoiseTextureObject = vtkTextureObject::New();
this->NoiseTextureObject->SetContext(this);
}
if (this->NoiseTextureObject->GetHandle() == 0)
{
vtkNew<vtkPerlinNoise> generator;
generator->SetFrequency(64, 64, 1.0);
generator->SetAmplitude(0.5);
int const bufferSize = 64 * 64;
float* noiseTextureData = new float[bufferSize];
for (int i = 0; i < bufferSize; i++)
{
int const x = i % 64;
int const y = i / 64;
noiseTextureData[i] = static_cast<float>(generator->EvaluateFunction(x, y, 0.0) + 0.5);
}
// Prepare texture
this->NoiseTextureObject->Create2DFromRaw(64, 64, 1, VTK_FLOAT, noiseTextureData);
this->NoiseTextureObject->SetWrapS(vtkTextureObject::Repeat);
this->NoiseTextureObject->SetWrapT(vtkTextureObject::Repeat);
this->NoiseTextureObject->SetMagnificationFilter(vtkTextureObject::Nearest);
this->NoiseTextureObject->SetMinificationFilter(vtkTextureObject::Nearest);
delete[] noiseTextureData;
}
int result = this->GetTextureUnitForTexture(this->NoiseTextureObject);
if (result >= 0)
{
return result;
}
this->NoiseTextureObject->Activate();
return this->GetTextureUnitForTexture(this->NoiseTextureObject);
}
//------------------------------------------------------------------------------
void vtkOpenGLRenderWindow::Render()
{
if (this->Initialized)
{
vtkOpenGLRenderUtilities::MarkDebugEvent("Starting vtkOpenGLRenderWIndow::Render");
}
this->Superclass::Render();
if (this->FirstRenderTime < 0)
{
this->FirstRenderTime = vtkTimerLog::GetUniversalTime();
}
this->GetShaderCache()->SetElapsedTime(vtkTimerLog::GetUniversalTime() - this->FirstRenderTime);
if (this->NoiseTextureObject && this->GetTextureUnitForTexture(this->NoiseTextureObject) >= 0)
{
this->NoiseTextureObject->Deactivate();
}
if (this->Initialized)
{
vtkOpenGLRenderUtilities::MarkDebugEvent("Completed vtkOpenGLRenderWIndow::Render");
}
}
| 28.479857
| 100
| 0.620772
|
bartholmberg
|
6165d4667166d5a46c09cf173c3143d76254af5a
| 8,435
|
hpp
|
C++
|
src/RNG/Random123.hpp
|
franjgonzalez/Quinoa
|
411eb8815e92618c563881b784e287e2dd916f89
|
[
"RSA-MD"
] | null | null | null |
src/RNG/Random123.hpp
|
franjgonzalez/Quinoa
|
411eb8815e92618c563881b784e287e2dd916f89
|
[
"RSA-MD"
] | null | null | null |
src/RNG/Random123.hpp
|
franjgonzalez/Quinoa
|
411eb8815e92618c563881b784e287e2dd916f89
|
[
"RSA-MD"
] | null | null | null |
// *****************************************************************************
/*!
\file src/RNG/Random123.hpp
\copyright 2012-2015 J. Bakosi,
2016-2018 Los Alamos National Security, LLC.,
2019 Triad National Security, LLC.
All rights reserved. See the LICENSE file for details.
\brief Interface to Random123 random number generators
\details Interface to Random123 random number generators
*/
// *****************************************************************************
#ifndef Random123_h
#define Random123_h
#include <cstring>
#include <random>
#include <limits>
#include <array>
#include "NoWarning/uniform.hpp"
#include "NoWarning/beta_distribution.hpp"
#include <boost/random/gamma_distribution.hpp>
#include "Make_unique.hpp"
#include "Exception.hpp"
#include "Keywords.hpp"
#include "Macro.hpp"
namespace tk {
//! Random123-based random number generator used polymorphically with tk::RNG
template< class CBRNG >
class Random123 {
private:
static const std::size_t CBRNG_DATA_SIZE = 3;
using ncomp_t = kw::ncomp::info::expect::type;
using ctr_type = typename CBRNG::ctr_type;
using key_type = typename CBRNG::key_type;
using value_type = typename CBRNG::ctr_type::value_type;
using arg_type = std::vector< std::array< value_type, CBRNG_DATA_SIZE > >;
//! Adaptor to use a std distribution with the Random123 generator
//! \see C++ concepts: UniformRandomNumberGenerator
struct Adaptor {
using result_type = unsigned long;
Adaptor( CBRNG& r, arg_type& d, int t ) : rng(r), data(d), tid(t) {}
static constexpr result_type min() { return 0u; }
static constexpr result_type max() {
return std::numeric_limits< result_type >::max();
}
result_type operator()()
{
auto& d = data[ static_cast< std::size_t >( tid ) ];
d[2] = static_cast< result_type >( tid );
ctr_type ctr = {{ d[0], d[1] }}; // assemble counter
key_type key = {{ d[2] }}; // assemble key
auto res = rng( ctr, key ); // generate
ctr.incr();
d[0] = ctr[0];
d[1] = ctr[1];
return res[0];
}
CBRNG& rng;
arg_type& data;
int tid;
};
public:
//! Constructor
//! \param[in] n Initialize RNG using this many independent streams
//! \param[in] seed RNG seed
explicit Random123( uint64_t n = 1, uint64_t seed = 0 ) {
Assert( n > 0, "Need at least one thread" );
m_data.resize( n, {{ 0, seed << 32, 0 }} );
}
//! Uniform RNG: Generate uniform random numbers
//! \param[in] tid Thread (or more precisely) stream ID
//! \param[in] num Number of RNGs to generate
//! \param[in,out] r Pointer to memory to write the random numbers to
void uniform( int tid, ncomp_t num, double* r ) const {
auto& d = m_data[ static_cast< std::size_t >( tid ) ];
for (ncomp_t i=0; i<num; ++i) {
d[2] = static_cast< unsigned long >( tid );
ctr_type ctr = {{ d[0], d[1] }}; // assemble counter
key_type key = {{ d[2] }}; // assemble key
auto res = m_rng( ctr, key ); // generate
r[i] = r123::u01fixedpt< double, value_type >( res[0] );
ctr.incr();
d[0] = ctr[0];
d[1] = ctr[1];
}
}
//! Gaussian RNG: Generate Gaussian random numbers
//! \param[in] tid Thread (or more precisely stream) ID
//! \param[in] num Number of RNGs to generate
//! \param[in,out] r Pointer to memory to write the random numbers to
//! \details Generating Gaussian random numbers is implemented via an
//! adaptor, modeling std::UniformRandomNumberGenerator, outsourcing the
//! transformation of uniform random numbers to Gaussian ones, to the
//! standard library. The adaptor is instantiated here because a standard
//! distribution, such as e.g., std::normal_distribution, generates
//! numbers using operator() with no arguments, thus the RNG state and the
//! thread ID (this latter only known here) must be stored in the adaptor
//! functor's state. Even though creating the adaptor seems like a
//! potentially costly operation for every call, using the standard
//! library implementation is still faster than a hand-coded
//! implementation of the Box-Muller algorithm. Note that libc++ uses a
//! cache, as Box-Muller, implemented using the polar algorithm generates
//! 2 Gaussian numbers for each pair of uniform ones, caching every 2nd.
void gaussian( int tid, ncomp_t num, double* r ) const {
Adaptor generator( m_rng, m_data, tid );
std::normal_distribution<> gauss_dist( 0.0, 1.0 );
for (ncomp_t i=0; i<num; ++i) r[i] = gauss_dist( generator );
}
//! \brief Multi-variate Gaussian RNG: Generate multi-variate Gaussian
//! random numbers
//! \param[in] tid Thread (or more precisely stream) ID
//! \param[in] num Number of RNGs to generate
//! \param[in] d Dimension d ( d ≥ 1) of output random vectors
//! \param[in] mean Mean vector of dimension d
//! \param[in] cov Lower triangle of covariance matrix, stored as a vector
//! of length d(d+1)/2
//! \param[in,out] r Pointer to memory to write the random numbers to
//! \warning Not implemented!
void gaussianmv( int tid, ncomp_t num, ncomp_t d, const double* const mean,
const double* const cov, double* r ) const
{
IGNORE(tid);
IGNORE(num);
IGNORE(d);
IGNORE(mean);
IGNORE(cov);
IGNORE(r);
}
//! Beta RNG: Generate beta random numbers
//! \param[in] tid Thread (or more precisely stream) ID
//! \param[in] num Number of RNGs to generate
//! \param[in] p First beta shape parameter
//! \param[in] q Second beta shape parameter
//! \param[in] a Beta displacement parameter
//! \param[in] b Beta scale factor
//! \param[in,out] r Pointer to memory to write the random numbers to
//! \details Generating beta-distributed random numbers is implemented via
//! an adaptor, modeling boost::UniformRandomNumberGenerator, outsourcing
//! the transformation of uniform random numbers to beta-distributed ones,
//! to boost::random. The adaptor is instantiated here because a boost
//! random number distribution, such as e.g.,
//! boost::random::beta_distribution, generates numbers using operator()
//! with no arguments, thus the RNG state and the thread ID (this latter
//! only known here) must be stored in the adaptor functor's state.
void beta( int tid, ncomp_t num, double p, double q, double a, double b,
double* r ) const {
Adaptor generator( m_rng, m_data, tid );
boost::random::beta_distribution<> beta_dist( p, q );
for (ncomp_t i=0; i<num; ++i) r[i] = beta_dist( generator ) * b + a;
}
//! Gamma RNG: Generate gamma random numbers
//! \param[in] tid Thread (or more precisely stream) ID
//! \param[in] num Number of RNGs to generate
//! \param[in] a Gamma shape parameter
//! \param[in] b Gamma scale factor
//! \param[in,out] r Pointer to memory to write the random numbers to
//! \details Generating gamma-distributed random numbers is implemented via
//! an adaptor, modeling boost::UniformRandomNumberGenerator, outsourcing
//! the transformation of uniform random numbers to gamma-distributed
//! ones, to boost::random. The adaptor is instantiated here because a
//! boost random number distribution, such as e.g.,
//! boost::random::gamma_distribution, generates numbers using operator()
//! with no arguments, thus the RNG state and the thread ID (this latter
//! only known here) must be stored in the adaptor functor's state.
void gamma( int tid, ncomp_t num, double a, double b, double* r ) const {
Adaptor generator( m_rng, m_data, tid );
boost::random::gamma_distribution<> gamma_dist( a, b );
for (ncomp_t i=0; i<num; ++i) r[i] = gamma_dist( generator );
}
//! Accessor to the number of threads we operate on
uint64_t nthreads() const noexcept { return m_data.size(); }
private:
mutable CBRNG m_rng; //!< Random123 RNG object
mutable arg_type m_data; //!< RNG arguments
};
} // tk::
#endif // Random123_h
| 43.479381
| 80
| 0.628216
|
franjgonzalez
|
616b3243e42e5c6eb1d4f963d24bf8ff1c36782c
| 1,261
|
hpp
|
C++
|
core/core_util.hpp
|
tamasgoga/SnakeRipoff
|
a9ca7fbaf7803173e803929f3dbd5dbd43fe223e
|
[
"MIT"
] | null | null | null |
core/core_util.hpp
|
tamasgoga/SnakeRipoff
|
a9ca7fbaf7803173e803929f3dbd5dbd43fe223e
|
[
"MIT"
] | null | null | null |
core/core_util.hpp
|
tamasgoga/SnakeRipoff
|
a9ca7fbaf7803173e803929f3dbd5dbd43fe223e
|
[
"MIT"
] | null | null | null |
#ifndef FLAG_CORE_CORE_UTIL_HPP
#define FLAG_CORE_CORE_UTIL_HPP
//------------------------------------------------------------
// Utility functions and variables
//------------------------------------------------------------
#include "core_def.hpp"
#include <SDL2/SDL_rect.h>
namespace core {
/** Find the center of an rectangle */
inline float centerX(const SDL_Rect& rect) noexcept {return (rect.x + rect.x + rect.w) * 0.5f;}
inline float centerY(const SDL_Rect& rect) noexcept {return (rect.y + rect.y + rect.h) * 0.5f;}
/** Scale an SDL_Rect. Nothing happens if amount == 1 or amount <= 0. */
SDL_Rect scale(SDL_Rect rect, float amount);
/** Check if point is inside a rectangle */
bool isInside(int x, int y, const SDL_Rect& rect);
/** Ladies and gentleman, I give you the one and only "Fast Inverse Square Root" algorithm.
Here for historical & inspirational purposes; not very useful when today's FPUs are so fast.
Research on # of iterations:
- 1: a bit faster than sqrt(), but the result differs at the precision of 10^-4 and onwards;
- 2: quite slower than sqrt(), but the result only differs by 1 at the precision of 10^-6. */
float rsqrt(float x);
} // namespace core
#endif // FLAG_CORE_CORE_UTIL_HPP
| 33.184211
| 100
| 0.63521
|
tamasgoga
|
616df23411178cebad8598f46886421ce209f3b3
| 2,280
|
hpp
|
C++
|
include/bhtree.hpp
|
shohirose/sphcode
|
67efb8882520cd8d53ca12ec07439dfa515fd862
|
[
"MIT"
] | 14
|
2019-06-23T12:39:44.000Z
|
2022-03-01T06:29:30.000Z
|
include/bhtree.hpp
|
shohirose/sphcode
|
67efb8882520cd8d53ca12ec07439dfa515fd862
|
[
"MIT"
] | 7
|
2019-10-20T14:07:19.000Z
|
2019-11-12T13:51:22.000Z
|
include/bhtree.hpp
|
shohirose/sphcode
|
67efb8882520cd8d53ca12ec07439dfa515fd862
|
[
"MIT"
] | 3
|
2019-09-13T11:21:28.000Z
|
2021-05-28T05:56:07.000Z
|
#pragma once
#include <memory>
#include <vector>
#include <algorithm>
#include "vector_type.hpp"
#include "particle.hpp"
namespace sph
{
struct SPHParameters;
class Periodic;
constexpr int NCHILD = DIM == 1 ? 2 : DIM == 2 ? 4 : 8;
class BHTree
{
class BHNode
{
public:
SPHParticle * first;
real mass;
int num;
BHNode * childs[NCHILD];
vec_t center;
vec_t m_center; // mass center
real edge;
int level;
real kernel_size;
bool is_leaf;
void clear() {
first = nullptr;
mass = 0.0;
num = 0;
std::fill(childs, childs + NCHILD, nullptr);
center = 0.0;
m_center = 0.0;
edge = 0.0;
level = 0;
kernel_size = 0.0;
is_leaf = false;
}
void root_clear() {
first = nullptr;
mass = 0.0;
num = 0;
m_center = 0.0;
kernel_size = 0.0;
is_leaf = false;
}
void create_tree(BHNode * & nodes, int & remaind, const int max_level, const int leaf_particle_num);
void assign(SPHParticle * particle, BHNode * & nodes, int & remaind);
real set_kernel();
void neighbor_search(const SPHParticle & p_i, std::vector<int> & neighbor_list, int & n_neighbor, const bool is_ij, const Periodic * periodic);
void calc_force(SPHParticle & p_i, const real theta2, const real g_constant, const Periodic * periodic);
};
int m_max_level;
int m_leaf_particle_num;
bool m_is_periodic;
vec_t m_range_max;
vec_t m_range_min;
std::shared_ptr<Periodic> m_periodic;
BHNode m_root;
std::shared_ptr<BHNode> m_nodes;
int m_node_size;
real m_g_constant;
real m_theta;
real m_theta2;
public:
void initialize(std::shared_ptr<SPHParameters> param);
void resize(const int particle_num, const int tree_size = 5);
void make(std::vector<SPHParticle> & particles, const int particle_num);
void set_kernel();
int neighbor_search(const SPHParticle & p_i, std::vector<int> & neighbor_list, const std::vector<SPHParticle> & particles, const bool is_ij = false);
void tree_force(SPHParticle & p_i);
};
}
| 27.142857
| 153
| 0.59693
|
shohirose
|
61734910f7cbb370b5d2801a3f353ad84ef626d6
| 25,571
|
cpp
|
C++
|
toonz/sources/toonz/trackerpopup.cpp
|
Savraska2/opentoonz
|
47ab3039c899ae1a50d612d097415ab09f10f35e
|
[
"BSD-3-Clause"
] | 36
|
2020-05-18T22:26:35.000Z
|
2022-02-19T00:09:25.000Z
|
toonz/sources/toonz/trackerpopup.cpp
|
LibrePhone/opentoonz
|
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
|
[
"BSD-3-Clause"
] | 22
|
2017-03-16T18:52:36.000Z
|
2019-09-09T06:02:53.000Z
|
toonz/sources/toonz/trackerpopup.cpp
|
LibrePhone/opentoonz
|
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
|
[
"BSD-3-Clause"
] | 9
|
2019-05-27T02:48:16.000Z
|
2022-03-29T12:32:04.000Z
|
#include "trackerpopup.h"
// Tnz6 includes
#include "tapp.h"
#include "filmstripselection.h"
#include "cellselection.h"
#include "menubarcommandids.h"
// TnzTools includes
#include "tools/toolhandle.h"
#include "tools/tool.h"
// TnzQt includes
#include "toonzqt/doublefield.h"
#include "toonzqt/checkbox.h"
#include "toonzqt/menubarcommand.h"
#include "toonzqt/tselectionhandle.h"
// TnzLib includes
#include "toonz/hook.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/txshcell.h"
#include "toonz/toonzscene.h"
#include "toonz/tscenehandle.h"
#include "toonz/tframehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/tcamera.h"
// TnzCore includes
#include "tlevel_io.h"
#include "tpalette.h"
#include "trasterimage.h"
#include "ttoonzimage.h"
#include "tvectorimage.h"
#include "tropcm.h"
#include "tofflinegl.h"
#include "tvectorrenderdata.h"
#include "tsystem.h"
// Qt includes
#include <QPushButton>
#include <QComboBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QMainWindow>
using namespace DVGui;
using namespace std;
//=============================================================================
namespace {
//=============================================================================
// helper function
TFrameId getFidFromFrame(int frame) {
TApp *app = TApp::instance();
if (app->getCurrentFrame()->isEditingLevel()) {
TXshLevel *level = app->getCurrentLevel()->getLevel();
assert(level);
if (level->getFrameCount() < frame)
return TFrameId();
else
return TFrameId(frame);
}
int columnIndex = app->getCurrentColumn()->getColumnIndex();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
assert(xsh);
TXshColumn *column = xsh->getColumn(columnIndex);
assert(column);
TXshCellColumn *cellColumn = column->getCellColumn();
if (frame > cellColumn->getRowCount()) return TFrameId();
TXshCell cell = cellColumn->getCell(frame - 1);
return cell.getFrameId();
}
//-----------------------------------------------------------------------------
TRaster32P resampleRaster(TRaster32P raster, const TAffine &affine) {
if (affine.isIdentity()) return raster;
TRect rasRect = raster->getBounds();
TRectD newRect = affine * convert(rasRect);
TRaster32P app(TDimension(newRect.getLx(), newRect.getLy()));
app->clear();
TRop::resample(app, raster, affine);
return app;
}
//-----------------------------------------------------------------------------
TRaster32P loadFrame(int frame, const TAffine &affine) {
TFrameId id = getFidFromFrame(frame);
if (id.isNoFrame()) return (TRaster32P)0;
TImageP img = TApp::instance()->getCurrentLevel()->getSimpleLevel()->getFrame(
id, false);
if (!img) return (TRaster32P)0;
TPaletteP plt = img->getPalette();
TRasterImageP ri = img;
TVectorImageP vi = img;
TToonzImageP ti = img;
if (ri) {
TRaster32P raster = TRaster32P(ri->getRaster());
return resampleRaster(raster, affine);
} else if (vi) {
assert(plt);
TCamera *camera =
TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera();
if (!camera) return TRaster32P();
TDimension size = camera->getRes();
TVectorImageP vimage = vi->clone();
vimage->transform(TTranslation((size.lx - 1) * 0.5, (size.ly - 1) * 0.5),
true);
TVectorRenderData rd(TVectorRenderData::ProductionSettings(), TAffine(),
size, plt.getPointer());
TOfflineGL offlineContext(size);
offlineContext.makeCurrent();
offlineContext.clear(TPixel32(0, 0, 0, 0));
offlineContext.draw(vimage, rd);
TRaster32P raster = offlineContext.getRaster();
assert(raster->getSize() == size);
return resampleRaster(raster, affine);
} else if (ti) {
assert(plt);
TRasterCM32P CMras = ti->getCMapped();
TRaster32P raster = TRaster32P(CMras->getSize());
TRop::convert(raster, CMras, plt);
return resampleRaster(raster, affine);
} else
return TRaster32P();
}
//-----------------------------------------------------------------------------
} // namespace
//-----------------------------------------------------------------------------
//=============================================================================
// TrackerPopup
//-----------------------------------------------------------------------------
#if QT_VERSION >= 0x050500
TrackerPopup::TrackerPopup(QWidget *parent, Qt::WindowFlags flags)
#else
TrackerPopup::TrackerPopup(QWidget *parent, Qt::WFlags flags)
#endif
: Dialog(TApp::instance()->getMainWindow(), true, true, "Tracker") {
// Su MAC i dialog modali non hanno bottoni di chiusura nella titleBar
setModal(false);
setWindowTitle(tr("Tracking Settings"));
beginVLayout();
// IntField per i parametri threshold, accuracy, smoothness
m_threshold = new DoubleField(); // W_Threshold
m_threshold->setFixedHeight(WidgetHeight);
m_threshold->setRange(0, 1);
m_threshold->setValue(0.2);
addWidget(tr("Threshold:"), m_threshold);
m_sensitivity = new DoubleField(); // W_Accuracy
m_sensitivity->setFixedHeight(WidgetHeight);
m_sensitivity->setRange(0, 1000);
m_sensitivity->setValue(10);
addWidget(tr("Sensitivity:"), m_sensitivity);
m_variationWindow = new CheckBox(tr("Variable Region Size"));
m_variationWindow->setFixedHeight(WidgetHeight);
addWidget(m_variationWindow);
m_activeBackground = new CheckBox(tr("Include Background"));
m_activeBackground->setFixedHeight(WidgetHeight);
addWidget(m_activeBackground);
endVLayout();
// Bottone Convert
m_trackBtn = new QPushButton(QString(tr("Track")), this); // W_Vectorize
connect(m_trackBtn, SIGNAL(clicked()), this, SLOT(onTrack()));
addButtonBarWidget(m_trackBtn);
}
//-----------------------------------------------------------------------------
bool TrackerPopup::apply() {
float threshold = m_threshold->getValue();
float sensitivity = m_sensitivity->getValue() / 1000;
int activeBackground = m_activeBackground->isChecked();
int manageOcclusion = 0;
int variationWindow = m_variationWindow->isChecked();
TSelection *selection =
TApp::instance()->getCurrentSelection()->getSelection();
TCellSelection *cellSelection = dynamic_cast<TCellSelection *>(selection);
TFilmstripSelection *filmstripSelection =
dynamic_cast<TFilmstripSelection *>(selection);
int frameStart = 0;
int framesNumber = 0;
if (cellSelection) {
TCellSelection::Range range = cellSelection->getSelectedCells();
if (range.getColCount() == 1) {
frameStart = range.m_r0 + 1;
framesNumber = range.m_r1 - range.m_r0 + 1;
}
} else if (filmstripSelection) {
set<TFrameId> frameIds = filmstripSelection->getSelectedFids();
if (!frameIds.empty()) {
frameStart = frameIds.begin()->getNumber();
framesNumber = frameIds.size();
}
} else
return false;
if (framesNumber <= 0) return false;
m_tracker =
new Tracker(threshold, sensitivity, activeBackground, manageOcclusion,
variationWindow, frameStart, framesNumber);
if (m_tracker->getLastError() != 0) {
DVGui::warning(m_tracker->getLastError());
return false;
}
m_myThread = new MyThread(m_tracker);
connect(m_myThread, SIGNAL(finished()), this, SLOT(startNewThread()));
m_progressBarIndex = 0;
m_stoppedProcess = false;
m_progress =
new ProgressDialog(tr("Processing..."), tr("Cancel"), m_progressBarIndex,
m_tracker->getFramesNumber() - 1);
// QPushButton* cancelButton = new QPushButton(QString("Cancel"),this);
// m_progress->setCancelButton(cancelButton);
bool ret =
connect(m_progress, SIGNAL(canceled()), this, SLOT(stopProcessing()));
assert(ret);
// m_progress->setWindowModality(Qt::WindowModal);
m_progress->show();
m_myThread->start();
return true;
}
void TrackerPopup::startNewThread() {
// Interruzione del processing da parte dell'utente
if (m_stoppedProcess) return;
QString lastError = m_tracker->getLastError();
if (lastError != "") {
QMessageBox::critical(this, "Tracking Error", lastError);
m_progress->close();
return;
}
int progressBarMaxValue = m_tracker->getFramesNumber() - 1;
m_progressBarIndex++;
m_progress->setValue(m_progressBarIndex);
if (m_progressBarIndex < progressBarMaxValue) {
m_myThread->start();
} else {
m_progress->close();
close();
}
}
void TrackerPopup::stopProcessing() {
m_myThread->quit();
m_stoppedProcess = true;
m_myThread->wait();
}
//-----------------------------------------------------------------------------
void TrackerPopup::onTrack() { apply(); }
//=============================================================================
// TrackerPopup
//-----------------------------------------------------------------------------
Tracker::Tracker(double threshold, double sensitivity, int activeBackground,
int manageOcclusion, int variationWindow, int frameStart,
int framesNumber)
: m_affine() {
m_threshold = threshold;
m_sensitivity = sensitivity;
m_activeBackground = activeBackground;
m_manageOcclusion = manageOcclusion;
m_variationWindow = variationWindow;
m_indexFrameStart = frameStart;
m_framesNumber = framesNumber;
m_processor = new DummyProcessor();
m_processor->setActive(false);
m_lastErrorCode = 0;
setup();
}
//-----------------------------------------------------------------------------
Tracker::~Tracker() {
int i = 0;
for (i = 0; i < m_trackerCount; i++) delete m_pObjectTracker[i];
}
//-----------------------------------------------------------------------------
bool Tracker::setup() {
ToolHandle *toolH = TApp::instance()->getCurrentTool();
if (toolH && toolH->getTool()) toolH->getTool()->reset();
TTool *tool = toolH->getTool();
TXshLevel *xl = TApp::instance()->getCurrentLevel()->getLevel();
if (!xl) {
m_lastErrorCode = 13;
return false;
}
// setto il frame di partenza
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
int columnIndex = TApp::instance()->getCurrentColumn()->getColumnIndex();
TFrameId frameStartId =
xsh->getCell(m_indexFrameStart - 1, columnIndex).getFrameId();
if (frameStartId.isNoFrame()) {
m_lastErrorCode = 11;
return false;
}
int startFrameGlobalIndex = frameStartId.getNumber() - 1;
TFrameHandle *fh = TApp::instance()->getCurrentFrame();
if (!fh) {
m_lastErrorCode = 1;
return false;
}
HookSet *hookSet = xl->getHookSet();
if (!hookSet) {
m_lastErrorCode = 2;
return false;
}
m_trackerObjectsSet = hookSet->getTrackerObjectsSet();
if (!m_trackerObjectsSet ||
m_trackerObjectsSet->getTrackerObjectsCount() == 0) {
m_lastErrorCode = 2;
return false;
}
TXshSimpleLevel *simpleLevel = xl->getSimpleLevel();
if (!simpleLevel) {
m_lastErrorCode = 13;
return false;
}
TFilePath fp1 = xl->getSimpleLevel()->getPath();
if (fp1.isEmpty()) {
m_lastErrorCode = 12;
return false;
}
TFilePath fp(xl->getSimpleLevel()->getScene()->decodeFilePath(fp1));
if (fp.isEmpty() || !TSystem::doesExistFileOrLevel(fp)) {
m_lastErrorCode = 14;
return false;
}
TLevelReaderP levelReader;
try {
levelReader = TLevelReaderP(fp);
} catch (...) {
m_lastErrorCode = 1;
return false;
}
if (!levelReader) {
m_lastErrorCode = 1;
return false;
}
m_level = levelReader->loadInfo();
if (!m_level) {
m_lastErrorCode = 1;
return false;
}
// # elements to track
m_trackerCount = 0;
int k = 0;
for (k = 0; k < (int)m_trackerObjectsSet->getTrackerObjectsCount(); k++) {
m_trackerCount =
m_trackerCount +
m_trackerObjectsSet->getObjectFromIndex(k)->getHooksCount();
}
if (m_trackerCount <= 0 || m_trackerCount > 30) {
m_lastErrorCode = 3;
return false;
}
// ID object
std::unique_ptr<short[]> id(new short[m_trackerCount]);
if (!id) {
m_lastErrorCode = 1;
return false;
}
//(x,y) coordinate object
std::unique_ptr<short[]> x(new short[m_trackerCount]);
if (!x) {
m_lastErrorCode = 1;
return false;
}
std::unique_ptr<short[]> y(new short[m_trackerCount]);
if (!y) {
m_lastErrorCode = 1;
return false;
}
// Width and Height of object box
std::unique_ptr<short[]> Width(new short[m_trackerCount]);
if (!Width) {
m_lastErrorCode = 1;
return false;
}
std::unique_ptr<short[]> Height(new short[m_trackerCount]);
if (!Height) {
m_lastErrorCode = 1;
return false;
}
//# start frame
std::unique_ptr<int[]> m_numstart(new int[m_trackerCount]);
if (!m_numstart) {
m_lastErrorCode = 1;
return false;
}
TImageP imagep = tool->getImage(false);
if (!imagep) {
m_lastErrorCode = 1;
return false;
}
TRasterImageP ri = imagep;
TVectorImageP vi = imagep;
TToonzImageP ti = imagep;
TPaletteP plt = m_level->getPalette();
if (ri)
m_raster = ri->getRaster();
else if (vi) {
assert(plt);
TCamera *camera =
TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera();
if (!camera) {
m_lastErrorCode = 1;
return false;
}
TDimension size = camera->getRes();
TVectorImageP vimage = vi->clone();
vimage->transform(TTranslation((size.lx - 1) * 0.5, (size.ly - 1) * 0.5),
true);
TVectorRenderData rd(TVectorRenderData::ProductionSettings(), TAffine(),
size, plt.getPointer());
TOfflineGL offlineContext(size);
offlineContext.makeCurrent();
offlineContext.clear(TPixel32(0, 0, 0, 0));
offlineContext.draw(vimage, rd);
m_raster = offlineContext.getRaster();
assert(m_raster->getSize() == size);
} else if (ti) {
assert(plt);
TRasterCM32P CMras = ti->getCMapped();
m_raster = TRaster32P(CMras->getSize());
TRop::convert(m_raster, CMras, plt);
} else {
m_lastErrorCode = 1;
return false;
}
TDimension size = m_raster->getSize();
if (size.lx > 1024 || size.ly > 768) {
double scaleX = 1024.0 / (double)size.lx;
double scaleY = 768.0 / (double)size.ly;
double factor = scaleX > scaleY ? scaleY : scaleX;
m_affine = TScale(factor);
m_raster = resampleRaster(m_raster, m_affine);
size = m_raster->getSize();
}
TFrameId fid = toolH->getTool()->getCurrentFid();
m_rasterOrigin = m_raster->getCenterD() - TPointD(size.lx, 0);
// characteristics objects
int posInitObject = 0;
int totalFrameCount = m_level->getFrameCount();
int i = 0;
for (i = 0; i < (int)m_trackerObjectsSet->getTrackerObjectsCount(); i++) {
int j = 0;
for (j = 0; j < m_trackerObjectsSet->getObjectFromIndex(i)->getHooksCount();
j++) {
id[posInitObject + j] =
m_trackerObjectsSet->getObjectFromIndex(i)->getId();
Hook *hook = m_trackerObjectsSet->getObjectFromIndex(i)->getHook(j);
TPointD hookPos = m_affine * hook->getPos(fid);
assert(hook);
double globalx = hookPos.x;
double localx = globalx - m_rasterOrigin.x;
x[posInitObject + j] = localx;
if (x[posInitObject + j] < 0 || x[posInitObject + j] > size.lx - 1) {
m_lastErrorCode = 4;
return false;
}
double globaly = hookPos.y;
double localy = globaly - m_rasterOrigin.y;
y[posInitObject + j] = -localy;
if (y[posInitObject + j] < 0 || y[posInitObject + j] > size.ly - 1) {
m_lastErrorCode = 4;
return false;
}
TRectD trackerRect(TDimensionD(hook->getTrackerRegionWidth(),
hook->getTrackerRegionHeight()));
trackerRect = m_affine * trackerRect;
Width[posInitObject + j] = trackerRect.getLx();
// controllo che le dimensioni (larghezza) della regioni siano contenute
// nell'immagine
if (Width[posInitObject + j] <= 0 ||
x[posInitObject + j] - 0.5 * Width[posInitObject + j] < 0 ||
x[posInitObject + j] + 0.5 * Width[posInitObject + j] > size.lx) {
m_lastErrorCode = 5;
return false;
}
Height[posInitObject + j] = trackerRect.getLy();
// controllo che le dimensioni (altezza) della regioni siano contenute
// nell'immagine
if (Height[posInitObject + j] <= 0 ||
y[posInitObject + j] - 0.5 * Height[posInitObject + j] < 0 ||
y[posInitObject + j] + 0.5 * Height[posInitObject + j] > size.ly) {
m_lastErrorCode = 6;
return false;
}
m_numstart[posInitObject + j] = startFrameGlobalIndex;
if (m_numstart[posInitObject + j] < 0 ||
m_numstart[posInitObject + j] >= totalFrameCount - 1) {
m_lastErrorCode = 12;
return false;
}
}
posInitObject +=
m_trackerObjectsSet->getObjectFromIndex(i)->getHooksCount();
}
int numframe = m_framesNumber;
if (numframe < 1 || (fh->getMaxFrameIndex() - m_indexFrameStart + 2) < 0) {
m_lastErrorCode = 8;
return false;
}
if (numframe >= (fh->getMaxFrameIndex() - m_indexFrameStart) + 2) {
numframe = (fh->getMaxFrameIndex() - m_indexFrameStart) + 2;
m_framesNumber = numframe;
}
// dimension searce template area
short dimtemp = 8;
// variation dimension window
short vardim = m_variationWindow;
// threshold lose object (null =0)
float threshold_dist = m_threshold;
if ((threshold_dist < 0.0) || (threshold_dist > 1.0)) {
m_lastErrorCode = 9;
return false;
}
float threshold_distB = 0.6 * threshold_dist;
if ((m_sensitivity < 0) || (m_sensitivity > 1)) {
m_lastErrorCode = 10;
return false;
}
m_currentFrame = m_indexFrameStart;
// update current frame
m_raster = loadFrame(m_currentFrame, m_affine);
if (!m_raster) {
m_lastErrorCode = 1;
return false;
}
m_processor->setActive(false);
m_processor->process(m_raster);
// Store the old value of m_processor
bool status = m_processor->isActive();
// Set processing false
m_processor->setActive(false);
bool image_c = true;
bool image_background = false;
bool occl = m_manageOcclusion;
// costruct trackers
for (i = 0; i < m_trackerCount; i++) {
// costruct
m_pObjectTracker[i] =
new CObjectTracker(size.lx, size.ly, image_c, image_background, occl);
// initialization
m_pObjectTracker[i]->ObjectTrackerInitObjectParameters(
id[i], x[i], y[i], Width[i], Height[i], dimtemp, vardim, threshold_dist,
threshold_distB);
}
m_numobjactive = 0;
for (i = 0; i < m_trackerCount; i++) {
if (m_numstart[0] == m_numstart[i])
m_numobjactive++;
else
break;
}
m_raster_template = new TRaster32P[m_trackerCount];
for (i = 0; (i < m_numobjactive); i++) {
// tracking object first frame
m_pObjectTracker[i]->ObjeckTrackerHandlerByUser(&m_raster);
m_raster_template[i] = m_raster;
}
m_num = m_numstart[0] + 1;
++m_currentFrame;
m_trackerRegionIndex = 0;
m_oldObjectId = 0;
return true;
}
//-----------------------------------------------------------------------------
bool Tracker::trackCurrentFrame() {
m_raster_prev = m_raster;
// update Current Frame;
m_raster = loadFrame(m_currentFrame, m_affine);
if (!m_raster) {
m_lastErrorCode = 1;
return false;
}
m_processor->process(m_raster);
short app1 = 0;
app1 = m_numobjactive;
// control active object
int i = 0;
for (i = m_numobjactive; (i < m_trackerCount); i++) {
if (m_num == m_numstart[m_numobjactive])
m_numobjactive++;
else
break;
}
for (i = 0; i < app1; i++) {
// tracking old objects
if (m_pObjectTracker[i]->track)
m_pObjectTracker[i]->ObjeckTrackerHandlerByUser(&m_raster);
float dist_temp;
dist_temp = m_pObjectTracker[i]->Matching(&m_raster, &m_raster_template[i]);
if ((dist_temp < m_sensitivity) && (m_pObjectTracker[i]->track)) {
m_raster_template[i] = m_raster;
m_pObjectTracker[i]->updateTemp();
}
}
// update neighbours
for (i = 0; i < app1; i++) {
m_pObjectTracker[i]->DistanceReset();
for (int k = 0; k < app1; k++) {
if ((m_pObjectTracker[k]->track) && (i != k) &&
(m_pObjectTracker[i]->objID == m_pObjectTracker[k]->objID)) {
NEIGHBOUR position = m_pObjectTracker[k]->GetPosition();
m_pObjectTracker[i]->DistanceAndUpdate(position);
if (!m_pObjectTracker[i]->GetInit()) {
m_pObjectTracker[i]->SetInitials(m_pObjectTracker[i]->GetPosition());
}
}
}
m_pObjectTracker[i]->SetInit(true);
}
Predict3D::Point current[30], initials[30];
bool visible[30];
// datiPredict<<endl<<"-----------------------------"<<endl<<endl;
for (i = 0; i < app1; i++) {
visible[i] = m_pObjectTracker[i]->track;
initials[i] = m_pObjectTracker[i]->GetInitials();
NEIGHBOUR position = m_pObjectTracker[i]->GetPosition();
current[i].x = position.X;
current[i].y = position.Y;
}
int k_dist;
for (i = 0; i < app1; i++) {
if (m_pObjectTracker[i]->GetVisibility() == "WARNING") {
if (Predict3D::Predict(app1, initials, current, visible)) {
k_dist = m_pObjectTracker[i]->GetKDist();
NEIGHBOUR position = m_pObjectTracker[i]->GetPosition();
m_pObjectTracker[i]->SetPosition(
(k_dist * (current[i].x) + (1 - k_dist) * (position.X)),
(k_dist * (current[i].y) + (1 - k_dist) * (position.Y)));
}
}
// Set position by neighbours
if (!m_pObjectTracker[i]->track) {
if (Predict3D::Predict(app1, initials, current, visible)) {
m_pObjectTracker[i]->SetPosition(current[i].x, current[i].y);
} else {
m_pObjectTracker[i]->SetVisibility("LOST");
}
}
short objectId = m_pObjectTracker[i]->getId();
if (objectId != m_oldObjectId) {
m_trackerRegionIndex = 0;
m_oldObjectId = objectId;
}
double globalx = m_rasterOrigin.x + m_pObjectTracker[i]->GetPosition().X;
double globaly = m_rasterOrigin.y - m_pObjectTracker[i]->GetPosition().Y;
Hook *hook =
m_trackerObjectsSet->getObject(objectId)->getHook(m_trackerRegionIndex);
hook->setAPos(getFidFromFrame(m_currentFrame),
m_affine.inv() * TPointD(globalx, globaly));
m_trackerRegionIndex++;
if (m_trackerRegionIndex >=
m_trackerObjectsSet->getObject(objectId)->getHooksCount()) {
m_trackerRegionIndex = 0;
}
}
// tracking new objects
for (i = app1; i < m_numobjactive; i++) {
m_pObjectTracker[i]->ObjeckTrackerHandlerByUser(&m_raster);
m_raster_template[i] = m_raster;
}
++m_currentFrame;
++m_num;
return true;
}
//-----------------------------------------------------------------------------
QString Tracker::getErrorMessage(int errorCode) {
QString errorMessage;
switch (errorCode) {
case 0: // No Error
errorMessage = QObject::tr("");
break;
case 1:
errorMessage = QObject::tr(
"It is not possible to track the level:\nallocation error.");
break;
case 2:
errorMessage = QObject::tr(
"It is not possible to track the level:\nno region defined.");
break;
case 3:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\nmore than 30 regions "
"defined.");
break;
case 4:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\ndefined regions are "
"not valid.");
break;
case 5:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\nsome regions are too "
"wide.");
break;
case 6:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\nsome regions are too "
"high.");
break;
case 7:
errorMessage = QObject::tr("Frame Start Error");
break;
case 8:
errorMessage = QObject::tr("Frame End Error");
break;
case 9:
errorMessage = QObject::tr("Threshold Distance Error");
break;
case 10:
errorMessage = QObject::tr("Sensitivity Error");
break;
case 11:
errorMessage = QObject::tr("No Frame Found");
break;
case 12:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\nthe selected level is "
"not valid.");
break;
case 13:
errorMessage = QObject::tr(
"It is not possible to track the level:\nno level selected.");
break;
case 14:
errorMessage = QObject::tr(
"It is not possible to track specified regions:\nthe level has to be "
"saved first.");
break;
default:
errorMessage =
QObject::tr("It is not possible to track the level:\nundefined error.");
}
return errorMessage;
}
//-----------------------------------------------------------------------------
MyThread::MyThread(Tracker *tracker) { m_tracker = tracker; }
//-----------------------------------------------------------------------------
void MyThread::run() { m_tracker->trackCurrentFrame(); }
//=============================================================================
// TrackerPopupCommand
//-----------------------------------------------------------------------------
OpenPopupCommandHandler<TrackerPopup> openTrackerPopup(MI_Tracking);
| 30.808434
| 80
| 0.608072
|
Savraska2
|
61752df3d9deaaa07372810e34fa14d8ed36ab7f
| 1,270
|
hpp
|
C++
|
libvast/include/vast/concept/printable/vast/port.hpp
|
rdettai/vast
|
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
|
[
"BSD-3-Clause"
] | 249
|
2019-08-26T01:44:45.000Z
|
2022-03-26T14:12:32.000Z
|
libvast/include/vast/concept/printable/vast/port.hpp
|
rdettai/vast
|
0b3cf41011df5fe8a4e8430fa6a1d6f1c50a18fa
|
[
"BSD-3-Clause"
] | 586
|
2019-08-06T13:10:36.000Z
|
2022-03-31T08:31:00.000Z
|
libvast/vast/concept/printable/vast/port.hpp
|
satta/vast
|
6c7587effd4265c4a5de23252bc7c7af3ef78bee
|
[
"BSD-3-Clause"
] | 37
|
2019-08-16T02:01:14.000Z
|
2022-02-21T16:13:59.000Z
|
// _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2016 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include "vast/concept/printable/core/printer.hpp"
#include "vast/concept/printable/numeric/integral.hpp"
#include "vast/concept/printable/string/char.hpp"
#include "vast/concept/printable/string/string.hpp"
#include "vast/port.hpp"
namespace vast {
struct port_printer : printer_base<port_printer> {
using attribute = port;
template <class Iterator>
bool print(Iterator& out, const port& p) const {
using namespace printers;
if (!(u16(out, p.number()) && chr<'/'>(out)))
return false;
switch (p.type()) {
default:
return chr<'?'>(out);
case port_type::icmp:
return str(out, "icmp");
case port_type::tcp:
return str(out, "tcp");
case port_type::udp:
return str(out, "udp");
case port_type::icmp6:
return str(out, "icmp6");
case port_type::sctp:
return str(out, "sctp");
}
}
};
template <>
struct printer_registry<port> {
using type = port_printer;
};
} // namespace vast
| 25.4
| 57
| 0.612598
|
rdettai
|
6175c22c79a2e29bdb4906aa175995792620795a
| 5,374
|
hh
|
C++
|
dune/gdt/test/operators/darcy.hh
|
TiKeil/dune-gdt
|
25c8b987cc07a4b8b966c1a07ea21b78dba7852f
|
[
"BSD-2-Clause"
] | null | null | null |
dune/gdt/test/operators/darcy.hh
|
TiKeil/dune-gdt
|
25c8b987cc07a4b8b966c1a07ea21b78dba7852f
|
[
"BSD-2-Clause"
] | null | null | null |
dune/gdt/test/operators/darcy.hh
|
TiKeil/dune-gdt
|
25c8b987cc07a4b8b966c1a07ea21b78dba7852f
|
[
"BSD-2-Clause"
] | null | null | null |
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2014 - 2018)
// Rene Milk (2014, 2016, 2018)
// Tobias Leibner (2014)
#ifndef DUNE_GDT_TEST_OPERATORS_DARCY_HH
#define DUNE_GDT_TEST_OPERATORS_DARCY_HH
#include <dune/xt/common/test/gtest/gtest.h>
#include <dune/xt/la/container.hh>
#include <dune/xt/functions/expression.hh>
#include <dune/xt/grid/gridprovider/cube.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/operators/darcy.hh>
#include <dune/gdt/projections.hh>
#include <dune/gdt/operators/laplace.hh>
#include <dune/gdt/operators/l2.hh>
#include <dune/gdt/spaces/cg.hh>
#include <dune/gdt/spaces/fv.hh>
#include <dune/gdt/spaces/rt/default.hh>
namespace Dune {
namespace GDT {
namespace Test {
/**
* \note This test assumes that DiscreteFunction, Operators::L2Projection, Products::L2, Products::H1Semi,
* ContinuousLagrangeSpace, RaviartThomasSpace and FvSpace work correctly.
* \todo This test is rather old and could be refactored in terms of the other operator tests.
* \todo Missing ctor and make_darcy_operator tests.
*/
template <class SpaceTypes>
struct DarcyOperatorTest : public ::testing::Test
{
typedef typename SpaceTypes::first_type SourceSpaceType;
typedef typename SpaceTypes::second_type RangeSpaceType;
typedef typename RangeSpaceType::GridLayerType GridLayerType;
typedef XT::Grid::extract_grid_t<GridLayerType> GridType;
typedef XT::Grid::GridProvider<GridType, XT::Grid::none_t> GridProviderType;
using EntityType = XT::Grid::extract_entity_t<GridLayerType>;
typedef typename GridLayerType::ctype DomainFieldType;
static const size_t dimDomain = SourceSpaceType::dimDomain;
typedef double RangeFieldType;
typedef typename Dune::XT::LA::Container<RangeFieldType>::VectorType VectorType;
void produces_correct_results() const
{
GridProviderType grid_provider(XT::Grid::make_cube_grid<GridType>(0.0, 1.0, 4));
grid_provider.global_refine(1);
typedef XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1> FunctionType;
const FunctionType source("x", "x[0] * x[1]", 2, "source", {"x[1]", "x[0]"});
const RangeSpaceType range_space(
grid_provider.template layer<XT::Grid::Layers::leaf, RangeSpaceType::layer_backend>());
VectorType range_vector(range_space.mapper().size());
DiscreteFunction<RangeSpaceType, VectorType> range(range_space, range_vector);
const FunctionType function("x", "-1.0", 0);
const DarcyOperator<GridLayerType, FunctionType> darcy_operator(range_space.grid_layer(), function);
darcy_operator.apply(source, range);
const XT::Functions::ExpressionFunction<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain>
desired_output(
"x", std::vector<std::string>({"x[1]", "x[0]"}), 1, "desired output", {{"0.0", "1.0"}, {"1.0", "0.0"}});
const RangeFieldType l2_error = make_l2_operator(range_space.grid_layer(), 2)->induced_norm(desired_output - range);
const RangeFieldType l2_error_expected = expected_result_("l2", desired_output, range_space.grid_layer());
EXPECT_LE(l2_error, l2_error_expected);
const RangeFieldType h1_error =
make_laplace_operator(range_space.grid_layer(), 2)->induced_norm(desired_output - range);
const RangeFieldType h1_error_expected = expected_result_("h1", desired_output, range_space.grid_layer());
EXPECT_LE(h1_error, h1_error_expected);
} // ... produces_correct_results()
template <class FunctionType, class GL>
RangeFieldType
expected_result_(const std::string type, const FunctionType& desired_output, const GL& grid_layer) const
{
if (std::is_base_of<Dune::GDT::ContinuousLagrangeSpace<GL, 1, double>, RangeSpaceType>::value) {
if (type == "l2")
return 2.18e-16;
else if (type == "h1")
return 3.12e-15;
else
DUNE_THROW(Dune::XT::Common::Exceptions::internal_error, type);
} else if (std::is_base_of<RaviartThomasSpace<GL, 0, RangeFieldType>, RangeSpaceType>::value) {
typedef FvSpace<GL, RangeFieldType, dimDomain> FvSpaceType;
const FvSpaceType fv_space(grid_layer);
VectorType fv_desired_output_vector(fv_space.mapper().size());
DiscreteFunction<FvSpaceType, VectorType> fv_desired_output(fv_space, fv_desired_output_vector);
project(desired_output, fv_desired_output);
if (type == "l2") {
return 2.0 * make_l2_operator(grid_layer, 2)->induced_norm(desired_output - fv_desired_output);
} else if (type == "h1") {
return make_laplace_operator(grid_layer, 2)->induced_norm(desired_output - fv_desired_output);
} else
DUNE_THROW(Dune::XT::Common::Exceptions::internal_error, type);
} else
DUNE_THROW(Dune::XT::Common::Exceptions::internal_error, type);
} // ... expected_result_(...)
}; // struct DarcyOperatorTest
} // namespace Test
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_TEST_OPERATORS_DARCY_HH
| 44.04918
| 120
| 0.731857
|
TiKeil
|
61764e62bfbe03e1f5a1c5a50c70228764fd1e73
| 1,617
|
cpp
|
C++
|
PlatformLib/common/cpp/revTexture.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
PlatformLib/common/cpp/revTexture.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
PlatformLib/common/cpp/revTexture.cpp
|
YIMonge/Rev
|
db3b71a27659a2652bdd50069a881702b3ae059e
|
[
"MIT"
] | null | null | null |
#include "revTexture.h"
#define STB_IMAGE_IMPLEMENTATION
// TODO: set memory allocation way
//#define STBI_MALLOC(sz) malloc(sz)
//#define STBI_REALLOC(p,newsz) realloc(p,newsz)
//#define STBI_FREE(p) free(p)
#include "stb_image.h"
bool revTexture::LoadFromFile(revDevice* device, const char* path)
{
// Load Texture Data
revString resourcePath(RESOURCE_PATH);
resourcePath += path;
File file;
if (!file.Open(resourcePath.c_str(), FileMode::ReadBinary)) {
NATIVE_LOGE("failed to open texture : %s", resourcePath.c_str());
return false;
}
// Load Meta Data
char metaPath[MAX_META_PATH_LENGTH];
MakeMetaPath(metaPath, resourcePath.c_str());
#ifdef _DEBUG
// if meta file is not found try to make default meta
File metaFile;
if (!metaFile.Open(metaPath, FileMode::ReadText)) {
NATIVE_LOGI("meta file is not found. create new file : %s", metaPath);
revSerializer::Serialize(metaPath, *this);
}
else metaFile.Close();
#endif
revSerializer::Deserialize(metaPath, *this);
// Load Texture Data
uint32 fileLength = file.GetFileSize();
char* data = new char[fileLength];
file.ReadData(data);
file.Close();
int n;
uint8* imageData = stbi_load_from_memory(reinterpret_cast<uint8*>(data), fileLength, reinterpret_cast<int32*>(&width), reinterpret_cast<int32*>(&height), &n, 4);
if (!CreateTexture(device, imageData)) {
stbi_image_free(imageData);
delete[] data;
return false;
}
stbi_image_free(imageData);
delete[] data;
return true;
}
| 30.509434
| 165
| 0.66543
|
YIMonge
|
617663da4370a123479d40aa1c8dc29a556a7a2c
| 24,594
|
cpp
|
C++
|
Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp
|
ninpo3d/o3de
|
69bd0e85199829643a25f8829a1ae283b1016260
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp
|
ninpo3d/o3de
|
69bd0e85199829643a25f8829a1ae283b1016260
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp
|
ninpo3d/o3de
|
69bd0e85199829643a25f8829a1ae283b1016260
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Atom/RHI.Reflect/ShaderDataMappings.h>
#include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
#include <AzCore/Debug/EventTrace.h>
#include <AtomCore/Instance/InstanceDatabase.h>
namespace AZ
{
namespace RPI
{
const char* ShaderResourceGroup::s_traceCategoryName = "ShaderResourceGroup";
const Data::Instance<Image> ShaderResourceGroup::s_nullImage;
const Data::Instance<Buffer> ShaderResourceGroup::s_nullBuffer;
Data::Instance<ShaderResourceGroup> ShaderResourceGroup::FindOrCreate(const Data::Asset<ShaderResourceGroupAsset>& srgAsset)
{
return Data::InstanceDatabase<ShaderResourceGroup>::Instance().FindOrCreate(
Data::InstanceId::CreateFromAssetId(srgAsset.GetId()),
srgAsset);
}
Data::Instance<ShaderResourceGroup> ShaderResourceGroup::Create(const Data::Asset<ShaderResourceGroupAsset>& srgAsset)
{
return Data::InstanceDatabase<ShaderResourceGroup>::Instance().FindOrCreate(
Data::InstanceId::CreateRandom(),
srgAsset);
}
Data::Instance<ShaderResourceGroup> ShaderResourceGroup::CreateInternal(ShaderResourceGroupAsset& srgAsset)
{
Data::Instance<ShaderResourceGroup> srg = aznew ShaderResourceGroup();
const RHI::ResultCode resultCode = srg->Init(srgAsset);
if (resultCode == RHI::ResultCode::Success)
{
return srg;
}
return nullptr;
}
RHI::ResultCode ShaderResourceGroup::Init(ShaderResourceGroupAsset& shaderResourceGroupAsset)
{
AZ_TRACE_METHOD();
m_layout = shaderResourceGroupAsset.GetLayout();
if (!m_layout)
{
AZ_Assert(false, "ShaderResourceGroup cannot be initialized due to invalid ShaderResourceGroupLayout");
return RHI::ResultCode::Fail;
}
m_pool = ShaderResourceGroupPool::FindOrCreate(AZ::Data::Asset<ShaderResourceGroupAsset>(
&shaderResourceGroupAsset,
AZ::Data::AssetLoadBehavior::PreLoad));
if (!m_pool)
{
return RHI::ResultCode::Fail;
}
m_shaderResourceGroup = m_pool->CreateRHIShaderResourceGroup();
if (!m_shaderResourceGroup)
{
return RHI::ResultCode::Fail;
}
m_shaderResourceGroup->SetName(shaderResourceGroupAsset.GetName());
m_data = RHI::ShaderResourceGroupData(m_layout);
m_asset = { &shaderResourceGroupAsset, AZ::Data::AssetLoadBehavior::PreLoad };
// The RPI groups match the same dimensions as the RHI group.
m_imageGroup.resize(m_layout->GetGroupSizeForImages());
m_bufferGroup.resize(m_layout->GetGroupSizeForBuffers());
return RHI::ResultCode::Success;
}
void ShaderResourceGroup::Compile()
{
m_shaderResourceGroup->Compile(m_data);
}
bool ShaderResourceGroup::IsQueuedForCompile() const
{
return m_shaderResourceGroup->IsQueuedForCompile();
}
RHI::ShaderInputBufferIndex ShaderResourceGroup::FindShaderInputBufferIndex(const Name& name) const
{
return m_layout->FindShaderInputBufferIndex(name);
}
RHI::ShaderInputImageIndex ShaderResourceGroup::FindShaderInputImageIndex(const Name& name) const
{
return m_layout->FindShaderInputImageIndex(name);
}
RHI::ShaderInputSamplerIndex ShaderResourceGroup::FindShaderInputSamplerIndex(const Name& name) const
{
return m_layout->FindShaderInputSamplerIndex(name);
}
RHI::ShaderInputConstantIndex ShaderResourceGroup::FindShaderInputConstantIndex(const Name& name) const
{
return m_layout->FindShaderInputConstantIndex(name);
}
RHI::ShaderInputBufferUnboundedArrayIndex ShaderResourceGroup::FindShaderInputBufferUnboundedArrayIndex(const Name& name) const
{
return m_layout->FindShaderInputBufferUnboundedArrayIndex(name);
}
RHI::ShaderInputImageUnboundedArrayIndex ShaderResourceGroup::FindShaderInputImageUnboundedArrayIndex(const Name& name) const
{
return m_layout->FindShaderInputImageUnboundedArrayIndex(name);
}
const Data::Asset<ShaderResourceGroupAsset>& ShaderResourceGroup::GetAsset() const
{
return m_asset;
}
const RHI::ShaderResourceGroupLayout* ShaderResourceGroup::GetLayout() const
{
return m_layout;
}
RHI::ShaderResourceGroup* ShaderResourceGroup::GetRHIShaderResourceGroup()
{
return m_shaderResourceGroup.get();
}
bool ShaderResourceGroup::SetShaderVariantKeyFallbackValue(const ShaderVariantKey& shaderKey)
{
uint32_t keySize = GetLayout()->GetShaderVariantKeyFallbackSize();
if (keySize == 0)
{
return false;
}
auto shaderFallbackIndex = GetLayout()->GetShaderVariantKeyFallbackConstantIndex();
if (!shaderFallbackIndex.IsValid())
{
return false;
}
return SetConstantRaw(shaderFallbackIndex, shaderKey.data(), 0, AZStd::min(keySize, (uint32_t) ShaderVariantKeyBitCount) / 8);
}
bool ShaderResourceGroup::HasShaderVariantKeyFallbackEntry() const
{
return GetLayout()->HasShaderVariantKeyFallbackEntry();
}
bool ShaderResourceGroup::SetImage(RHI::ShaderInputNameIndex& inputIndex, const Data::Instance<Image>& image, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return SetImage(inputIndex.GetImageIndex(), image, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetImage(RHI::ShaderInputImageIndex inputIndex, const Data::Instance<Image>& image, uint32_t arrayIndex)
{
const RHI::ImageView* imageView = image ? image->GetImageView() : nullptr;
if (m_data.SetImageView(inputIndex, imageView, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
// Track the RPI image entry at the same slot.
m_imageGroup[interval.m_min + arrayIndex] = image;
return true;
}
return false;
}
bool ShaderResourceGroup::SetImageArray(RHI::ShaderInputNameIndex& inputIndex, AZStd::array_view<Data::Instance<Image>> images, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return SetImageArray(inputIndex.GetImageIndex(), images, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetImageArray(RHI::ShaderInputImageIndex inputIndex, AZStd::array_view<Data::Instance<Image>> images, uint32_t arrayIndex)
{
if (GetLayout()->ValidateAccess(inputIndex, arrayIndex + static_cast<uint32_t>(images.size()) - 1))
{
bool isValidAll = true;
for (size_t i = 0; i < images.size(); ++i)
{
isValidAll &= SetImage(inputIndex, images[i], static_cast<uint32_t>(arrayIndex + i));
}
return isValidAll;
}
return false;
}
const Data::Instance<Image>& ShaderResourceGroup::GetImage(RHI::ShaderInputNameIndex& inputIndex, uint32_t arrayIndex) const
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return GetImage(inputIndex.GetImageIndex(), arrayIndex);
}
return s_nullImage;
}
const Data::Instance<Image>& ShaderResourceGroup::GetImage(RHI::ShaderInputImageIndex inputIndex, uint32_t arrayIndex) const
{
if (m_layout->ValidateAccess(inputIndex, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
return m_imageGroup[interval.m_min + arrayIndex];
}
return s_nullImage;
}
AZStd::array_view<Data::Instance<Image>> ShaderResourceGroup::GetImageArray(RHI::ShaderInputNameIndex& inputIndex) const
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return GetImageArray(inputIndex.GetImageIndex());
}
return {};
}
AZStd::array_view<Data::Instance<Image>> ShaderResourceGroup::GetImageArray(RHI::ShaderInputImageIndex inputIndex) const
{
if (m_layout->ValidateAccess(inputIndex, 0))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
return AZStd::array_view<Data::Instance<Image>>(&m_imageGroup[interval.m_min], interval.m_max - interval.m_min);
}
return {};
}
bool ShaderResourceGroup::SetImageView(RHI::ShaderInputNameIndex& inputIndex, const RHI::ImageView* imageView, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return SetImageView(inputIndex.GetImageIndex(), imageView, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetImageView(RHI::ShaderInputImageIndex inputIndex, const RHI::ImageView* imageView, uint32_t arrayIndex)
{
if (m_data.SetImageView(inputIndex, imageView, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
// Reset the RPI image entry, since an RHI version now takes precedence.
m_imageGroup[interval.m_min + arrayIndex] = nullptr;
return true;
}
return false;
}
bool ShaderResourceGroup::SetImageViewArray(RHI::ShaderInputNameIndex& inputIndex, AZStd::array_view<const RHI::ImageView*> imageViews, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindImageIndex(GetLayout()))
{
return SetImageViewArray(inputIndex.GetImageIndex(), imageViews, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetImageViewArray(RHI::ShaderInputImageIndex inputIndex, AZStd::array_view<const RHI::ImageView*> imageViews, uint32_t arrayIndex)
{
if (GetLayout()->ValidateAccess(inputIndex, arrayIndex + static_cast<uint32_t>(imageViews.size()) - 1))
{
bool isValidAll = true;
for (size_t i = 0; i < imageViews.size(); ++i)
{
isValidAll &= SetImageView(inputIndex, imageViews[i], static_cast<uint32_t>(arrayIndex + i));
}
return isValidAll;
}
return false;
}
bool ShaderResourceGroup::SetImageViewUnboundedArray(RHI::ShaderInputImageUnboundedArrayIndex inputIndex, AZStd::array_view<const RHI::ImageView*> imageViews)
{
return m_data.SetImageViewUnboundedArray(inputIndex, imageViews);
}
bool ShaderResourceGroup::SetBufferView(RHI::ShaderInputNameIndex& inputIndex, const RHI::BufferView* bufferView, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return SetBufferView(inputIndex.GetBufferIndex(), bufferView, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetBufferView(RHI::ShaderInputBufferIndex inputIndex, const RHI::BufferView* bufferView, uint32_t arrayIndex)
{
if (m_data.SetBufferView(inputIndex, bufferView, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
// Reset the RPI image entry, since an RHI version now takes precedence.
m_bufferGroup[interval.m_min + arrayIndex] = nullptr;
return true;
}
return false;
}
bool ShaderResourceGroup::SetBufferViewArray(RHI::ShaderInputNameIndex& inputIndex, AZStd::array_view<const RHI::BufferView*> bufferViews, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return SetBufferViewArray(inputIndex.GetBufferIndex(), bufferViews, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetBufferViewArray(RHI::ShaderInputBufferIndex inputIndex, AZStd::array_view<const RHI::BufferView*> bufferViews, uint32_t arrayIndex)
{
if (GetLayout()->ValidateAccess(inputIndex, arrayIndex + static_cast<uint32_t>(bufferViews.size()) - 1))
{
bool isValidAll = true;
for (size_t i = 0; i < bufferViews.size(); ++i)
{
isValidAll &= SetBufferView(inputIndex, bufferViews[i], static_cast<uint32_t>(arrayIndex + i));
}
return isValidAll;
}
return false;
}
bool ShaderResourceGroup::SetBufferViewUnboundedArray(RHI::ShaderInputBufferUnboundedArrayIndex inputIndex, AZStd::array_view<const RHI::BufferView*> bufferViews)
{
return m_data.SetBufferViewUnboundedArray(inputIndex, bufferViews);
}
bool ShaderResourceGroup::SetSampler(RHI::ShaderInputNameIndex& inputIndex, const RHI::SamplerState& sampler, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindSamplerIndex(GetLayout()))
{
return SetSampler(inputIndex.GetSamplerIndex(), sampler, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetSampler(RHI::ShaderInputSamplerIndex inputIndex, const RHI::SamplerState& sampler, uint32_t arrayIndex)
{
return m_data.SetSampler(inputIndex, sampler, arrayIndex);
}
bool ShaderResourceGroup::SetSamplerArray(RHI::ShaderInputNameIndex& inputIndex, AZStd::array_view<RHI::SamplerState> samplers, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindSamplerIndex(GetLayout()))
{
return SetSamplerArray(inputIndex.GetSamplerIndex(), samplers, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetSamplerArray(RHI::ShaderInputSamplerIndex inputIndex, AZStd::array_view<RHI::SamplerState> samplers, uint32_t arrayIndex)
{
return m_data.SetSamplerArray(inputIndex, samplers, arrayIndex);
}
bool ShaderResourceGroup::SetConstantRaw(RHI::ShaderInputNameIndex& inputIndex, const void* bytes, uint32_t byteCount)
{
if (inputIndex.ValidateOrFindConstantIndex(GetLayout()))
{
return SetConstantRaw(inputIndex.GetConstantIndex(), bytes, byteCount);
}
return false;
}
bool ShaderResourceGroup::SetConstantRaw(RHI::ShaderInputConstantIndex inputIndex, const void* bytes, uint32_t byteCount)
{
return m_data.SetConstantRaw(inputIndex, bytes, byteCount);
}
bool ShaderResourceGroup::SetConstantRaw(RHI::ShaderInputNameIndex& inputIndex, const void* bytes, uint32_t byteOffset, uint32_t byteCount)
{
if (inputIndex.ValidateOrFindConstantIndex(GetLayout()))
{
return SetConstantRaw(inputIndex.GetConstantIndex(), bytes, byteOffset, byteCount);
}
return false;
}
bool ShaderResourceGroup::SetConstantRaw(RHI::ShaderInputConstantIndex inputIndex, const void* bytes, uint32_t byteOffset, uint32_t byteCount)
{
return m_data.SetConstantRaw(inputIndex, bytes, byteOffset, byteCount);
}
bool ShaderResourceGroup::ApplyDataMappings(const RHI::ShaderDataMappings& mappings)
{
bool success = true;
success = success && ApplyDataMappingArray(mappings.m_colorMappings);
success = success && ApplyDataMappingArray(mappings.m_uintMappings);
success = success && ApplyDataMappingArray(mappings.m_floatMappings);
success = success && ApplyDataMappingArray(mappings.m_float2Mappings);
success = success && ApplyDataMappingArray(mappings.m_float3Mappings);
success = success && ApplyDataMappingArray(mappings.m_float4Mappings);
success = success && ApplyDataMappingArray(mappings.m_matrix3x3Mappings);
success = success && ApplyDataMappingArray(mappings.m_matrix4x4Mappings);
return success;
}
const RHI::ConstPtr<RHI::ImageView>& ShaderResourceGroup::GetImageView(RHI::ShaderInputNameIndex& inputIndex, uint32_t arrayIndex) const
{
inputIndex.ValidateOrFindImageIndex(GetLayout());
return GetImageView(inputIndex.GetImageIndex(), arrayIndex);
}
const RHI::ConstPtr<RHI::ImageView>& ShaderResourceGroup::GetImageView(RHI::ShaderInputImageIndex inputIndex, uint32_t arrayIndex) const
{
return m_data.GetImageView(inputIndex, arrayIndex);
}
AZStd::array_view<RHI::ConstPtr<RHI::ImageView>> ShaderResourceGroup::GetImageViewArray(RHI::ShaderInputNameIndex& inputIndex) const
{
inputIndex.ValidateOrFindImageIndex(GetLayout());
return GetImageViewArray(inputIndex.GetImageIndex());
}
AZStd::array_view<RHI::ConstPtr<RHI::ImageView>> ShaderResourceGroup::GetImageViewArray(RHI::ShaderInputImageIndex inputIndex) const
{
return m_data.GetImageViewArray(inputIndex);
}
const RHI::ConstPtr<RHI::BufferView>& ShaderResourceGroup::GetBufferView(RHI::ShaderInputNameIndex& inputIndex, uint32_t arrayIndex) const
{
inputIndex.ValidateOrFindBufferIndex(GetLayout());
return GetBufferView(inputIndex.GetBufferIndex(), arrayIndex);
}
const RHI::ConstPtr<RHI::BufferView>& ShaderResourceGroup::GetBufferView(RHI::ShaderInputBufferIndex inputIndex, uint32_t arrayIndex) const
{
return m_data.GetBufferView(inputIndex, arrayIndex);
}
AZStd::array_view<RHI::ConstPtr<RHI::BufferView>> ShaderResourceGroup::GetBufferViewArray(RHI::ShaderInputNameIndex& inputIndex) const
{
inputIndex.ValidateOrFindBufferIndex(GetLayout());
return GetBufferViewArray(inputIndex.GetBufferIndex());
}
AZStd::array_view<RHI::ConstPtr<RHI::BufferView>> ShaderResourceGroup::GetBufferViewArray(RHI::ShaderInputBufferIndex inputIndex) const
{
return m_data.GetBufferViewArray(inputIndex);
}
bool ShaderResourceGroup::SetBuffer(RHI::ShaderInputNameIndex& inputIndex, const Data::Instance<Buffer>& buffer, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return SetBuffer(inputIndex.GetBufferIndex(), buffer, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetBuffer(RHI::ShaderInputBufferIndex inputIndex, const Data::Instance<Buffer>& buffer, uint32_t arrayIndex)
{
const RHI::BufferView* bufferView = buffer ? buffer->GetBufferView() : nullptr;
if (m_data.SetBufferView(inputIndex, bufferView, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
// Track the RPI buffer entry at the same slot.
m_bufferGroup[interval.m_min + arrayIndex] = buffer;
return true;
}
return false;
}
bool ShaderResourceGroup::SetBufferArray(RHI::ShaderInputNameIndex& inputIndex, AZStd::array_view<Data::Instance<Buffer>> buffers, uint32_t arrayIndex)
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return SetBufferArray(inputIndex.GetBufferIndex(), buffers, arrayIndex);
}
return false;
}
bool ShaderResourceGroup::SetBufferArray(RHI::ShaderInputBufferIndex inputIndex, AZStd::array_view<Data::Instance<Buffer>> buffers, uint32_t arrayIndex)
{
if (GetLayout()->ValidateAccess(inputIndex, arrayIndex + static_cast<uint32_t>(buffers.size()) - 1))
{
bool isValidAll = true;
for (size_t i = 0; i < buffers.size(); ++i)
{
isValidAll &= SetBuffer(inputIndex, buffers[i], static_cast<uint32_t>(arrayIndex + i));
}
return isValidAll;
}
return false;
}
const Data::Instance<Buffer>& ShaderResourceGroup::GetBuffer(RHI::ShaderInputNameIndex& inputIndex, uint32_t arrayIndex) const
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return GetBuffer(inputIndex.GetBufferIndex(), arrayIndex);
}
return s_nullBuffer;
}
const Data::Instance<Buffer>& ShaderResourceGroup::GetBuffer(RHI::ShaderInputBufferIndex inputIndex, uint32_t arrayIndex) const
{
if (m_layout->ValidateAccess(inputIndex, arrayIndex))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
return m_bufferGroup[interval.m_min + arrayIndex];
}
return s_nullBuffer;
}
AZStd::array_view<Data::Instance<Buffer>> ShaderResourceGroup::GetBufferArray(RHI::ShaderInputNameIndex& inputIndex) const
{
if (inputIndex.ValidateOrFindBufferIndex(GetLayout()))
{
return GetBufferArray(inputIndex.GetBufferIndex());
}
return {};
}
AZStd::array_view<Data::Instance<Buffer>> ShaderResourceGroup::GetBufferArray(RHI::ShaderInputBufferIndex inputIndex) const
{
if (m_layout->ValidateAccess(inputIndex, 0))
{
const RHI::Interval interval = m_layout->GetGroupInterval(inputIndex);
return AZStd::array_view<Data::Instance<Buffer>>(&m_bufferGroup[interval.m_min], interval.m_max - interval.m_min);
}
return {};
}
const RHI::SamplerState& ShaderResourceGroup::GetSampler(RHI::ShaderInputNameIndex& inputIndex, uint32_t arrayIndex) const
{
inputIndex.ValidateOrFindSamplerIndex(GetLayout());
return GetSampler(inputIndex.GetSamplerIndex(), arrayIndex);
}
const RHI::SamplerState& ShaderResourceGroup::GetSampler(RHI::ShaderInputSamplerIndex inputIndex, uint32_t arrayIndex) const
{
return m_data.GetSampler(inputIndex, arrayIndex);
}
AZStd::array_view<RHI::SamplerState> ShaderResourceGroup::GetSamplerArray(RHI::ShaderInputNameIndex& inputIndex) const
{
inputIndex.ValidateOrFindSamplerIndex(GetLayout());
return GetSamplerArray(inputIndex.GetSamplerIndex());
}
AZStd::array_view<RHI::SamplerState> ShaderResourceGroup::GetSamplerArray(RHI::ShaderInputSamplerIndex inputIndex) const
{
return m_data.GetSamplerArray(inputIndex);
}
AZStd::array_view<uint8_t> ShaderResourceGroup::GetConstantRaw(RHI::ShaderInputNameIndex& inputIndex) const
{
inputIndex.ValidateOrFindConstantIndex(GetLayout());
return GetConstantRaw(inputIndex.GetConstantIndex());
}
AZStd::array_view<uint8_t> ShaderResourceGroup::GetConstantRaw(RHI::ShaderInputConstantIndex inputIndex) const
{
return m_data.GetConstantRaw(inputIndex);
}
} // namespace RPI
} // namespace AZ
| 41.684746
| 170
| 0.634342
|
ninpo3d
|
6177da275c2e79b272694b9899c5903627444f73
| 5,002
|
cc
|
C++
|
1Layer/Systolic_sim/src/graphdata.cc
|
guohaoqiang/wegnn
|
9452f1b051a057a054d436e99610d766e6ed63fb
|
[
"MIT"
] | null | null | null |
1Layer/Systolic_sim/src/graphdata.cc
|
guohaoqiang/wegnn
|
9452f1b051a057a054d436e99610d766e6ed63fb
|
[
"MIT"
] | null | null | null |
1Layer/Systolic_sim/src/graphdata.cc
|
guohaoqiang/wegnn
|
9452f1b051a057a054d436e99610d766e6ed63fb
|
[
"MIT"
] | null | null | null |
#include "../include/graphdata.h"
void Graph::node_sort(const std::vector<std::vector<int>>& in){
int in_counts = 0;
for(size_t it=1;it<in.at(0).size();++it){
//LOG(INFO) << "it = "<<it<<std::endl;
int key = in.at(0).at(it) - in.at(0).at(it-1);
//push back rowID
auto pt = pre_sort_data.insert({key,std::vector<int>(1,it-1)});
for(size_t j=0;j<key;++j){
(*pt).second.push_back(in.at(1).at(in_counts+j));
}
in_counts += key;
//LOG(INFO) << "in_counts = "<<in_counts<<std::endl;
}
//copy to sorted_data
sorted_data.at(0).push_back(0);
int base = 0;
for(auto it:pre_sort_data){
base += it.first+1;
sorted_data.at(0).push_back(base);
std::sort(it.second.begin(),it.second.end());
for(auto ele:it.second)
sorted_data.at(1).push_back(ele);
}
}
Graph::Graph(const std::string& name):data(2,std::vector<int>()),\
sorted_data(2,std::vector<int>()),\
csr_diag(2,std::vector<int>()){
this->data_path = name.substr(0,name.find_last_of("\/"));
this->name = name.substr(name.find_last_of("\/")+1,-1);
//std::cout<<this->name<<std::endl;
//this->name = name;
//this->data = {{},{}};
//this->data.resize(2,std::vector<int>());
this->feature_size = feature_dim[this->name];
//this->feature_size = 16;
//this->hiden = output_dim[this->name];
this->hiden = 16;
this->load_adj(this->name);
this->nodes = data[0].size()-1;
node_sort(this->data);
csr_diag.at(0).push_back(0);
int base = 0;
int num = 0;
for(size_t i=1;i<this->data.at(0).size();++i){
//VLOG(2)<<"i = "<<i;
//VLOG(2)<<"base = "<<base;
//VLOG(2)<<"# = "<<this->data.at(0).at(i)-this->data.at(0).at(i-1);
csr_diag.at(1).push_back(i-1);
num = this->data.at(0).at(i)-this->data.at(0).at(i-1);
if(num > this->max_num)
this->max_num = num;
for(size_t j=base;j<base+this->data.at(0).at(i)-this->data.at(0).at(i-1);++j){
csr_diag.at(1).push_back(this->data.at(1).at(j));
// VLOG(2)<<"this->data.at(1).at("<<j<<") = "<<this->data.at(1).at(j);
}
std::sort(csr_diag.at(1).begin()+base+i-1,csr_diag.at(1).begin()+base+i-1+this->data.at(0).at(i)-this->data.at(0).at(i-1)+1);
base += this->data.at(0).at(i)-this->data.at(0).at(i-1);
csr_diag.at(0).push_back(base+i);
}
this->max_num += 1;
// print_data();
}
void Graph::load_adj(const std::string& name){
std::fstream fin;
fin.open(this->data_path+"\/"+"n_"+name+".csv",std::ios::in);
//std::cout<<this->data_path<<std::endl;
//std::cout<<name<<std::endl;
//std::cout<<this->data_path+"\/"+"n_"+name+".csv"<<std::endl;
std::string line, word;
int i = 0;
while(i<2){
std::getline(fin,line);
std::stringstream ss(line);
while(std::getline(ss,word,',')){
data.at(i).push_back(std::stoi(word));
}
i++;
}
fin.close();
}
std::string Graph::get_name(){
return this->name;
}
int Graph::get_nodes(){
return nodes;
}
int Graph::get_feature_size(){
return feature_size;
}
void Graph::print_data(){
std::cout<<"The first 5 elements of rowptr: ";
for(auto it=data[0].begin(); it<data[0].begin()+5 ; it++)
std::cout<<(*it)<<" ";
std::cout<<std::endl;
std::cout<<"The last 5 elements of rowptr: ";
for(auto it=data[0].end()-5; it!=data[0].end() ; it++)
std::cout<<(*it)<<" ";
std::cout<<std::endl;
std::cout<<"The first 5 elements of indies: ";
for(auto it=data[1].begin(); it<data[1].begin()+5 ; it++)
std::cout<<(*it)<<" ";
std::cout<<std::endl;
std::cout<<"The last 5 elements of indies: ";
for(auto it=data[1].end()-5; it!=data[1].end() ; it++)
std::cout<<(*it)<<" ";
std::cout<<std::endl;
std::cout<<"pre_sort_data: "<<std::endl;
for(auto it:pre_sort_data){
std::cout<<it.first<<": ";
for(auto loc:it.second)
std::cout<<loc<<" ";
std::cout<<std::endl;
}
std::cout<<std::endl;
std::cout<<"sorted_data: "<<std::endl;
for(auto it:sorted_data){
for(auto loc:it)
std::cout<<loc<<" ";
std::cout<<std::endl;
}
std::cout<<"csr_diag: "<<std::endl;
for(auto it:csr_diag){
for(auto loc:it)
std::cout<<loc<<" ";
std::cout<<std::endl;
}
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"Graph name: "<<get_name()<<std::endl;
std::cout<<"The number of nodes: "<< get_nodes()<<" Rowptr: "<<data.at(0).size()<<" Pointer: "<<data.at(1).size()<<std::endl;
std::cout<<"The size of a node feature: "<<get_feature_size()<<std::endl;
}
| 33.57047
| 133
| 0.513395
|
guohaoqiang
|
6179f1b525ebc4542bcd7804ab61304bca156689
| 1,034
|
cpp
|
C++
|
philibs/scene/sceneframebuffer.cpp
|
prwhite/philibs
|
3cb65bd0dae105026839a3e88d9cebafb72c2616
|
[
"Zlib"
] | 5
|
2015-05-12T14:48:03.000Z
|
2021-07-14T13:18:16.000Z
|
philibs/scene/sceneframebuffer.cpp
|
prwhite/philibs
|
3cb65bd0dae105026839a3e88d9cebafb72c2616
|
[
"Zlib"
] | null | null | null |
philibs/scene/sceneframebuffer.cpp
|
prwhite/philibs
|
3cb65bd0dae105026839a3e88d9cebafb72c2616
|
[
"Zlib"
] | 1
|
2021-04-18T07:32:43.000Z
|
2021-04-18T07:32:43.000Z
|
/////////////////////////////////////////////////////////////////////
//
// file: sceneframebuffer.cpp
//
/////////////////////////////////////////////////////////////////////
#include "sceneframebuffer.h"
/////////////////////////////////////////////////////////////////////
namespace scene {
/////////////////////////////////////////////////////////////////////
//framebuffer::framebuffer()
//{
//
//}
//
//framebuffer::~framebuffer()
//{
//
//}
//
//framebuffer::framebuffer(framebuffer const& rhs)
//{
//
//}
//
//framebuffer& framebuffer::operator=(framebuffer const& rhs)
//{
//
// return *this;
//}
//
//bool framebuffer::operator==(framebuffer const& rhs) const
//{
//
// return false;
//}
/////////////////////////////////////////////////////////////////////
// overrides from pni::pstd::refCount
void framebuffer::collectRefs ( pni::pstd::refCount::Refs& refs ) const
{
mTextureTargets.collectRefs(refs);
}
/////////////////////////////////////////////////////////////////////
} // end of namespace scene
| 18.464286
| 71
| 0.381044
|
prwhite
|
617ae705cd5bc12a419697d99c4850debe156926
| 31,969
|
cpp
|
C++
|
language-extensions/python/test/src/PythonGetResultColumnTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 82
|
2019-05-24T00:36:57.000Z
|
2022-02-21T23:51:46.000Z
|
language-extensions/python/test/src/PythonGetResultColumnTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 20
|
2019-07-05T06:12:28.000Z
|
2022-03-31T20:48:30.000Z
|
language-extensions/python/test/src/PythonGetResultColumnTests.cpp
|
rabryst/sql-server-language-extensions
|
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
|
[
"MIT"
] | 35
|
2019-05-24T01:44:07.000Z
|
2022-02-28T13:29:44.000Z
|
//*************************************************************************************************
// Copyright (C) Microsoft Corporation.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// @File: PythonGetResultColumnTests.cpp
//
// Purpose:
// Tests the Python Extension's implementation of the external language GetResultColumn API.
//
//*************************************************************************************************
#include "PythonExtensionApiTests.h"
using namespace std;
namespace ExtensionApiTest
{
// Name: GetIntegerResultColumnsTest
//
// Description:
// Test GetResultColumn with default script expecting an OutputDataSet of Integer columns.
//
TEST_F(PythonExtensionApiTests, GetIntegerResultColumnsTest)
{
InitializeSession(0, // parametersNumber
(*m_integerInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLINTEGER, SQL_C_SLONG>(m_integerInfo.get());
TestExecute<SQLINTEGER, SQL_C_SLONG>(
ColumnInfo<SQLINTEGER>::sm_rowsNumber,
(*m_integerInfo).m_dataSet.data(),
(*m_integerInfo).m_strLen_or_Ind.data(),
(*m_integerInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_SLONG, // dataType
m_IntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetBooleanResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of Boolean columns.
//
TEST_F(PythonExtensionApiTests, GetBooleanResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_booleanInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLCHAR, SQL_C_BIT>(m_booleanInfo.get());
TestExecute<SQLCHAR, SQL_C_BIT>(
ColumnInfo<SQLCHAR>::sm_rowsNumber,
(*m_booleanInfo).m_dataSet.data(),
(*m_booleanInfo).m_strLen_or_Ind.data(),
(*m_booleanInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_BIT, // dataType
m_BooleanSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // dataType - since there is a NULL, we return SQL_C_CHAR
5, // columnSize - length of the word "False"
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetRealResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of Real columns.
//
TEST_F(PythonExtensionApiTests, GetRealResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_realInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLREAL, SQL_C_FLOAT>(m_realInfo.get());
TestExecute<SQLREAL, SQL_C_FLOAT>(
ColumnInfo<SQLREAL>::sm_rowsNumber,
(*m_realInfo).m_dataSet.data(),
(*m_realInfo).m_strLen_or_Ind.data(),
(*m_realInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_FLOAT, // dataType
m_RealSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetDoubleResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of Double columns.
//
TEST_F(PythonExtensionApiTests, GetDoubleResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_doubleInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLDOUBLE, SQL_C_DOUBLE>(m_doubleInfo.get());
TestExecute<SQLDOUBLE, SQL_C_DOUBLE>(
ColumnInfo<SQLDOUBLE>::sm_rowsNumber,
(*m_doubleInfo).m_dataSet.data(),
(*m_doubleInfo).m_strLen_or_Ind.data(),
(*m_doubleInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetBigIntResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of BigInteger columns.
//
TEST_F(PythonExtensionApiTests, GetBigIntResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_bigIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLBIGINT, SQL_C_SBIGINT>(m_bigIntInfo.get());
TestExecute<SQLBIGINT, SQL_C_SBIGINT>(
ColumnInfo<SQLBIGINT>::sm_rowsNumber,
(*m_bigIntInfo).m_dataSet.data(),
(*m_bigIntInfo).m_strLen_or_Ind.data(),
(*m_bigIntInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_SBIGINT, // dataType
m_BigIntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetSmallIntResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of SmallInt columns.
//
TEST_F(PythonExtensionApiTests, GetSmallIntResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_smallIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLSMALLINT, SQL_C_SSHORT>(m_smallIntInfo.get());
TestExecute<SQLSMALLINT, SQL_C_SSHORT>(
ColumnInfo<SQLSMALLINT>::sm_rowsNumber,
(*m_smallIntInfo).m_dataSet.data(),
(*m_smallIntInfo).m_strLen_or_Ind.data(),
(*m_smallIntInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_SSHORT, // dataType
m_SmallIntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetTinyIntResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of TinyInt columns.
//
TEST_F(PythonExtensionApiTests, GetTinyIntResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_tinyIntInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQLCHAR, SQL_C_UTINYINT>(m_tinyIntInfo.get());
TestExecute<SQLCHAR, SQL_C_UTINYINT>(
ColumnInfo<SQLCHAR>::sm_rowsNumber,
(*m_tinyIntInfo).m_dataSet.data(),
(*m_tinyIntInfo).m_strLen_or_Ind.data(),
(*m_tinyIntInfo).m_columnNames,
false); // validate
TestGetResultColumn(0, // columnNumber
SQL_C_UTINYINT, // dataType
m_TinyIntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetStringResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of String columns.
//
TEST_F(PythonExtensionApiTests, GetStringResultColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string stringColumn1Name = "StringColumn1";
InitializeColumn(0, stringColumn1Name, SQL_C_CHAR, m_CharSize);
string stringColumn2Name = "StringColumn2";
InitializeColumn(1, stringColumn2Name, SQL_C_CHAR, m_CharSize);
string stringColumn3Name = "StringColumn3";
InitializeColumn(2, stringColumn3Name, SQL_C_CHAR, m_CharSize);
vector<const char *> stringCol1{ "Hello", "test", "data", "World", "-123" };
vector<const char *> stringCol2{ "", 0, nullptr, "verify", "-1" };
vector<SQLINTEGER> strLenOrIndCol1 =
{ static_cast<SQLINTEGER>(strlen(stringCol1[0])),
static_cast<SQLINTEGER>(strlen(stringCol1[1])),
static_cast<SQLINTEGER>(strlen(stringCol1[2])),
static_cast<SQLINTEGER>(strlen(stringCol1[3])),
static_cast<SQLINTEGER>(strlen(stringCol1[4])) };
vector<SQLINTEGER> strLenOrIndCol2 =
{ 0, SQL_NULL_DATA, SQL_NULL_DATA,
static_cast<SQLINTEGER>(strlen(stringCol2[3])),
static_cast<SQLINTEGER>(strlen(stringCol2[4])) };
vector<SQLINTEGER *> strLen_or_Ind{ strLenOrIndCol1.data(),
strLenOrIndCol2.data(), nullptr };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
vector<char> stringCol1Data = GenerateContiguousData<char>(stringCol1, strLenOrIndCol1.data());
vector<char> stringCol2Data = GenerateContiguousData<char>(stringCol2, strLenOrIndCol2.data());
void *dataSet[] = { stringCol1Data.data(),
stringCol2Data.data(),
nullptr };
int rowsNumber = stringCol1.size();
vector<string> columnNames{ stringColumn1Name, stringColumn2Name, stringColumn3Name };
TestExecute<SQLCHAR, SQL_C_CHAR>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames,
false); // validate
SQLULEN maxCol1Len = GetMaxLength(strLenOrIndCol1.data(), rowsNumber);
SQLULEN maxCol2Len = GetMaxLength(strLenOrIndCol2.data(), rowsNumber);
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // dataType
maxCol1Len, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // dataType
maxCol2Len, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
TestGetResultColumn(2, // columnNumber
SQL_C_CHAR, // dataType
sizeof(SQLCHAR), // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetWStringResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of wstring columns.
//
TEST_F(PythonExtensionApiTests, GetWStringResultColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string wstringColumn1Name = "WstringColumn1";
InitializeColumn(0, wstringColumn1Name, SQL_C_WCHAR, m_CharSize);
string wstringColumn2Name = "WstringColumn2";
InitializeColumn(1, wstringColumn2Name, SQL_C_WCHAR, m_CharSize);
string wstringColumn3Name = "WstringColumn3";
InitializeColumn(2, wstringColumn3Name, SQL_C_WCHAR, m_CharSize);
vector<const wchar_t *> wstringCol1{ L"Hello", L"test", L"data", L"World", L"你" };
vector<const wchar_t *> wstringCol2{ L"", 0, nullptr, L"verify", L"-1" };
int rowsNumber = wstringCol1.size();
vector<SQLINTEGER> strLenOrIndCol1 =
{ static_cast<SQLINTEGER>(5 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(4 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(4 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(5 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(1 * sizeof(wchar_t)) };
vector<SQLINTEGER> strLenOrIndCol2 =
{ 0, SQL_NULL_DATA, SQL_NULL_DATA,
static_cast<SQLINTEGER>(6 * sizeof(wchar_t)),
static_cast<SQLINTEGER>(2 * sizeof(wchar_t)) };
vector<SQLINTEGER> strLenOrIndCol3(rowsNumber, SQL_NULL_DATA);
vector<SQLINTEGER *> strLen_or_Ind{ strLenOrIndCol1.data(),
strLenOrIndCol2.data(), strLenOrIndCol3.data() };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
vector<wchar_t> wstringCol1Data =
GenerateContiguousData<wchar_t>(wstringCol1, strLenOrIndCol1.data());
vector<wchar_t> wstringCol2Data =
GenerateContiguousData<wchar_t>(wstringCol2, strLenOrIndCol2.data());
void *dataSet[] = { wstringCol1Data.data(),
wstringCol2Data.data(),
nullptr };
vector<string> columnNames{ wstringColumn1Name, wstringColumn2Name, wstringColumn3Name };
TestExecute<wchar_t, SQL_C_WCHAR>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames,
false); // validate
// Because Python is UTF-8, we always return UTF-8 strings.
// Thus, we expect output result columns to be strings, not wstrings, so we need to resize
// our expected column size by dividing by the sizeof(wchar_t).
//
SQLULEN maxCol1Len = GetMaxLength(strLenOrIndCol1.data(), rowsNumber) / sizeof(wchar_t);
SQLULEN maxCol2Len = GetMaxLength(strLenOrIndCol2.data(), rowsNumber) / sizeof(wchar_t);
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // expectedDataType
maxCol1Len, // expectedColumnSize
0, // expectedDecimalDigits
SQL_NO_NULLS); // expectedNullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // expectedDataType
maxCol2Len, // expectedColumnSize
0, // expectedDecimalDigits
SQL_NULLABLE); // expectedNullable
TestGetResultColumn(2, // columnNumber
SQL_C_CHAR, // expectedDataType
sizeof(SQLCHAR), // expectedColumnSize
0, // expectedDecimalDigits
SQL_NULLABLE); // expectedNullable
}
// Name: GetRawResultColumnTest
//
// Description:
// Test GetResultColumn with a script that returns OutputDataSet with raw columns.
//
TEST_F(PythonExtensionApiTests, GetRawResultColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
const SQLCHAR BinaryValue1[] = { 0x01, 0x01, 0xe2, 0x40 };
const SQLCHAR BinaryValue2[] = { 0x04, 0x05, 0xe1 };
const SQLCHAR BinaryValue3[] = { 0x00, 0x00, 0x00, 0x01 };
const SQLCHAR BinaryValue4[] = { 0xff };
const SQLCHAR BinaryValue5[] = { 0x00 };
const SQLCHAR BinaryValue6[] = { 0xff, 0xff, 0xff, 0xff };
const SQLCHAR BinaryValue7[] = { 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff };
string binaryColumn1Name = "BinaryColumn1";
InitializeColumn(0, binaryColumn1Name, SQL_C_BINARY, m_BinarySize);
string binaryColumn2Name = "BinaryColumn2";
InitializeColumn(1, binaryColumn2Name, SQL_C_BINARY, m_BinarySize);
string binaryColumn3Name = "BinaryColumn3";
InitializeColumn(2, binaryColumn3Name, SQL_C_BINARY, m_BinarySize);
vector<const SQLCHAR*> binaryCol1{ BinaryValue1, BinaryValue2, BinaryValue3, BinaryValue4 };
vector<const SQLCHAR*> binaryCol2{ BinaryValue5, BinaryValue6, nullptr, BinaryValue7 };
SQLINTEGER strLenOrIndCol1[] =
{
static_cast<SQLINTEGER>(sizeof(BinaryValue1) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue2) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue3) / m_BinarySize),
static_cast<SQLINTEGER>(sizeof(BinaryValue4) / m_BinarySize)
};
SQLINTEGER strLenOrIndCol2[] =
{
SQL_NULL_DATA,
static_cast<SQLINTEGER>(sizeof(BinaryValue6) / m_BinarySize),
SQL_NULL_DATA,
static_cast<SQLINTEGER>(sizeof(BinaryValue7) / m_BinarySize)
};
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, strLenOrIndCol2, nullptr };
// Coalesce the arrays of each row of each column
// into a contiguous array for each column.
//
int rowsNumber = binaryCol1.size();
vector<SQLCHAR> binaryCol1Data = GenerateContiguousData<SQLCHAR>(binaryCol1, strLenOrIndCol1);
vector<SQLCHAR> binaryCol2Data = GenerateContiguousData<SQLCHAR>(binaryCol2, strLenOrIndCol2);
void* dataSet[] = { binaryCol1Data.data(),
binaryCol2Data.data(),
nullptr };
vector<string> columnNames{ binaryColumn1Name, binaryColumn2Name, binaryColumn3Name };
SQLULEN maxCol1Len = GetMaxLength(strLenOrIndCol1, rowsNumber);
SQLULEN maxCol2Len = GetMaxLength(strLenOrIndCol2, rowsNumber);
TestExecute<SQLCHAR, SQL_C_BINARY>(
rowsNumber,
dataSet,
strLen_or_Ind.data(),
columnNames,
false);
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // dataType
maxCol1Len, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // dataType
maxCol2Len, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
TestGetResultColumn(2, // columnNumber
SQL_C_CHAR, // dataType
sizeof(SQLCHAR), // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: GetDateTimeResultColumnsTest
//
// Description:
// Test GetResultColumn with default script expecting an OutputDataSet of DateTime columns.
//
TEST_F(PythonExtensionApiTests, GetDateTimeResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_dateTimeInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>(m_dateTimeInfo.get());
TestExecute<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>(
ColumnInfo<SQL_TIMESTAMP_STRUCT>::sm_rowsNumber,
(*m_dateTimeInfo).m_dataSet.data(),
(*m_dateTimeInfo).m_strLen_or_Ind.data(),
(*m_dateTimeInfo).m_columnNames,
false);
// datetimes are stored in python as an object column which is return as SQL_C_CHAR
// A datetime like "9021-08-25 19:11:40.123456" has 26 chars
//
SQLSMALLINT sizeOfDateTimeString = 26;
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // expectedDataType
sizeOfDateTimeString, // expectedColumnSize
0, // expectedDecimalDigits
SQL_NO_NULLS); // expectedNullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // expectedDataType
sizeOfDateTimeString, // expectedColumnSize
0, // expectedDecimalDigits
SQL_NULLABLE); // expectedNullable
}
// Name: GetDateResultColumnsTest
//
// Description:
// Test GetResultColumn with default script expecting an OutputDataSet of Date columns.
//
TEST_F(PythonExtensionApiTests, GetDateResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
(*m_dateInfo).GetColumnsNumber(),
m_scriptString);
InitializeColumns<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>(m_dateInfo.get());
TestExecute<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>(
ColumnInfo<SQL_DATE_STRUCT>::sm_rowsNumber,
(*m_dateInfo).m_dataSet.data(),
(*m_dateInfo).m_strLen_or_Ind.data(),
(*m_dateInfo).m_columnNames,
false);
// dates are stored in python as an object column which is return as SQL_C_CHAR
// A date like "9021-08-25" has 10 chars
//
SQLSMALLINT sizeOfDateString = 10;
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // expectedDataType
sizeOfDateString, // expectedColumnSize
0, // expectedDeci malDigits
SQL_NO_NULLS); // expectedNullable
TestGetResultColumn(1, // columnNumber
SQL_C_CHAR, // expectedDataType
sizeOfDateString, // expectedColumnSize
0, // expectedDecimalDigits
SQL_NULLABLE); // expectedNullable
}
// Name: GetDifferentResultColumnsTest
//
// Description:
// Test GetResultColumn with default script using an OutputDataSet of different column types.
//
TEST_F(PythonExtensionApiTests, GetDifferentResultColumnsTest)
{
SQLUSMALLINT inputSchemaColumnsNumber = 3;
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(0, // parametersNumber
inputSchemaColumnsNumber,
m_scriptString);
string integerColumnName = "IntegerColumn";
InitializeColumn(0, integerColumnName, SQL_C_SLONG, m_IntSize);
string doubleColumnName = "DoubleColumn";
InitializeColumn(1, doubleColumnName, SQL_C_DOUBLE, m_DoubleSize);
string stringColumnName = "StringColumn";
InitializeColumn(2, stringColumnName, SQL_C_CHAR, m_CharSize);
vector<SQLINTEGER> intColData{ m_MaxInt, m_MinInt, 0, 1320, -1 };
vector<SQLDOUBLE> doubleColData{ m_MinDouble, 1.33, 83.98, 72.45, m_MaxDouble };
vector<const char*> stringCol{ "Hello", "test", "data", "World", "-123" };
const SQLINTEGER intSize = m_IntSize;
SQLINTEGER strLenOrIndCol1[] = { intSize, intSize, SQL_NULL_DATA, SQL_NULL_DATA, intSize };
SQLINTEGER strLenOrIndCol3[] =
{ static_cast<SQLINTEGER>(strlen(stringCol[0])),
static_cast<SQLINTEGER>(strlen(stringCol[1])),
static_cast<SQLINTEGER>(strlen(stringCol[2])),
static_cast<SQLINTEGER>(strlen(stringCol[3])),
static_cast<SQLINTEGER>(strlen(stringCol[4])) };
vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, nullptr, strLenOrIndCol3 };
int rowsNumber = intColData.size();
vector<char> stringColData = GenerateContiguousData<char>(stringCol, strLenOrIndCol3);
vector<void*> dataSet{ intColData.data(), doubleColData.data(), stringColData.data() };
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
rowsNumber,
dataSet.data(),
strLen_or_Ind.data(),
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
// Returns double type because NULLs get changed to NaN
// and column changes to float64
//
TestGetResultColumn(0, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
SQLULEN maxLen = GetMaxLength(strLenOrIndCol3, rowsNumber);
TestGetResultColumn(2, // columnNumber
SQL_C_CHAR, // dataType
maxLen, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
}
// Name: GetEmptyResultColumnTest
//
// Description:
// Test GetResultColumn with a script that returns OutputDataSet with empty rows.
//
TEST_F(PythonExtensionApiTests, GetEmptyResultColumnTest)
{
string scriptString = "from pandas import DataFrame; import numpy as np;"
"OutputDataSet = DataFrame({'intCol' : np.array([], dtype=np.int32)});"
"print(OutputDataSet)";
// Initialize with a Session that executes the above script
// that creates an empty row 1 column OutputDataSet.
//
InitializeSession(0, // parametersNumber
0, // inputSchemaColumnsNumber
scriptString);
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
0,
nullptr,
nullptr,
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
EXPECT_EQ(outputschemaColumnsNumber, 1);
TestGetResultColumn(0, // columnNumber
SQL_C_SLONG, // dataType
m_IntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
}
// Name: MixedColumnNamesTest
//
// Description:
// Test GetResultColumn with a script that returns a dataset with mixed type column names
// i.e. integer and string.
// This makes sure that we can access columns with integer column names.
//
TEST_F(PythonExtensionApiTests, MixedColumnNamesTest)
{
// With this script, we create a DataFrame with unusual column names.
// This tests non-string and mixed type column names.
//
string scriptString = "from pandas import DataFrame;"
"OutputDataSet = DataFrame([['ABC', 123],['DEF', 456]], columns=[3, 'col2']);"
"print(OutputDataSet)";
// Initialize with a Session that executes the above script
// that creates an OutputDataSet with mixed column names.
//
InitializeSession(0, // parametersNumber
0, // inputSchemaColumnsNumber
scriptString);
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
0,
nullptr,
nullptr,
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
EXPECT_EQ(outputschemaColumnsNumber, 2);
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // dataType
3, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_SBIGINT, // dataType
m_BigIntSize, // columnSize
0, // decimalDigits
SQL_NO_NULLS); // nullable
}
//----------------------------------------------------------------------------------------------
// Name: GetStreamIntegerResultColumnsTest
//
// Description:
// Tests GetResultColumn with default script expecting an OutputDataSet of Integer columns.
// When `r_rowsPerRead` parameter is set (streaming), both nullable and non-nullable
// columns must return as nullable (since in streaming, it is not predictable
// whether the upcoming chunks of data will contain nulls).
//
TEST_F(PythonExtensionApiTests, GetStreamIntegerResultColumnsTest)
{
// Initialize with a default Session that prints Hello PythonExtension
// and assigns InputDataSet to OutputDataSet
//
InitializeSession(1, // parametersNumber
(*m_integerInfo).GetColumnsNumber(),
m_scriptString);
// Initialize @r_rowsPerRead input param which sets session as streaming mode
//
SQLCHAR *paramName = static_cast<SQLCHAR *>(
static_cast<void *>(const_cast<char *>(m_streamingParamName.c_str())));
// chunk size, # of rows per chunk
//
SQLINTEGER paramValue = 1;
SQLRETURN result = SQL_ERROR;
result = InitParam(
*m_sessionId,
m_taskId,
0,
paramName, // paramName
m_streamingParamName.length(), // paramSize
SQL_C_SLONG, // dataType
sizeof(SQLINTEGER), // size of dataType
0, // decimalDigits
¶mValue, // chunkSize (@r_rowsPerRead)
0, // strLenOrInd
SQL_PARAM_INPUT); // input output type
EXPECT_EQ(result, SQL_SUCCESS);
InitializeColumns<SQLINTEGER, SQL_C_SLONG>(m_integerInfo.get());
TestExecute<SQLINTEGER, SQL_C_SLONG>(
ColumnInfo<SQLINTEGER>::sm_rowsNumber,
(*m_bigIntInfo).m_dataSet.data(),
(*m_bigIntInfo).m_strLen_or_Ind.data(),
(*m_bigIntInfo).m_columnNames,
false); // validate
// When streaming, we return a broader type because we don't know if later
// values will have bigger values than those in the first chunk.
//
TestGetResultColumn(0, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
TestGetResultColumn(1, // columnNumber
SQL_C_DOUBLE, // dataType
m_DoubleSize, // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: AllNonesColumnTest
//
// Description:
// Test GetResultColumn with a script that returns a dataset with a column of all Nones.
// We expect the output to be of type CHAR and have the minimum columnSize of 1.
//
TEST_F(PythonExtensionApiTests, AllNonesColumnTest)
{
// With this script, we create a DataFrame with column of Nones.
//
string scriptString = "from pandas import DataFrame;"
"OutputDataSet = DataFrame({'noneColumn': [None, None, None, None, None]});"
"print(OutputDataSet)";
// Initialize with a Session that executes the above script
// that creates an OutputDataSet with column of Nones.
//
InitializeSession(0, // parametersNumber
0, // inputSchemaColumnsNumber
scriptString);
SQLUSMALLINT outputschemaColumnsNumber = 0;
SQLRETURN result = Execute(
*m_sessionId,
m_taskId,
0,
nullptr,
nullptr,
&outputschemaColumnsNumber);
ASSERT_EQ(result, SQL_SUCCESS);
EXPECT_EQ(outputschemaColumnsNumber, 1);
TestGetResultColumn(0, // columnNumber
SQL_C_CHAR, // dataType
sizeof(SQLCHAR), // columnSize
0, // decimalDigits
SQL_NULLABLE); // nullable
}
// Name: TestGetResultColumn
//
// Description:
// Test GetResultColumn to verify the expected result column information is obtained.
//
void PythonExtensionApiTests::TestGetResultColumn(
SQLUSMALLINT columnNumber,
SQLSMALLINT expectedDataType,
SQLULEN expectedColumnSize,
SQLSMALLINT expectedDecimalDigits,
SQLSMALLINT expectedNullable)
{
SQLSMALLINT dataType = 0;
SQLULEN columnSize = 0;
SQLSMALLINT decimalDigits = 0;
SQLSMALLINT nullable = 0;
SQLRETURN result = GetResultColumn(
*m_sessionId,
m_taskId,
columnNumber,
&dataType,
&columnSize,
&decimalDigits,
&nullable);
ASSERT_EQ(result, SQL_SUCCESS);
EXPECT_EQ(dataType, expectedDataType);
EXPECT_EQ(columnSize, expectedColumnSize);
EXPECT_EQ(decimalDigits, expectedDecimalDigits);
EXPECT_EQ(nullable, expectedNullable);
}
}
| 33.82963
| 109
| 0.675279
|
rabryst
|
617e86f51a938281f60ef3138da3a4fdba0e4c5f
| 6,704
|
cpp
|
C++
|
src/sli_gpg/finger_hand.cpp
|
Smilels/sli_gpg
|
bf00c773b187ca13da0a2c949f9cfbee2c038172
|
[
"BSD-2-Clause"
] | null | null | null |
src/sli_gpg/finger_hand.cpp
|
Smilels/sli_gpg
|
bf00c773b187ca13da0a2c949f9cfbee2c038172
|
[
"BSD-2-Clause"
] | null | null | null |
src/sli_gpg/finger_hand.cpp
|
Smilels/sli_gpg
|
bf00c773b187ca13da0a2c949f9cfbee2c038172
|
[
"BSD-2-Clause"
] | null | null | null |
#include <gpg/finger_hand.h>
FingerHand::FingerHand(double finger_width, double hand_outer_diameter, double hand_depth)
: finger_width_(finger_width), hand_depth_(hand_depth), lateral_axis_(-1),
forward_axis_(-1)
{
int n = 10; // number of finger placements to consider over a single hand diameter
// Calculate the finger spacing.
Eigen::VectorXd fs_half;
fs_half.setLinSpaced(n, 0.0, hand_outer_diameter - finger_width);
finger_spacing_.resize(2 * n);
finger_spacing_ << (fs_half.array() - hand_outer_diameter + finger_width_).matrix(), fs_half;
fingers_ = Eigen::Array<bool, 1, Eigen::Dynamic>::Constant(1, 2 * n, false);
hand_ = Eigen::Array<bool, 1, Eigen::Dynamic>::Constant(1, n, false);
}
void FingerHand::evaluateFingers(const Eigen::Matrix3Xd& points, double bite, int idx)
{
// Calculate top and bottom of the hand (top = fingertip, bottom = base).
top_ = bite;
bottom_ = bite - hand_depth_;
fingers_.setConstant(false);
// Crop points at bite.
std::vector<int> cropped_indices;
for (int i = 0; i < points.cols(); i++)
{
if (points(forward_axis_, i) < bite)
{
// Check that the hand would be able to extend by <bite> onto the object without causing the back of the hand to
// collide with <points>.
if (points(forward_axis_, i) < bottom_)
{
return;
}
cropped_indices.push_back(i);
}
}
// Check that there is at least one point in between the fingers.
if (cropped_indices.size() == 0)
{
return;
}
// Identify free gaps (finger placements that do not collide with the point cloud).
if (idx == -1)
{
for (int i = 0; i < fingers_.size(); i++)
{
if (isGapFree(points, cropped_indices, i))
{
fingers_(i) = true;
}
}
}
else
{
if (isGapFree(points, cropped_indices, idx))
{
fingers_(idx) = true;
}
if (isGapFree(points, cropped_indices, fingers_.size() / 2 + idx))
{
fingers_(fingers_.size() / 2 + idx) = true;
}
}
}
int FingerHand::evaluateFingers_out(const Eigen::Matrix3Xd& points, double bite, int idx)
{
// Calculate top and bottom of the hand (top = fingertip, bottom = base).
top_ = bite;
bottom_ = bite - hand_depth_;
fingers_.setConstant(false);
// Crop points at bite.
std::vector<int> cropped_indices;
for (int i = 0; i < points.cols(); i++)
{
if (points(forward_axis_, i) < bite)
{
// Check that the hand would be able to extend by <bite> onto the object without causing the back of the hand to
// collide with <points>.
if (points(forward_axis_, i) < bottom_)
{
return cropped_indices.size();
}
cropped_indices.push_back(i);
}
}
// Check that there is at least one point in between the fingers.
if (cropped_indices.size() == 0)
{
return cropped_indices.size();
}
// Identify free gaps (finger placements that do not collide with the point cloud).
if (idx == -1)
{
for (int i = 0; i < fingers_.size(); i++)
{
if (isGapFree(points, cropped_indices, i))
{
fingers_(i) = true;
}
}
}
else
{
if (isGapFree(points, cropped_indices, idx))
{
fingers_(idx) = true;
}
if (isGapFree(points, cropped_indices, fingers_.size() / 2 + idx))
{
fingers_(fingers_.size() / 2 + idx) = true;
}
}
return cropped_indices.size();
}
void FingerHand::evaluateHand()
{
const int n = fingers_.size() / 2;
for (int i = 0; i < n; i++)
{
hand_(i) = (fingers_(i) == true && fingers_(n + i) == true);
}
}
void FingerHand::evaluateHand(int idx)
{
const int n = fingers_.size() / 2;
hand_.setConstant(false);
hand_(idx) = (fingers_(idx) == true && fingers_(n + idx) == true);
}
int FingerHand::deepenHand(const Eigen::Matrix3Xd& points, double min_depth, double max_depth)
{
std::vector<int> hand_idx;
for (int i = 0; i < hand_.cols(); i++)
{
if (hand_(i) == true)
{
hand_idx.push_back(i);
}
}
if (hand_idx.size() == 0)
{
return -1;
}
// Choose middle hand.
int hand_eroded_idx = hand_idx[ceil(hand_idx.size() / 2.0) - 1]; // middle index
int opposite_idx = fingers_.size() / 2 + hand_eroded_idx; // opposite finger index
// Attempt to deepen hand (move as far onto the object as possible without collision).
const double DEEPEN_STEP_SIZE = 0.005;
FingerHand new_hand = *this;
FingerHand last_new_hand = new_hand;
int new_indices;
int last_new_indices;
int grow_indices;
for (double depth = min_depth + DEEPEN_STEP_SIZE; depth <= max_depth; depth += DEEPEN_STEP_SIZE)
{
// Check if the new hand placement is feasible
new_indices = new_hand.evaluateFingers_out(points, depth, hand_eroded_idx);
if (new_indices==0)
{
if (!new_hand.fingers_(hand_eroded_idx) || !new_hand.fingers_(opposite_idx))
break;
}
else
{
grow_indices=new_indices-last_new_indices;
if (!new_hand.fingers_(hand_eroded_idx) || !new_hand.fingers_(opposite_idx) || (grow_indices==0))
{
break;
}
}
last_new_indices= new_indices;
hand_(hand_eroded_idx) = true;
last_new_hand = new_hand;
}
// Recover the deepest hand.
*this = last_new_hand;
hand_.setConstant(false);
hand_(hand_eroded_idx) = true;
return hand_eroded_idx;
}
std::vector<int> FingerHand::computePointsInClosingRegion(const Eigen::Matrix3Xd& points, int idx)
{
// Find feasible finger placement.
if (idx == -1)
{
for (int i = 0; i < hand_.cols(); i++)
{
if (hand_(i) == true)
{
idx = i;
break;
}
}
}
// Calculate the lateral parameters of the hand closing region for this finger placement.
left_ = finger_spacing_(idx) + finger_width_;
right_ = finger_spacing_(hand_.cols() + idx);
center_ = 0.5 * (left_ + right_);
surface_ = points.row(lateral_axis_).minCoeff();
// Find points inside the hand closing region defined by <bottom_>, <top_>, <left_> and <right_>.
std::vector<int> indices;
for (int i = 0; i < points.cols(); i++)
{
if (points(forward_axis_, i) > bottom_ && points(forward_axis_, i) < top_
&& points(lateral_axis_, i) > left_ && points(lateral_axis_, i) < right_)
{
indices.push_back(i);
}
}
return indices;
}
bool FingerHand::isGapFree(const Eigen::Matrix3Xd& points, const std::vector<int>& indices, int idx)
{
for (int i = 0; i < indices.size(); i++)
{
const double& x = points(lateral_axis_, indices[i]);
if (x > finger_spacing_(idx) && x < finger_spacing_(idx) + finger_width_)
{
return false;
}
}
return true;
}
| 25.587786
| 118
| 0.62858
|
Smilels
|
61824c95ab95da4e692969a805325bdb363629be
| 11,915
|
cpp
|
C++
|
test/reserve_test.cpp
|
mattwatts/marzone
|
85082e3346937010703ecad829f0eb2fd132d82f
|
[
"MIT"
] | 3
|
2021-03-17T14:36:54.000Z
|
2021-03-17T20:25:21.000Z
|
test/reserve_test.cpp
|
mattwatts/marzone
|
85082e3346937010703ecad829f0eb2fd132d82f
|
[
"MIT"
] | null | null | null |
test/reserve_test.cpp
|
mattwatts/marzone
|
85082e3346937010703ecad829f0eb2fd132d82f
|
[
"MIT"
] | 1
|
2020-10-02T20:06:07.000Z
|
2020-10-02T20:06:07.000Z
|
#include "../reserve.hpp"
#include "CppUTest/TestHarness.h"
using namespace marzone;
TEST_GROUP(ReserveTestsGroup)
{
};
// ensure loadZones correctly parses.
TEST(ReserveTestsGroup, Reserve_InitializeSolution_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
Reserve r(spec, 3, 1); // 3 zones
CHECK_EQUAL(3, r.speciesAmounts.size());
r.InitializeSolution(5);
CHECK_EQUAL(5, r.solution.size());
r.InitializeSolution(2);
CHECK_EQUAL(2, r.solution.size());
}
// tests basic ComputeSpeciesAmounts with the _test1 suite.
TEST(ReserveTestsGroup, Reserve_ComputeSpeciesAmounts_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.puname = "data/pu_test1.dat";
fnames.zonesname = "data/zones_test1.dat";
fnames.zonecontribname = "data/zonecontrib_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
Zones zones(fnames, c, logger);
Pu pu(fnames, c, 0, zones.zoneNames, logger);
pu.LoadSparseMatrix(spec, "data/puvspr_test1.dat", logger);
zones.BuildZoneContributions(spec, pu);
Reserve r(spec, 3, 1); // 3 zones
// set a solution
r.InitializeSolution(pu.puno);
// compute species amounts
r.ComputeSpeciesAmounts(pu, spec, zones);
int spind1 = spec.LookupIndex(1);
int spind2 = spec.LookupIndex(2);
int spind3 = spec.LookupIndex(3);
CHECK(spind1 != -1 && spind2 != -1 && spind3 != -1);
CHECK_EQUAL(70.5, r.speciesAmounts[spind1].amount); //20.0*1 + 50.5*1
CHECK_EQUAL(15.8*0.5 + 118*0.5, r.speciesAmounts[spind2].amount); //15.8*0.5 + 118*0.5
CHECK_EQUAL(212, r.speciesAmounts[spind3].amount); //200.0*1 + 12*1
// Check occs
CHECK_EQUAL(2, r.speciesAmounts[spind1].occurrence);
CHECK_EQUAL(2, r.speciesAmounts[spind2].occurrence);
CHECK_EQUAL(2, r.speciesAmounts[spind3].occurrence);
r.solution[0] = 1; // flip zone to 1 indirectly
r.ComputeSpeciesAmounts(pu, spec, zones); // recompute.
CHECK_EQUAL(50.5, r.speciesAmounts[spind1].amount); //20.0*0 + 50.5*1
CHECK_EQUAL(15.8*0.5 + 118*0.5, r.speciesAmounts[spind2].amount); // same as before
CHECK_EQUAL(212, r.speciesAmounts[spind3].amount); // same as before.
}
// tests basic CheckChangeValue with the _test1 suite.
TEST(ReserveTestsGroup, Reserve_CheckChangeValue_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.puname = "data/pu_test1.dat";
fnames.zonesname = "data/zones_test1.dat";
fnames.zonecontribname = "data/zonecontrib_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
Zones zones(fnames, c, logger);
Pu pu(fnames, c, 0, zones.zoneNames, logger);
pu.LoadSparseMatrix(spec, "data/puvspr_test1.dat", logger);
zones.BuildZoneContributions(spec, pu);
Reserve r(spec, 3, 1); // 3 zones
// set a solution
r.InitializeSolution(pu.puno);
r.ComputeSpeciesAmounts(pu, spec, zones);
int spind1 = spec.LookupIndex(1);
int spind2 = spec.LookupIndex(2);
int spind3 = spec.LookupIndex(3);
schange change1 = r.InitializeChange(spec, zones);
r.CheckChangeValue(change1, 0, 0, 1, pu, zones, spec, 0, 1); //puindex 0, preZone 0, postZone 1.
// Check species amounts not changed
CHECK_EQUAL(70.5, r.speciesAmounts[spind1].amount); //20.0*1 + 50.5*1
CHECK_EQUAL(66.9, r.speciesAmounts[spind2].amount); //15.8*0.5 + 118*0.5
CHECK_EQUAL(212, r.speciesAmounts[spind3].amount); //200.0*1 + 12*1
// check change value is 20 for species 1
CHECK_EQUAL(1, change1.specListChangeTarget.size());
CHECK_EQUAL(spind1, change1.specListChangeTarget[0].first);
CHECK_EQUAL(-20, change1.specListChangeTarget[0].second);
// check change occurrence
CHECK_EQUAL(1, change1.specListChangeOcc.size());
CHECK_EQUAL(-1, change1.specListChangeOcc[0]);
// Check others are 0 because zoneTargets don't exist
CHECK_EQUAL(0, change1.zoneTargetChange.size());
CHECK_EQUAL(0, change1.zoneOccChange.size());
CHECK_EQUAL(0, change1.speciesClumpChange.size());
// Check change overall values
CHECK_EQUAL(20, change1.shortfall);
CHECK_EQUAL(0, change1.penalty); // no penalties set for this example.
CHECK_EQUAL(0, change1.cost);
CHECK_EQUAL(0, change1.connection);
CHECK_EQUAL(0, change1.total); // no penalty, cost or connection changes here.
// Apply the change.
r.ApplyChange(0, 1, change1, pu, zones, spec);
CHECK_EQUAL(1, r.solution[0]);
CHECK_EQUAL(50.5, r.speciesAmounts[spind1].amount); //20.0*0 + 50.5*1
CHECK_EQUAL(15.8*0.5 + 118*0.5, r.speciesAmounts[spind2].amount); //15.8*0.5 + 118*0.5
CHECK_EQUAL(212, r.speciesAmounts[spind3].amount); //200.0*1 + 12*1
}
// tests basic EvaluateObjectiveValue with the _test1 suite.
TEST(ReserveTestsGroup, Reserve_EvaluateObjectiveValue_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.puname = "data/pu_test1.dat";
fnames.zonesname = "data/zones_test1.dat";
fnames.zonecontribname = "data/zonecontrib_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
Zones zones(fnames, c, logger);
Pu pu(fnames, c, 0, zones.zoneNames, logger);
pu.LoadSparseMatrix(spec, "data/puvspr_test1.dat", logger);
zones.BuildZoneContributions(spec, pu);
Reserve r(spec, 3, 1); // 3 zones
// set a solution to 0 0 0 0 0
r.InitializeSolution(pu.puno);
// Evaluate objective value. and check shortfall, connections, cost
r.EvaluateObjectiveValue(pu, spec, zones, 1);
// We know given this configuration, the species amounts are 70.5, 66.9, 212
// we have not called SetProportionTargets so the regular (non proportion) targets are 100, 110 and 120
double expected = (100-70.5)+(110-66.9) + (3-2); // 3-2 = shortfall occurrence for species 3
CHECK_EQUAL(expected, r.objective.shortfall);
// Since all pu are being used, and there's no zoneCost supplied, it should be total pu cost in this case.
// note that the 5 missing costs get defaulted to 1, hence +5.
CHECK_EQUAL(6+66+666+2+2+5, r.objective.cost);
// Connection cost - 0 in this case since no connections entered
CHECK_EQUAL(0, r.objective.connection);
}
// Test shortfall and penalty calculation when there is zone targets.
TEST(ReserveTestsGroup, Reserve_EvaluateObjectiveValue_ZoneTargets_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.puname = "data/pu_test1.dat";
fnames.zonesname = "data/zones_test1.dat";
fnames.zonecontribname = "data/zonecontrib_test1.dat";
fnames.zonetargetname = "data/zonetarget_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
// set dummy penalties
vector<double> penalties {1000.0, 1000.0, 1000.0};
spec.SetPenalties(penalties);
Zones zones(fnames, c, logger);
Pu pu(fnames, c, 0, zones.zoneNames, logger);
pu.LoadSparseMatrix(spec, "data/puvspr_test1.dat", logger);
zones.BuildZoneContributions(spec, pu);
zones.BuildZoneTarget(spec, pu, fnames, logger);
Reserve r(spec, 3, 1); // 3 zones
// set a solution to 0 0 0 0 0
r.InitializeSolution(pu.puno);
// Evaluate objective value. and check shortfall, connections, cost
r.EvaluateObjectiveValue(pu, spec, zones, 1);
double expected = (100-70.5)+(110-66.9) + (3-2); // regular shortfall
expected += 100+ 500+ (1000-70.5); // shortfall with zone targets. Zone targ only supplied for species 1, but for all zones.
CHECK_EQUAL(expected, r.objective.shortfall);
CHECK(r.objective.penalty > 0);
// Test change with pu2 to zone 1.
schange change1 = r.InitializeChange(spec, zones);
r.CheckChangeValue(change1, 0, 0, 1, pu, zones, spec, 0, 1); //puindex 0, preZone 0, postZone 1.
// ensure targets adjusted. Zone1 loses 20 and zone2 gains 20
CHECK_EQUAL(2, change1.zoneTargetChange.size());
CHECK_EQUAL(2, change1.zoneOccChange.size());
CHECK_EQUAL(-20, change1.zoneTargetChange[0].second);
CHECK_EQUAL(20, change1.zoneTargetChange[1].second);
CHECK_EQUAL(-1, change1.zoneOccChange[0]);
CHECK_EQUAL(1, change1.zoneOccChange[1]);
// overall change in shortfall is positive (i.e. shortfall increased), since zone2 has a zonecontrib of 0
// we should also ensure symmetry of changing a planning unit back and forth.
double pre_change = change1.shortfall, pre_penalty = change1.penalty;
CHECK(pre_change > 0);
CHECK(pre_penalty > 0);
r.ApplyChange(0, 1, change1, pu, zones, spec);
r.CheckChangeValue(change1, 0, 1, 0, pu, zones, spec, 0, 1); //puindex 0, preZone 1, postZone 0. Opposite of before.
// ensure symmetry of values
CHECK(change1.shortfall == -pre_change);
CHECK(change1.penalty == -pre_penalty);
}
// This is a generic test that ensures flipping pu back and forth gives symmetrical results.
// This test does not check for specific values
TEST(ReserveTestsGroup, Reserve_Symmetry_test)
{
sfname fnames = {};
fnames.costsname = "data/costs_test1.dat";
fnames.specname = "data/species_test1.dat";
fnames.puname = "data/pu_test1.dat";
fnames.zonesname = "data/zones_test1.dat";
fnames.zonecontribname = "data/zonecontrib_test1.dat";
fnames.zonetargetname = "data/zonetarget_test1.dat";
fnames.inputdir = "";
Logger logger;
Costs c(fnames, logger);
Species spec(fnames, logger);
// set dummy penalties
vector<double> penalties {1000.0, 1000.0, 1000.0};
spec.SetPenalties(penalties);
Zones zones(fnames, c, logger);
Pu pu(fnames, c, 0, zones.zoneNames, logger);
pu.LoadSparseMatrix(spec, "data/puvspr_test1.dat", logger);
zones.BuildZoneContributions(spec, pu);
zones.BuildZoneTarget(spec, pu, fnames, logger);
Reserve r(spec, 3, 1); // 3 zones
// set a solution to 0 0 0 0 0
r.InitializeSolution(pu.puno);
// Evaluate objective value. and check shortfall, connections, cost
r.EvaluateObjectiveValue(pu, spec, zones, 1);
// Set up objects needed for symmetry testing.
uniform_int_distribution<int> randomDist(0, zones.zoneCount);
mt19937 rngEngine(1); // arbitrary seed.
int preZone, postZone;
schange preChange = r.InitializeChange(spec, zones), postChange = r.InitializeChange(spec, zones);
for (int i = 0; i < pu.puno; i++) {
preZone = r.solution[i];
postZone = pu.RtnValidZoneForPu(i, preZone, randomDist, rngEngine, 3);
r.CheckChangeValue(preChange, i, preZone, postZone, pu, zones, spec, 0, 1);
r.ApplyChange(i, postZone, preChange, pu, zones, spec);
r.CheckChangeValue(postChange, i, postZone, preZone, pu, zones, spec, 0, 1);
// Ensure symmetry in changes
CHECK_EQUAL(preChange.total, -postChange.total);
CHECK_EQUAL(preChange.shortfall, -postChange.shortfall);
CHECK_EQUAL(preChange.penalty, -postChange.penalty);
CHECK_EQUAL(preChange.cost, -postChange.cost);
CHECK_EQUAL(preChange.connection, -postChange.connection);
}
}
| 39.849498
| 129
| 0.67243
|
mattwatts
|
61831df5548e171a05be307e7e92e854edbcef7f
| 50,372
|
cpp
|
C++
|
TongueQT/TongueQT/src/Vega/libraries/objMesh/objMeshOffsetVoxels.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | 2
|
2020-03-28T03:15:49.000Z
|
2020-09-09T02:54:33.000Z
|
TongueQT/TongueQT/src/Vega/libraries/objMesh/objMeshOffsetVoxels.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | null | null | null |
TongueQT/TongueQT/src/Vega/libraries/objMesh/objMeshOffsetVoxels.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | 2
|
2020-09-08T19:28:19.000Z
|
2021-07-25T00:35:26.000Z
|
/*************************************************************************
* *
* Vega FEM Simulation Library Version 2.2 *
* *
* "objMesh" library , Copyright (C) 2007 CMU, 2009 MIT, 2015 USC *
* All rights reserved. *
* *
* Code authors: Jernej Barbic, Christopher Twigg, Daniel Schroeder *
* http://www.jernejbarbic.com/code *
* *
* Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, *
* Doug L. James, Jovan Popovic *
* *
* Funding: National Science Foundation, Link Foundation, *
* Singapore-MIT GAMBIT Game Lab, *
* Zumberge Research and Innovation Fund at USC *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the BSD-style license that is *
* included with this library in the file LICENSE.txt *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
/*
Author: Jernej Barbic, 2003
Generates a voxel representation of an offset surface
*/
#if defined(_WIN32) || defined(WIN32)
#pragma warning(disable : 4996)
#pragma warning(disable : 4267)
#pragma warning(disable : 4244)
#endif
#include "objMeshOffsetVoxels.h"
#include "matrixIO.h"
#include "matrixMacros.h"
#include <fstream>
#include <iomanip>
#include <string.h>
using namespace std;
ObjMeshOffsetVoxels::ObjMeshOffsetVoxels( ObjMesh * objMesh_, int resolution_[3], int depth_, Vec3d bmin_, Vec3d bmax_ )
{
objMesh = new ObjMesh(*objMesh_);
init(resolution_, depth_, bmin_, bmax_);
}
ObjMeshOffsetVoxels::ObjMeshOffsetVoxels( ObjMesh * objMesh_, int resolution_[3], int depth_, double expansionFactor )
{
objMesh = new ObjMesh(*objMesh_);
// build mesh bounding box
Vec3d bmin_, bmax_;
objMesh->getCubicBoundingBox(expansionFactor, &bmin_, &bmax_);
init(resolution_, depth_, bmin_, bmax_);
}
void ObjMeshOffsetVoxels::init(int resolution_[3], int depth_, Vec3d bmin_, Vec3d bmax_)
{
resolution[0] = resolution_[0];
resolution[1] = resolution_[1];
resolution[2] = resolution_[2];
depth = depth_;
bmin = bmin_;
bmax = bmax_;
//cout << "Entering obj mesh voxelization routine..." << endl;
//cout << "Resolution is " << resolution[0] << " x " << resolution[1] << " x " << resolution[2] << " ..." << endl;
//cout << "Checking if mesh is triangular... ";
if (!(objMesh->isTriangularMesh()))
{
//cout << "mesh was not triangular: triangulating... ";
objMesh->triangulate();
//cout << "done" << endl;
}
else
{
//cout << "yes" << endl;
}
side = bmax - bmin;
inc[0] = side[0] / resolution[0];
inc[1] = side[1] / resolution[1];
inc[2] = side[2] / resolution[2];
//cout << "Scene bounding box is: " << bmin << " " << bmax << endl;
//cout << "Computing voxels intersecting the model..." << endl;
// iterate over all triangles
// for every triangle, find the voxel containing its center of mass
// then, grow the voxels until they don't intersect the triangle any more
voxels.clear(); // will contain voxels intersecting the triangles
// local search helpers:
set<voxel> checkedVoxels; // used to mark what voxels have already been visited
vector<voxel> scheduledVoxels; // contains voxels still to be processed
for (unsigned int i=0; i<objMesh->getNumGroups(); i++)
{
const ObjMesh::Group * getGroupHandle = objMesh->getGroupHandle(i);
for (unsigned int j=0; j<getGroupHandle->getNumFaces(); j++)
{
Vec3d p0 = objMesh->getPosition(getGroupHandle->getFace(j).getVertex(0).getPositionIndex());
Vec3d p1 = objMesh->getPosition(getGroupHandle->getFace(j).getVertex(1).getPositionIndex());
Vec3d p2 = objMesh->getPosition(getGroupHandle->getFace(j).getVertex(2).getPositionIndex());
TriangleBasic triangle(p0,p1,p2);
Vec3d center = 1.0 / 3 * (p0 + p1 + p2);
Vec3d relCenter = center-bmin;
// find voxel containing center
int vi,vj,vk;
vi = (int)(relCenter[0] / inc[0]);
vj = (int)(relCenter[1] / inc[1]);
vk = (int)(relCenter[2] / inc[2]);
checkedVoxels.clear();
checkedVoxels.insert(voxel(vi,vj,vk));
scheduledVoxels.clear();
scheduledVoxels.push_back(voxel(vi,vj,vk));
// while there are still some scheduled voxels:
// take one
// check if intersecting the triangle
// if yes
// add voxel to voxels
// queue all neighbors that haven't been visited yet
while (!scheduledVoxels.empty())
{
voxel v = scheduledVoxels.back();
scheduledVoxels.pop_back();
// make bounding box for voxel
Vec3d bbmin = bmin + Vec3d(v.first * inc[0], v.second * inc[1], v.third * inc[2]);
BoundingBox bbox(bbmin, bbmin + inc);
if (triangle.doesIntersectBox(bbox)) // intersection test
{
// add the voxel to the final list of hits
voxels.insert(v);
// queue all neighbors of v, and also put them into checkedVoxels
// (but don't do anything if they have already been queued)
voxel neighbor;
#define PROCESS(ii,jj,kk)\
neighbor = voxel(v.first+(ii),v.second+(jj),v.third+(kk));\
if ((neighbor.first >= 0) && (neighbor.first <= resolution[0]) &&\
(neighbor.second >= 0) && (neighbor.second <= resolution[1]) &&\
(neighbor.third >= 0) && (neighbor.third <= resolution[2])) \
{\
if (checkedVoxels.find(neighbor) == checkedVoxels.end())\
{\
checkedVoxels.insert(neighbor);\
scheduledVoxels.push_back(neighbor);\
}\
}
for (int iii=-1; iii<=1; iii++)
for (int jjj=-1; jjj<=1; jjj++)
for (int kkk=-1; kkk<=1; kkk++)
{
if ((iii == 0) && (jjj ==0) && (kkk==0))
continue;
PROCESS(iii,jjj,kkk)
}
}
}
// now, voxels contains all voxels that intersect the given triangle (plus everything from previous triangles)
}
}
// now, voxels contains all voxels intersecting any triangle
//cout << "Growing " << depth << " layers of voxels out of the original (squashing cubes) layer." << endl;
// grow voxels several layers
set<voxel> voxeli; // temporary buffer
for (int i=0; i<depth; i++)
{
// expand all voxels in all directions
// take everything out of voxels, expand one layer, and insert into voxeli
voxeli.clear();
voxel neighbor;
#define PROCESSI(ii,jj,kk)\
neighbor = voxel(vox->first+(ii),vox->second+(jj),vox->third+(kk));\
if ((neighbor.first >= 0) && (neighbor.first <= resolution[0]) &&\
(neighbor.second >= 0) && (neighbor.second <= resolution[1]) &&\
(neighbor.third >= 0) && (neighbor.third <= resolution[2])) \
{\
voxeli.insert(neighbor);\
}
set<voxel>::iterator vox;
for (vox = voxels.begin(); vox != voxels.end(); ++vox) // over all members of voxels
{
for (int iii=-1; iii<=1; iii++)
for (int jjj=-1; jjj<=1; jjj++)
for (int kkk=-1; kkk<=1; kkk++)
{
PROCESSI(iii,jjj,kkk)
}
}
voxels = voxeli;
}
//cout << "Building unique list of faces..." << endl;
// build unique list of faces
buildUniqueListOfFaces();
}
void ObjMeshOffsetVoxels::emptyComponents(vector<Vec3d> & componentSeeds, vector<int> & componentSize, bool interiorOnly)
{
componentSeeds.clear();
componentSize.clear();
set<voxel> voxelSet = voxels;
for(int i=0; i<resolution[0]; i++)
for(int j=0; j<resolution[1]; j++)
for(int k=0; k<resolution[2]; k++)
{
if (voxelSet.find(voxel(i,j,k)) == voxelSet.end())
{
// new component detected
size_t sizePrev = voxelSet.size();
Vec3d seed(bmin[0] + inc[0] * ( i + 0.5 ),
bmin[1] + inc[1] * ( j + 0.5 ),
bmin[2] + inc[2] * ( k + 0.5 ));
bool touchesBoundingBox = floodFillFromSet(seed, voxelSet);
if (!(interiorOnly && touchesBoundingBox))
{
componentSize.push_back(voxelSet.size() - sizePrev);
componentSeeds.push_back(seed);
}
}
}
}
void ObjMeshOffsetVoxels::floodFill(Vec3d seed)
{
//cout << "Flood-filling from seed: " << seed << endl;
floodFillFromSet(seed, voxels);
buildUniqueListOfFaces();
}
void ObjMeshOffsetVoxels::floodFill(vector<Vec3d> & seeds)
{
for(unsigned int i=0; i<seeds.size(); i++)
{
//cout << "Flood-filling from seed: " << seeds[i] << endl;
floodFillFromSet(seeds[i], voxels);
}
buildUniqueListOfFaces();
}
bool ObjMeshOffsetVoxels::floodFillFromSet(Vec3d seed, set<voxel> & voxelSet)
{
bool touchesBoundingBox = false;
// find voxel containing seed
int vi,vj,vk;
Vec3d relSeed = seed-bmin;
vi = (int)(relSeed[0] / inc[0]);
vj = (int)(relSeed[1] / inc[1]);
vk = (int)(relSeed[2] / inc[2]);
if ((vi < 0) || (vi >= resolution[0]) ||
(vj < 0) || (vj >= resolution[1]) ||
(vk < 0) || (vk >= resolution[2]))
{
printf("Warning: flood-filling seed is outside the bounding box. Performing no flood-fill.\n");
return false;
}
voxel seedVoxel(vi,vj,vk);
set<voxel> queue;
queue.insert(seedVoxel);
voxelSet.insert(seedVoxel);
while (!queue.empty())
{
//cout << "." << flush;
voxel vox = *(queue.begin());
queue.erase(vox);
voxel neighbor;
//printf("vox: %d %d %d\n",vox.first,vox.second,vox.third);
// process all 8 neighbors
#define PROCESSNGH(ii,jj,kk)\
neighbor = voxel(vox.first+(ii),vox.second+(jj),vox.third+(kk));\
if ((neighbor.first >= 0) && (neighbor.first < resolution[0]) &&\
(neighbor.second >= 0) && (neighbor.second < resolution[1]) &&\
(neighbor.third >= 0) && (neighbor.third < resolution[2])) \
{\
if (voxelSet.find(neighbor) == voxelSet.end())\
{\
queue.insert(neighbor);\
voxelSet.insert(neighbor);\
if (!touchesBoundingBox)\
if ((neighbor.first == 0) || (neighbor.first == resolution[0] - 1) ||\
(neighbor.second == 0) || (neighbor.second == resolution[1] - 1) ||\
(neighbor.third == 0) || (neighbor.third == resolution[2] - 1))\
touchesBoundingBox = true;\
}\
}
PROCESSNGH(1,0,0);
PROCESSNGH(-1,0,0);
PROCESSNGH(0,1,0);
PROCESSNGH(0,-1,0);
PROCESSNGH(0,0,1);
PROCESSNGH(0,0,-1);
}
return touchesBoundingBox;
}
void ObjMeshOffsetVoxels::buildUniqueListOfFaces()
{
surfaceFaces.clear();
interiorFaces.clear();
set<voxel>::iterator vox;
for (vox = voxels.begin(); vox != voxels.end(); ++vox) // over all members of voxels
{
// for each face of vox:
// if already on the list of surface faces, erase it from there, and add it among interior faces
// else add it among surface faces
//cout << "Voxel: " << vox->first << " " << vox->second << " " << vox->third << endl;
gridPoint pmin(vox->first,vox->second,vox->third);
gridPoint pmax(vox->first+1,vox->second+1,vox->third+1);
gridPoint p0(pmin.first,pmin.second,pmin.third);
gridPoint p1(pmax.first,pmin.second,pmin.third);
gridPoint p2(pmax.first,pmax.second,pmin.third);
gridPoint p3(pmin.first,pmax.second,pmin.third);
gridPoint p4(pmin.first,pmin.second,pmax.third);
gridPoint p5(pmax.first,pmin.second,pmax.third);
gridPoint p6(pmax.first,pmax.second,pmax.third);
gridPoint p7(pmin.first,pmax.second,pmax.third);
TopologicalFace * face;
#define PROCESS_FACE(q0,q1,q2,q3)\
face = new TopologicalFace((q0),(q1),(q2),(q3));\
if (surfaceFaces.find(*face) != surfaceFaces.end())\
{\
surfaceFaces.erase(*face);\
interiorFaces.insert(*face);\
}\
else\
{\
surfaceFaces.insert(*face);\
}\
delete(face);
PROCESS_FACE(p0,p3,p2,p1)
PROCESS_FACE(p4,p5,p6,p7)
PROCESS_FACE(p0,p1,p5,p4)
PROCESS_FACE(p3,p7,p6,p2)
PROCESS_FACE(p1,p2,p6,p5)
PROCESS_FACE(p0,p4,p7,p3)
}
}
void ObjMeshOffsetVoxels::render()
{
set<voxel>::iterator vox;
for (vox = voxels.begin(); vox != voxels.end(); ++vox) // over all members of voxels
renderVoxel(*vox);
}
void ObjMeshOffsetVoxels::renderSurfaceFaces()
{
set<TopologicalFace,FaceOrder>::iterator face;
for (face = surfaceFaces.begin(); face != surfaceFaces.end(); ++face) // over all surface faces
renderTopologicalFace(*face);
}
void ObjMeshOffsetVoxels::renderVoxel(voxel vox)
{
// make bounding box for voxel
Vec3d bbmin = bmin + Vec3d(vox.first*inc[0],vox.second*inc[1],vox.third*inc[2]);
BoundingBox bbox(bbmin,bbmin+inc);
bbox.render();
}
void ObjMeshOffsetVoxels::renderTopologicalFace(const TopologicalFace & face) const
{
// make flat bounding box
Vec3d bbmin = Vec3d(face.vertex(0).first*inc[0],face.vertex(0).second*inc[1],face.vertex(0).third*inc[2]);
bbmin += bmin;
Vec3d bbmax = Vec3d(face.vertex(2).first*inc[0],face.vertex(2).second*inc[1],face.vertex(2).third*inc[2]);
bbmax += bmin;
BoundingBox bbox(bbmin,bbmax);
bbox.render();
}
ObjMesh * ObjMeshOffsetVoxels::surfaceOffsetMesh()
{
ObjMesh * objMesh = new ObjMesh();
// create a list of vertices
set<gridPoint> vertices;
set<TopologicalFace,FaceOrder>::iterator face; // insert all vertices
for (face = surfaceFaces.begin(); face != surfaceFaces.end(); ++face) // over all surface faces
{
vertices.insert(face->vertex(0));
vertices.insert(face->vertex(1));
vertices.insert(face->vertex(2));
vertices.insert(face->vertex(3));
}
// now, vertices contains all vertices with no duplications
// create default group
objMesh->addGroup("Default");
// add all vertices into a map, together with their corresponding position
// also, add vertices to objMesh
map<gridPoint,int> vertices2;
set<gridPoint>:: iterator v;
int position=0;
for (v = vertices.begin(); v != vertices.end(); ++v)
{
vertices2.insert(pair<gridPoint,int>(*v,position));
Vec3d pos = bmin + Vec3d(v->first*inc[0], v->second*inc[1], v->third*inc[2]);
objMesh->addVertexPosition( pos );
//cout << "Position " << position << ": " << pos << endl;
position++;
}
// add all faces
unsigned int index;
for (face = surfaceFaces.begin(); face != surfaceFaces.end(); ++face) // over all surface faces
{
ObjMesh::Face newFace;
for (int i=0; i<4; i++)
{
index = (vertices2.find(face->vertex(i)))->second;
std::pair< bool, unsigned int > texPos(false,0); // no textures or normals assigned
std::pair< bool, unsigned int > normal(false,0);
newFace.addVertex( ObjMesh::Vertex( index, texPos, normal ) );
}
objMesh->addFaceToGroup(newFace,0);
}
return objMesh;
}
bool ObjMeshOffsetVoxels::FaceOrder::operator()(const TopologicalFace & x, const TopologicalFace & y) const
{
// first, sort the vertices on each face (order of vertices is irrelevant when comparing if two faces are equal)
TopologicalFace xSorted = x; xSorted.sortVertices();
TopologicalFace ySorted = y; ySorted.sortVertices();
for (int i=0; i<4; i++)
{
gridPoint x1 = xSorted.vertex(i);
gridPoint y1 = ySorted.vertex(i);
if (x1 < y1)
return true;
if (y1 < x1)
return false;
}
return false;
}
ObjMeshOffsetVoxels::TopologicalFace::TopologicalFace(gridPoint p1, gridPoint p2, gridPoint p3, gridPoint p4)
{
vertices_.push_back(p1); vertices_.push_back(p2); vertices_.push_back(p3); vertices_.push_back(p4);
assert(vertices_.size() == 4);
}
void ObjMeshOffsetVoxels::TopologicalFace::sortVertices()
{
sort(vertices_.begin(),vertices_.end());
// sanity check
unique(vertices_.begin(),vertices_.end());
assert(vertices_.size() == 4);
}
void ObjMeshOffsetVoxels::generateCubicMesh(const string & filenameVeg, const string & filenameInterp, const string & filenameObj)
{
cout << "Generating cubic mesh..." << endl;
cout << "Writing mesh to " << filenameVeg << " ." << endl;
// open file
ofstream fout(filenameVeg.c_str());
if (!fout)
{
cout << "Error: could not write to file " << filenameVeg << endl;
return;
}
// create a list of vertices in all voxels
set<gridPoint> vertices;
// insert all voxel vertices
set<voxel>::iterator aVoxel;
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
vertices.insert(gridPoint(i1,j1,k1));
vertices.insert(gridPoint(i1+1,j1,k1));
vertices.insert(gridPoint(i1+1,j1+1,k1));
vertices.insert(gridPoint(i1,j1+1,k1));
vertices.insert(gridPoint(i1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1+1,k1+1));
vertices.insert(gridPoint(i1,j1+1,k1+1));
}
// now, vertices contains all voxel vertices with no duplications
cout << "Num voxels: " << voxels.size() << " Num voxel vertices: " << vertices.size() << endl;
// open up the objMesh for the output surface mesh
ObjMesh * objMesh = new ObjMesh();
// create default group
objMesh->addGroup("Default");
// add all voxel vertices into a map, together with their corresponding index (i.e. serial number of a voxel vertex in the set order)
map<gridPoint,int> vertices2;
set<gridPoint>:: iterator v; // will run over all voxel vertices
int position=0;
fout << "*VERTICES" << endl;
fout << (int)vertices.size() << " 3 0 0" << endl;
for (v = vertices.begin(); v != vertices.end(); ++v)
{
vertices2.insert(pair<gridPoint,int>(*v,position));
Vec3d pos = bmin + Vec3d(v->first*inc[0], v->second*inc[1], v->third*inc[2]);
objMesh->addVertexPosition(pos);
//cout << "Position " << position << ": " << pos << endl;
position++;
// write vertex to file
fout << setprecision (16) << position << " " << pos[0] << " " << pos[1] << " " << pos[2] << endl;
}
fout << endl;
fout << "*ELEMENTS" << endl;
fout << "CUBIC" << endl;
fout << (int)voxels.size() << " 4 0" << endl;
// print out all voxels
unsigned int index;
position = 0;
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
fout << position+1;
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
#define PROCESS_CORNER(di,dj,dk)\
index = 1+(vertices2.find(gridPoint(i1+(di),j1+(dj),k1+(dk))))->second;\
fout << " " << index;
PROCESS_CORNER(0,0,0);
PROCESS_CORNER(1,0,0);
PROCESS_CORNER(1,1,0);
PROCESS_CORNER(0,1,0);
PROCESS_CORNER(0,0,1);
PROCESS_CORNER(1,0,1);
PROCESS_CORNER(1,1,1);
PROCESS_CORNER(0,1,1);
fout << endl;
position++;
}
fout.close();
// generate the barycentric masks
cout << "Writing interpolation info to file " << filenameInterp << " ." << endl;
// open file
fout.open(filenameInterp.c_str());
if (!fout)
{
cout << "Error: could not write to file " << filenameInterp << endl;
return;
}
// for every vertex of the mesh, find what voxel it is in
// then find indices of the vertices of that voxel
// and compute the barycentric coordinates
for (unsigned int i=0; i < objMesh->getNumVertices(); i++) // over all vertices of the mesh
{
Vec3d pos = objMesh->getPosition(i);
unsigned int i1,j1,k1;
Vec3d relPos = pos-bmin;
// find voxel containing 'pos'
i1 = (unsigned int)(relPos[0] / inc[0]);
j1 = (unsigned int)(relPos[1] / inc[1]);
k1 = (unsigned int)(relPos[2] / inc[2]);
// compute barycentric coordinates
Vec3d w = pos - (bmin + Vec3d(i1 * inc[0], j1 * inc[1], k1 * inc[2]));
double alpha = w[0] / inc[0];
double beta = w[1] / inc[1];
double gamma = w[2] / inc[2];
unsigned int c000 = vertices2.find(gridPoint(i1+0,j1+0,k1+0))->second;
unsigned int c100 = vertices2.find(gridPoint(i1+1,j1+0,k1+0))->second;
unsigned int c110 = vertices2.find(gridPoint(i1+1,j1+1,k1+0))->second;
unsigned int c010 = vertices2.find(gridPoint(i1+0,j1+1,k1+0))->second;
unsigned int c001 = vertices2.find(gridPoint(i1+0,j1+0,k1+1))->second;
unsigned int c101 = vertices2.find(gridPoint(i1+1,j1+0,k1+1))->second;
unsigned int c111 = vertices2.find(gridPoint(i1+1,j1+1,k1+1))->second;
unsigned int c011 = vertices2.find(gridPoint(i1+0,j1+1,k1+1))->second;
double f000 = (1-alpha)*(1-beta)*(1-gamma);
double f100 = (alpha)*(1-beta)*(1-gamma);
double f110 = (alpha)*(beta)*(1-gamma);
double f010 = (1-alpha)*(beta)*(1-gamma);
double f001 = (1-alpha)*(1-beta)*(gamma);
double f101 = (alpha)*(1-beta)*(gamma);
double f111 = (alpha)*(beta)*(gamma);
double f011 = (1-alpha)*(beta)*(gamma);
fout << i << " ";
fout << c000 << " " << f000 << " ";
fout << c100 << " " << f100 << " ";
fout << c110 << " " << f110 << " ";
fout << c010 << " " << f010 << " ";
fout << c001 << " " << f001 << " ";
fout << c101 << " " << f101 << " ";
fout << c111 << " " << f111 << " ";
fout << c011 << " " << f011 << endl;
}
fout.close();
// by now, surfaceFaces contains a unique list of all surface faces
// add all faces to the surface obj mesh of the voxel mesh
set<TopologicalFace,FaceOrder>::iterator face;
for (face = surfaceFaces.begin(); face != surfaceFaces.end(); ++face) // all surface faces
{
int index[4];
for (int i=0; i<4; i++)
index[i] = (vertices2.find(face->vertex(i)))->second;
std::pair< bool, unsigned int > texPos(false,0); // no textures
std::pair< bool, unsigned int > normal(false,0); // no normals
/*
// triangulate the face into two triangles
Face newFace1;
newFace1.addVertex( Vertex( index[0], texPos, normal ) );
newFace1.addVertex( Vertex( index[1], texPos, normal ) );
newFace1.addVertex( Vertex( index[2], texPos, normal ) );
Face newFace2;
newFace2.addVertex( Vertex( index[2], texPos, normal ) );
newFace2.addVertex( Vertex( index[3], texPos, normal ) );
newFace2.addVertex( Vertex( index[0], texPos, normal ) );
objMesh->addFaceToGroup(newFace1,0);
objMesh->addFaceToGroup(newFace2,0);
*/
// make one quad face
ObjMesh::Face newFace;
newFace.addVertex( ObjMesh::Vertex( index[0], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[1], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[2], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[3], texPos, normal ) );
objMesh->addFaceToGroup(newFace,0);
}
// search if there already is "default" material; if there is not, add it
objMesh->addDefaultMaterial();
objMesh->computeBoundingBox();
objMesh->save(filenameObj);
delete(objMesh);
}
void ObjMeshOffsetVoxels::generateCubicMesh(int * numCubeVertices, double ** cubeVertices, int * numCubes, int ** cubes, int ** interpolationVertices, double ** interpolationWeights, ObjMesh ** surfaceMesh)
{
//cout << "Generating cubic mesh..." << endl;
// create a list of vertices in all voxels
set<gridPoint> vertices;
// insert all voxel vertices
set<voxel>::iterator aVoxel;
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
vertices.insert(gridPoint(i1,j1,k1));
vertices.insert(gridPoint(i1+1,j1,k1));
vertices.insert(gridPoint(i1+1,j1+1,k1));
vertices.insert(gridPoint(i1,j1+1,k1));
vertices.insert(gridPoint(i1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1+1,k1+1));
vertices.insert(gridPoint(i1,j1+1,k1+1));
}
// now, "vertices" contains all voxel vertices with no duplications
//cout << "Num voxels: " << voxels.size() << " Num voxel vertices: " << vertices.size() << endl;
// creates an empty objMesh (for the output surface mesh)
*surfaceMesh = new ObjMesh();
// create default group
(*surfaceMesh)->addGroup("Default");
// add all voxel vertices into a map, together with their corresponding index (i.e. serial number of a voxel vertex in the set order)
map<gridPoint,int> vertices2;
set<gridPoint>:: iterator v; // will run over all voxel vertices
int position=0;
*numCubeVertices = vertices.size();
*cubeVertices = (double*) malloc (sizeof(double) * 3 * vertices.size());
for (v = vertices.begin(); v != vertices.end(); ++v)
{
vertices2.insert(pair<gridPoint,int>(*v,position));
Vec3d pos = bmin + Vec3d(v->first*inc[0], v->second*inc[1], v->third*inc[2]);
(*surfaceMesh)->addVertexPosition(pos);
(*cubeVertices)[3*position+0] = pos[0];
(*cubeVertices)[3*position+1] = pos[1];
(*cubeVertices)[3*position+2] = pos[2];
//cout << "Position " << position << ": " << pos << endl;
position++;
}
unsigned int index;
position = 0;
*numCubes = voxels.size();
*cubes = (int*) malloc (sizeof(int) * voxels.size() * 8);
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
#define PROCESS_CORNER_SHORT(di,dj,dk)\
index = (vertices2.find(gridPoint(i1+(di),j1+(dj),k1+(dk))))->second;
PROCESS_CORNER_SHORT(0,0,0); (*cubes)[8*position+0] = index;
PROCESS_CORNER_SHORT(1,0,0); (*cubes)[8*position+1] = index;
PROCESS_CORNER_SHORT(1,1,0); (*cubes)[8*position+2] = index;
PROCESS_CORNER_SHORT(0,1,0); (*cubes)[8*position+3] = index;
PROCESS_CORNER_SHORT(0,0,1); (*cubes)[8*position+4] = index;
PROCESS_CORNER_SHORT(1,0,1); (*cubes)[8*position+5] = index;
PROCESS_CORNER_SHORT(1,1,1); (*cubes)[8*position+6] = index;
PROCESS_CORNER_SHORT(0,1,1); (*cubes)[8*position+7] = index;
position++;
}
// generate the barycentric masks
// for every vertex of the mesh, find what voxel it is in
// then, find indices of the vertices of that voxel
// and compute the barycentric coordinates
*interpolationVertices = (int*) malloc (sizeof(int) * 8 * objMesh->getNumVertices());
*interpolationWeights = (double*) malloc (sizeof(double) * 8 * objMesh->getNumVertices());
for (unsigned int i=0; i < objMesh->getNumVertices(); i++) // over all vertices of the mesh
{
Vec3d pos = objMesh->getPosition(i);
unsigned int i1,j1,k1;
Vec3d relPos = pos-bmin;
// find voxel containing 'pos'
i1 = (unsigned int)(relPos[0] / inc[0]);
j1 = (unsigned int)(relPos[1] / inc[1]);
k1 = (unsigned int)(relPos[2] / inc[2]);
// compute barycentric coordinates
Vec3d w = pos - (bmin + Vec3d(i1 * inc[0], j1 * inc[1], k1 * inc[2]));
double alpha = w[0] / inc[0];
double beta = w[1] / inc[1];
double gamma = w[2] / inc[2];
unsigned int c000, c100, c110, c010, c001, c101, c111, c011;
unsigned int * cArray[8] = { &c000, &c100, &c110, &c010, &c001, &c101, &c111, &c011 };
int offset[8][3] = { {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1} };
for(int j=0; j<8; j++)
{
map<gridPoint,int> :: iterator iter = vertices2.find(gridPoint(i1 + offset[j][0], j1 + offset[j][1], k1 + offset[j][2]));
if (iter != vertices2.end())
*(cArray[j]) = iter->second;
else
*(cArray[j]) = 0; // handle case where vertex is at the boundary of a voxel and round-off may move it to a non-existing voxel (barycentric coordinate is zero in this case)
}
//unsigned int c000 = vertices2.find(gridPoint(i1+0,j1+0,k1+0))->second;
//unsigned int c100 = vertices2.find(gridPoint(i1+1,j1+0,k1+0))->second;
//unsigned int c110 = vertices2.find(gridPoint(i1+1,j1+1,k1+0))->second;
//unsigned int c010 = vertices2.find(gridPoint(i1+0,j1+1,k1+0))->second;
//unsigned int c001 = vertices2.find(gridPoint(i1+0,j1+0,k1+1))->second;
//unsigned int c101 = vertices2.find(gridPoint(i1+1,j1+0,k1+1))->second;
//unsigned int c111 = vertices2.find(gridPoint(i1+1,j1+1,k1+1))->second;
//unsigned int c011 = vertices2.find(gridPoint(i1+0,j1+1,k1+1))->second;
double f000 = (1-alpha)*(1-beta)*(1-gamma);
double f100 = (alpha)*(1-beta)*(1-gamma);
double f110 = (alpha)*(beta)*(1-gamma);
double f010 = (1-alpha)*(beta)*(1-gamma);
double f001 = (1-alpha)*(1-beta)*(gamma);
double f101 = (alpha)*(1-beta)*(gamma);
double f111 = (alpha)*(beta)*(gamma);
double f011 = (1-alpha)*(beta)*(gamma);
(*interpolationVertices)[8*i+0] = c000;
(*interpolationVertices)[8*i+1] = c100;
(*interpolationVertices)[8*i+2] = c110;
(*interpolationVertices)[8*i+3] = c010;
(*interpolationVertices)[8*i+4] = c001;
(*interpolationVertices)[8*i+5] = c101;
(*interpolationVertices)[8*i+6] = c111;
(*interpolationVertices)[8*i+7] = c011;
(*interpolationWeights)[8*i+0] = f000;
(*interpolationWeights)[8*i+1] = f100;
(*interpolationWeights)[8*i+2] = f110;
(*interpolationWeights)[8*i+3] = f010;
(*interpolationWeights)[8*i+4] = f001;
(*interpolationWeights)[8*i+5] = f101;
(*interpolationWeights)[8*i+6] = f111;
(*interpolationWeights)[8*i+7] = f011;
}
// by now, surfaceFaces contains a unique list of all surface faces
// add all faces to the surface obj mesh of the voxel mesh
set<TopologicalFace,FaceOrder>::iterator face;
for (face = surfaceFaces.begin(); face != surfaceFaces.end(); ++face) // all surface faces
{
int index[4];
for (int i=0; i<4; i++)
index[i] = (vertices2.find(face->vertex(i)))->second;
std::pair< bool, unsigned int > texPos(false,0); // no textures
std::pair< bool, unsigned int > normal(false,0); // no normals
/*
// triangulate the face into two triangles
Face newFace1;
newFace1.addVertex( Vertex( index[0], texPos, normal ) );
newFace1.addVertex( Vertex( index[1], texPos, normal ) );
newFace1.addVertex( Vertex( index[2], texPos, normal ) );
Face newFace2;
newFace2.addVertex( Vertex( index[2], texPos, normal ) );
newFace2.addVertex( Vertex( index[3], texPos, normal ) );
newFace2.addVertex( Vertex( index[0], texPos, normal ) );
objMesh->addFaceToGroup(newFace1,0);
objMesh->addFaceToGroup(newFace2,0);
*/
// make one quad face
ObjMesh::Face newFace;
newFace.addVertex( ObjMesh::Vertex( index[0], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[1], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[2], texPos, normal ) );
newFace.addVertex( ObjMesh::Vertex( index[3], texPos, normal ) );
(*surfaceMesh)->addFaceToGroup(newFace,0);
}
// search if there already is "default" material; if there is not, add it
(*surfaceMesh)->addDefaultMaterial();
(*surfaceMesh)->computeBoundingBox();
}
void ObjMeshOffsetVoxels::generateInterpolationMasks(const string & filenameInterp, const string & inputObjMesh)
{
cout << "Generating interpolation masks for the external file " << inputObjMesh << endl;
// create a list of vertices in all voxels
set<gridPoint> vertices;
// insert all voxel vertices
set<voxel>::iterator aVoxel;
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
vertices.insert(gridPoint(i1,j1,k1));
vertices.insert(gridPoint(i1+1,j1,k1));
vertices.insert(gridPoint(i1+1,j1+1,k1));
vertices.insert(gridPoint(i1,j1+1,k1));
vertices.insert(gridPoint(i1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1+1,k1+1));
vertices.insert(gridPoint(i1,j1+1,k1+1));
}
// now, vertices contains all voxel vertices with no duplications
// add all voxel vertices into a map, together with their corresponding index (i.e. serial number of a voxel vertex in the set order)
map<gridPoint,int> vertices2;
set<gridPoint>:: iterator v; // will run over all voxel vertices
int position=0;
for (v = vertices.begin(); v != vertices.end(); ++v)
{
vertices2.insert(pair<gridPoint,int>(*v,position));
//Vec3d pos = bmin + Vec3d(v->first*inc[0], v->second*inc[1], v->third*inc[2]);
//cout << "Position " << position << ": " << pos << endl;
position++;
}
// generate the barycentric masks
cout << "Writing interpolation info to file " << filenameInterp << " ." << endl;
// open file
ofstream fout(filenameInterp.c_str());
if (!fout)
{
cout << "Error: could not write to file " << filenameInterp << endl;
return;
}
// for every vertex of the mesh, find what voxel it is in
// then find indices of the vertices of that voxel
// and compute the barycentric coordinates
ObjMesh inputMesh(inputObjMesh);
// will contain all voxels that contain at least one vertex of the external mesh
set<voxel> visitedVoxels;
cout << "Processing vertices of the external mesh file..." << endl;
for (unsigned int i=0; i < inputMesh.getNumVertices(); i++) // over all vertices of the mesh
{
if (i % 100 == 0)
cout << i << " " << flush;
Vec3d pos = inputMesh.getPosition(i);
unsigned int i1,j1,k1;
Vec3d relPos = pos-bmin;
// find voxel containing 'pos'
i1 = (unsigned int)(relPos[0] / inc[0]);
j1 = (unsigned int)(relPos[1] / inc[1]);
k1 = (unsigned int)(relPos[2] / inc[2]);
// store voxel so that we can later print out a list of visited voxels
visitedVoxels.insert(voxel(i1,j1,k1));
// compute barycentric coordinates
Vec3d w = pos - (bmin + Vec3d(i1 * inc[0], j1 * inc[1], k1 * inc[2]));
double alpha = w[0] / inc[0];
double beta = w[1] / inc[1];
double gamma = w[2] / inc[2];
map<gridPoint,int> :: iterator voxelVertexEntry;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+0,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 000" << endl;
return;
}
unsigned int c000 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+0,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 100" << endl;
return;
}
unsigned int c100 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+1,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 110" << endl;
return;
}
unsigned int c110 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+1,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 010" << endl;
return;
}
unsigned int c010 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+0,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 001" << endl;
return;
}
unsigned int c001 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+0,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 101" << endl;
return;
}
unsigned int c101 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+1,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 111" << endl;
return;
}
unsigned int c111 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+1,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 011" << endl;
return;
}
unsigned int c011 = voxelVertexEntry->second;
/*
unsigned int c000 = vertices2.find(gridPoint(i1+0,j1+0,k1+0))->second;
unsigned int c100 = vertices2.find(gridPoint(i1+1,j1+0,k1+0))->second;
unsigned int c110 = vertices2.find(gridPoint(i1+1,j1+1,k1+0))->second;
unsigned int c010 = vertices2.find(gridPoint(i1+0,j1+1,k1+0))->second;
unsigned int c001 = vertices2.find(gridPoint(i1+0,j1+0,k1+1))->second;
unsigned int c101 = vertices2.find(gridPoint(i1+1,j1+0,k1+1))->second;
unsigned int c111 = vertices2.find(gridPoint(i1+1,j1+1,k1+1))->second;
unsigned int c011 = vertices2.find(gridPoint(i1+0,j1+1,k1+1))->second;
*/
double f000 = (1-alpha)*(1-beta)*(1-gamma);
double f100 = (alpha)*(1-beta)*(1-gamma);
double f110 = (alpha)*(beta)*(1-gamma);
double f010 = (1-alpha)*(beta)*(1-gamma);
double f001 = (1-alpha)*(1-beta)*(gamma);
double f101 = (alpha)*(1-beta)*(gamma);
double f111 = (alpha)*(beta)*(gamma);
double f011 = (1-alpha)*(beta)*(gamma);
fout << i << " ";
fout << c000 << " " << f000 << " ";
fout << c100 << " " << f100 << " ";
fout << c110 << " " << f110 << " ";
fout << c010 << " " << f010 << " ";
fout << c001 << " " << f001 << " ";
fout << c101 << " " << f101 << " ";
fout << c111 << " " << f111 << " ";
fout << c011 << " " << f011 << endl;
}
fout.close();
// print out indices of all voxels that contain vertices of the external mesh
int index=1;
int lineCounter = 0;
printf("\nVoxels that contain vertices of the given external mesh:\n");
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
// seek for (i1,j1,k1) in the list of all voxels
if (visitedVoxels.find(voxel(i1,j1,k1)) != visitedVoxels.end())
{
printf("%d,",index);
lineCounter++;
}
if (lineCounter >= 8)
{
lineCounter = 0;
printf("\n");
}
index++;
}
printf("\n");
index=1;
lineCounter = 0;
printf("\nVoxels that DO NOT contain vertices of the given external mesh:\n");
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
// seek for (i1,j1,k1) in the list of all voxels
if (visitedVoxels.find(voxel(i1,j1,k1)) == visitedVoxels.end())
{
printf("%d,",index);
lineCounter++;
}
if (lineCounter >= 8)
{
lineCounter = 0;
printf("\n");
}
index++;
}
printf("\n");
cout << endl << "Total voxels: " << voxels.size() << " Successful termination." << endl;
}
// generates the normal correction matrix for the vertices from the external file 'inputObjMesh'
void ObjMeshOffsetVoxels::generateNormalCorrectionMatrix(const string filenameCorrectionMatrix, const string inputObjMesh, const string filenameVoxelModalMatrix, const string filenameNormals)
{
cout << "Generating normal correction matrix for the external file " << inputObjMesh << endl;
// create a list of vertices in all voxels
set<gridPoint> vertices;
// insert all voxel vertices
set<voxel>::iterator aVoxel;
for (aVoxel = voxels.begin(); aVoxel != voxels.end(); ++aVoxel) // over all voxels
{
unsigned int i1,j1,k1;
i1 = aVoxel->first;
j1 = aVoxel->second;
k1 = aVoxel->third;
vertices.insert(gridPoint(i1,j1,k1));
vertices.insert(gridPoint(i1+1,j1,k1));
vertices.insert(gridPoint(i1+1,j1+1,k1));
vertices.insert(gridPoint(i1,j1+1,k1));
vertices.insert(gridPoint(i1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1,k1+1));
vertices.insert(gridPoint(i1+1,j1+1,k1+1));
vertices.insert(gridPoint(i1,j1+1,k1+1));
}
// now, vertices contains all voxel vertices with no duplications
// add all voxel vertices into a map, together with their corresponding index (i.e. serial number of a voxel vertex in the set order)
map<gridPoint,int> vertices2;
set<gridPoint>:: iterator v; // will run over all voxel vertices
int position=0;
for (v = vertices.begin(); v != vertices.end(); ++v)
{
vertices2.insert(pair<gridPoint,int>(*v,position));
//Vec3d pos = bmin + Vec3d(v->first*inc[0], v->second*inc[1], v->third*inc[2]);
//cout << "Position " << position << ": " << pos << endl;
position++;
}
// === load the voxel modal matrix
cout << "Loading the voxel modal matrix " << filenameVoxelModalMatrix << " ." << endl;
int nVoxel,r;
double * voxelModalMatrix;
ReadMatrixFromDisk_((char*)filenameVoxelModalMatrix.c_str(), &nVoxel, &r, &voxelModalMatrix);
nVoxel /= 3;
Assert_(nVoxel,vertices.size(),1);
// === load normals
FILE * fin;
OpenFile_((char*)filenameNormals.c_str(),&fin,"r");
int numNormals;
if (fscanf(fin,"%d\n",&numNormals) < 1)
printf("Warning: bad input file syntax. Unable to read the number of normals.\n");
vector<Vec3d> normals;
for(int i=0; i<numNormals; i++)
{
double nx,ny,nz;
if (fscanf(fin,"%lf %lf %lf\n",&nx,&ny,&nz) < 3)
printf("Warning: bad input file syntax. Unable to read normals.\n");
normals.push_back(Vec3d(nx,ny,nz));
}
fclose(fin);
// === generate the normal correction matrix
cout << "Loading the external file " << inputObjMesh << " ." << endl;
ObjMesh inputMesh(inputObjMesh);
cout << "Generating the normal correction matrix..." << endl;
int n = inputMesh.getNumVertices();
Assert_(n, numNormals, 2);
double * outputMatrix = (double*) malloc (sizeof(double) * 3 * n * r);
// for every vertex of the mesh, find what voxel it is in
// then find indices of the vertices of that voxel
// and compute the barycentric coordinates
// the assemble the normal matrix correction
cout << "Processing vertices of the external mesh file..." << endl;
for (unsigned int i=0; i < inputMesh.getNumVertices(); i++) // over all vertices of the mesh
{
if (i % 100 == 0)
cout << i << " " << flush;
Vec3d pos = inputMesh.getPosition(i);
unsigned int i1,j1,k1;
Vec3d relPos = pos-bmin;
// find voxel containing 'pos'
i1 = (unsigned int)(relPos[0] / inc[0]);
j1 = (unsigned int)(relPos[1] / inc[1]);
k1 = (unsigned int)(relPos[2] / inc[2]);
// compute barycentric coordinates
Vec3d w = pos - (bmin + Vec3d(i1 * inc[0], j1 * inc[1], k1 * inc[2]));
double alpha = w[0] / inc[0];
double beta = w[1] / inc[1];
double gamma = w[2] / inc[2];
// locate voxel vertices
map<gridPoint,int> :: iterator voxelVertexEntry;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+0,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 000" << endl;
return;
}
unsigned int c000 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+0,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 100" << endl;
return;
}
unsigned int c100 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+1,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 110" << endl;
return;
}
unsigned int c110 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+1,k1+0));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 010" << endl;
return;
}
unsigned int c010 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+0,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 001" << endl;
return;
}
unsigned int c001 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+0,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 101" << endl;
return;
}
unsigned int c101 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+1,j1+1,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 111" << endl;
return;
}
unsigned int c111 = voxelVertexEntry->second;
voxelVertexEntry = vertices2.find(gridPoint(i1+0,j1+1,k1+1));
if (voxelVertexEntry == vertices2.end())
{
cout << "Error: vertex " << i+1 << " at location " << pos << " doesn't have corner neighbor 011" << endl;
return;
}
unsigned int c011 = voxelVertexEntry->second;
/*
unsigned int c000 = vertices2.find(gridPoint(i1+0,j1+0,k1+0))->second;
unsigned int c100 = vertices2.find(gridPoint(i1+1,j1+0,k1+0))->second;
unsigned int c110 = vertices2.find(gridPoint(i1+1,j1+1,k1+0))->second;
unsigned int c010 = vertices2.find(gridPoint(i1+0,j1+1,k1+0))->second;
unsigned int c001 = vertices2.find(gridPoint(i1+0,j1+0,k1+1))->second;
unsigned int c101 = vertices2.find(gridPoint(i1+1,j1+0,k1+1))->second;
unsigned int c111 = vertices2.find(gridPoint(i1+1,j1+1,k1+1))->second;
unsigned int c011 = vertices2.find(gridPoint(i1+0,j1+1,k1+1))->second;
*/
/*
double f000 = (1-alpha)*(1-beta)*(1-gamma);
double f100 = (alpha)*(1-beta)*(1-gamma);
double f110 = (alpha)*(beta)*(1-gamma);
double f010 = (1-alpha)*(beta)*(1-gamma);
double f001 = (1-alpha)*(1-beta)*(gamma);
double f101 = (alpha)*(1-beta)*(gamma);
double f111 = (alpha)*(beta)*(gamma);
double f011 = (1-alpha)*(beta)*(gamma);
*/
Vec3d gradf000(1.0 / inc[0] * -(1-beta)*(1-gamma), 1.0 / inc[1] * -(1-alpha)*(1-gamma), 1.0 / inc[2] * -(1-alpha)*(1-beta));
Vec3d gradf100(1.0 / inc[0] * (1-beta)*(1-gamma), 1.0 / inc[1] * -alpha*(1-gamma), 1.0 / inc[2] * -alpha*(1-beta));
Vec3d gradf110(1.0 / inc[0] * beta*(1-gamma), 1.0 / inc[1] * alpha*(1-gamma), 1.0 / inc[2] * -alpha*beta);
Vec3d gradf010(1.0 / inc[0] * -beta*(1-gamma), 1.0 / inc[1] * (1-alpha)*(1-gamma), 1.0 / inc[2] * (1-alpha)*-beta);
Vec3d gradf001(1.0 / inc[0] * -(1-beta)*gamma, 1.0 / inc[1] * -(1-alpha)*gamma, 1.0 / inc[2] * (1-alpha)*(1-beta));
Vec3d gradf101(1.0 / inc[0] * (1-beta)*gamma, 1.0 / inc[1] * -alpha*gamma, 1.0 / inc[2] * alpha*(1-beta));
Vec3d gradf111(1.0 / inc[0] * beta*gamma, 1.0 / inc[1] * alpha*gamma, 1.0 / inc[2] * alpha*beta);
Vec3d gradf011(1.0 / inc[0] * -beta*gamma, 1.0 / inc[1] * (1-alpha)*gamma, 1.0 / inc[2] * (1-alpha)*beta);
Vec3d normal = normals[i];
for(int j=0; j<r; j++)
{
Vec3d u000(voxelModalMatrix[ELT(3*nVoxel,3*c000+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c000+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c000+2,j)]);
Vec3d u100(voxelModalMatrix[ELT(3*nVoxel,3*c100+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c100+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c100+2,j)]);
Vec3d u110(voxelModalMatrix[ELT(3*nVoxel,3*c110+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c110+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c110+2,j)]);
Vec3d u010(voxelModalMatrix[ELT(3*nVoxel,3*c010+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c010+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c010+2,j)]);
Vec3d u001(voxelModalMatrix[ELT(3*nVoxel,3*c001+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c001+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c001+2,j)]);
Vec3d u101(voxelModalMatrix[ELT(3*nVoxel,3*c101+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c101+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c101+2,j)]);
Vec3d u111(voxelModalMatrix[ELT(3*nVoxel,3*c111+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c111+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c111+2,j)]);
Vec3d u011(voxelModalMatrix[ELT(3*nVoxel,3*c011+0,j)],voxelModalMatrix[ELT(3*nVoxel,3*c011+1,j)],voxelModalMatrix[ELT(3*nVoxel,3*c011+2,j)]);
Vec3d coef(0,0,0);
coef += dot(gradf000,normal) * u000;
coef += dot(gradf100,normal) * u100;
coef += dot(gradf110,normal) * u110;
coef += dot(gradf010,normal) * u010;
coef += dot(gradf001,normal) * u001;
coef += dot(gradf101,normal) * u101;
coef += dot(gradf111,normal) * u111;
coef += dot(gradf011,normal) * u011;
outputMatrix[ELT(3*n, 3*i+0, j)] = coef[0];
outputMatrix[ELT(3*n, 3*i+1, j)] = coef[1];
outputMatrix[ELT(3*n, 3*i+2, j)] = coef[2];
}
}
cout << endl;
WriteMatrixToDisk_((char*)filenameCorrectionMatrix.c_str(), 3*n, r, outputMatrix);
free(outputMatrix);
free(voxelModalMatrix);
}
| 34.95628
| 206
| 0.608552
|
lrkk1234
|
618364aa14f73c4b730d07cf527bff4fa1021624
| 1,893
|
cpp
|
C++
|
client/src/win/win_registry.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | 1
|
2020-09-08T00:41:27.000Z
|
2020-09-08T00:41:27.000Z
|
client/src/win/win_registry.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | null | null | null |
client/src/win/win_registry.cpp
|
realrasengan/desktop
|
41213ed9efd70955bdd5872c68425868040afae2
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2019 London Trust Media Incorporated
//
// This file is part of the Private Internet Access Desktop Client.
//
// The Private Internet Access Desktop Client is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// The Private Internet Access Desktop Client is distributed in the hope that
// it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the Private Internet Access Desktop Client. If not, see
// <https://www.gnu.org/licenses/>.
#include "common.h"
#line SOURCE_FILE("win/win_registry.cpp")
#include "win_registry.h"
#include "path.h"
#include "version.h"
#include <QDir>
#include <windows.h>
#pragma comment(lib, "advapi32.lib")
namespace {
static const HKEY g_runKeyRoot = HKEY_CURRENT_USER;
static const wchar_t* g_runKeyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
static const wchar_t* g_runKeyName = L"" PIA_PRODUCT_NAME;
}
bool winLaunchAtLogin()
{
return ERROR_SUCCESS == RegGetValueW(g_runKeyRoot, g_runKeyPath, g_runKeyName, RRF_RT_ANY, NULL, NULL, NULL);
}
void winSetLaunchAtLogin(bool enable)
{
if (enable)
{
auto cmdline = QStringLiteral("\"%1\" --quiet").arg(QDir::toNativeSeparators(Path::ClientExecutable)).toStdWString();
CHECK_ERROR(RegSetKeyValueW(g_runKeyRoot, g_runKeyPath, g_runKeyName, REG_SZ, cmdline.c_str(), cmdline.size() * 2));
}
else
CHECK_ERROR_IF(error != ERROR_FILE_NOT_FOUND, RegDeleteKeyValueW(g_runKeyRoot, g_runKeyPath, g_runKeyName));
}
| 36.403846
| 125
| 0.742736
|
realrasengan
|
61837db47ebde841d5c69877c510263991fb4c80
| 5,021
|
cc
|
C++
|
xls/tools/delay_info_main.cc
|
RobSpringer/xls
|
a5521c7ecbd1a071828760cf429d74810f248681
|
[
"Apache-2.0"
] | null | null | null |
xls/tools/delay_info_main.cc
|
RobSpringer/xls
|
a5521c7ecbd1a071828760cf429d74810f248681
|
[
"Apache-2.0"
] | null | null | null |
xls/tools/delay_info_main.cc
|
RobSpringer/xls
|
a5521c7ecbd1a071828760cf429d74810f248681
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 The XLS Authors
//
// 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.
// Takes in an IR file and produces an IR file that has been run through the
// standard optimization pipeline.
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "xls/common/file/filesystem.h"
#include "xls/common/init_xls.h"
#include "xls/common/status/status_macros.h"
#include "xls/delay_model/analyze_critical_path.h"
#include "xls/delay_model/delay_estimator.h"
#include "xls/delay_model/delay_estimators.h"
#include "xls/ir/ir_parser.h"
#include "xls/ir/node_iterator.h"
#include "xls/ir/package.h"
#include "xls/scheduling/extract_stage.h"
#include "xls/scheduling/pipeline_schedule.h"
#include "xls/scheduling/pipeline_schedule.pb.h"
const char kUsage[] = R"(
Dumps delay information about an XLS function including per-node delay
information and critical-path. Example invocations:
Emit delay information about a function:
delay_info_main --delay_model=unit --entry=ENTRY IR_FILE
Emit delay information about a function including per-stage critical path
information:
delay_info_main --delay_model=unit \
--schedule_path=SCHEDULE_FILE \
--entry=ENTRY \
IR_FILE
)";
ABSL_FLAG(
std::string, top, "",
"The name of the top entity. Currently, only functions are supported. "
"Function to emit delay information about.");
ABSL_FLAG(std::string, delay_model, "",
"Delay model name to use from registry.");
ABSL_FLAG(std::string, schedule_path, "",
"Optional path to a pipeline schedule to use for emitting per-stage "
"critical paths.");
namespace xls::tools {
namespace {
absl::Status RealMain(absl::string_view input_path) {
if (input_path == "-") {
input_path = "/dev/stdin";
}
XLS_ASSIGN_OR_RETURN(std::string ir, GetFileContents(input_path));
XLS_ASSIGN_OR_RETURN(std::unique_ptr<Package> p,
Parser::ParsePackage(ir, input_path));
Function* function;
if (absl::GetFlag(FLAGS_top).empty()) {
XLS_ASSIGN_OR_RETURN(function, p->GetTopAsFunction());
} else {
XLS_ASSIGN_OR_RETURN(function, p->GetFunction(absl::GetFlag(FLAGS_top)));
}
XLS_ASSIGN_OR_RETURN(DelayEstimator * delay_estimator,
GetDelayEstimator(absl::GetFlag(FLAGS_delay_model)));
if (absl::GetFlag(FLAGS_schedule_path).empty()) {
XLS_ASSIGN_OR_RETURN(
std::vector<CriticalPathEntry> critical_path,
AnalyzeCriticalPath(function, /*clock_period_ps=*/absl::nullopt,
*delay_estimator));
std::cout << "# Critical path:\n";
std::cout << CriticalPathToString(critical_path);
std::cout << "\n";
} else {
XLS_ASSIGN_OR_RETURN(PipelineScheduleProto proto,
ParseTextProtoFile<PipelineScheduleProto>(
absl::GetFlag(FLAGS_schedule_path)));
XLS_ASSIGN_OR_RETURN(PipelineSchedule schedule,
PipelineSchedule::FromProto(function, proto));
XLS_RETURN_IF_ERROR(schedule.Verify());
for (int64_t i = 0; i < schedule.length(); ++i) {
XLS_ASSIGN_OR_RETURN(Function * stage_function,
ExtractStage(function, schedule, i));
XLS_ASSIGN_OR_RETURN(
std::vector<CriticalPathEntry> critical_path,
AnalyzeCriticalPath(stage_function, /*clock_period_ps=*/absl::nullopt,
*delay_estimator));
std::cout << absl::StrFormat("# Critical path for stage %d:\n", i);
std::cout << CriticalPathToString(critical_path);
std::cout << "\n";
}
}
std::cout << "# Delay of all nodes:\n";
for (Node* node : TopoSort(function)) {
absl::StatusOr<int64_t> delay_status =
delay_estimator->GetOperationDelayInPs(node);
if (delay_status.ok()) {
std::cout << absl::StreamFormat("%-15s : %5dps\n", node->GetName(),
delay_status.value());
} else {
std::cout << absl::StreamFormat("%-15s : <unknown>\n", node->GetName());
}
}
return absl::OkStatus();
}
} // namespace
} // namespace xls::tools
int main(int argc, char** argv) {
std::vector<absl::string_view> positional_arguments =
xls::InitXls(kUsage, argc, argv);
if (positional_arguments.empty()) {
XLS_LOG(QFATAL) << absl::StreamFormat("Expected invocation: %s <path>",
argv[0]);
}
XLS_QCHECK_OK(xls::tools::RealMain(positional_arguments[0]));
return EXIT_SUCCESS;
}
| 36.649635
| 80
| 0.673372
|
RobSpringer
|
618394454f4b8e20ac9b1032fcec69f9a2ba5913
| 1,107
|
hpp
|
C++
|
core/include/game/objects/gameobj.hpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
core/include/game/objects/gameobj.hpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
core/include/game/objects/gameobj.hpp
|
Darckore/SpaceAssault
|
287db7eff40e83fe08a34d50f617eedfaccb3a55
|
[
"MIT"
] | null | null | null |
#pragma once
#include "game/components/component.hpp"
namespace engine::world
{
class game_object
{
public:
using component_type = component;
using id_type = component_type::id_type;
using data_type = std::unordered_map<id_type, component_type*>;
public:
CLASS_SPECIALS_NOCOPY_CUSTOM(game_object);
virtual ~game_object() noexcept = default;
game_object() noexcept = default;
friend class component_store;
public:
template <game_component Component>
const Component* get_component() const noexcept
{
auto res = m_data.find(Component::type_id());
if (res == m_data.end())
{
return nullptr;
}
return static_cast<const Component*>(res->second);
}
template <game_component Component>
Component* get_component() noexcept
{
return utils::mutate(std::as_const(*this).template get_component<Component>());
}
private:
void attach_component(component_type& c) noexcept;
void remove_component(id_type id) noexcept;
void remove_all() noexcept;
private:
data_type m_data;
};
}
| 23.0625
| 85
| 0.684734
|
Darckore
|
61866e95ca20f494bed8f1ce6cc7804a37cb395d
| 3,764
|
cpp
|
C++
|
src/common/NameSpaceUtil.cpp
|
tclfs/rocketmq-client-cpp
|
ecfd7d3a598a54288817c038cb13f25c26bd370f
|
[
"Apache-2.0"
] | 314
|
2018-10-11T06:58:56.000Z
|
2022-03-22T14:03:54.000Z
|
src/common/NameSpaceUtil.cpp
|
tclfs/rocketmq-client-cpp
|
ecfd7d3a598a54288817c038cb13f25c26bd370f
|
[
"Apache-2.0"
] | 275
|
2018-11-12T03:55:44.000Z
|
2022-03-28T10:13:15.000Z
|
src/common/NameSpaceUtil.cpp
|
tclfs/rocketmq-client-cpp
|
ecfd7d3a598a54288817c038cb13f25c26bd370f
|
[
"Apache-2.0"
] | 165
|
2018-10-17T11:47:16.000Z
|
2022-01-31T12:10:19.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NameSpaceUtil.h"
#include "Logging.h"
#include "TraceContant.h"
namespace rocketmq {
bool NameSpaceUtil::isEndPointURL(string nameServerAddr) {
if (nameServerAddr.length() >= ENDPOINT_PREFIX_LENGTH && nameServerAddr.find(ENDPOINT_PREFIX) != string::npos) {
return true;
}
return false;
}
string NameSpaceUtil::formatNameServerURL(string nameServerAddr) {
auto index = nameServerAddr.find(ENDPOINT_PREFIX);
if (index != string::npos) {
LOG_DEBUG("Get Name Server from endpoint [%s]",
nameServerAddr.substr(ENDPOINT_PREFIX_LENGTH, nameServerAddr.length() - ENDPOINT_PREFIX_LENGTH).c_str());
return nameServerAddr.substr(ENDPOINT_PREFIX_LENGTH, nameServerAddr.length() - ENDPOINT_PREFIX_LENGTH);
}
return nameServerAddr;
}
string NameSpaceUtil::getNameSpaceFromNsURL(string nameServerAddr) {
LOG_DEBUG("Try to get Name Space from nameServerAddr [%s]", nameServerAddr.c_str());
string nsAddr = formatNameServerURL(nameServerAddr);
string nameSpace;
auto index = nsAddr.find(NAMESPACE_PREFIX);
if (index != string::npos) {
auto indexDot = nsAddr.find('.');
if (indexDot != string::npos && indexDot > index) {
nameSpace = nsAddr.substr(index, indexDot - index);
LOG_INFO("Get Name Space [%s] from nameServerAddr [%s]", nameSpace.c_str(), nameServerAddr.c_str());
return nameSpace;
}
}
return "";
}
bool NameSpaceUtil::checkNameSpaceExistInNsURL(string nameServerAddr) {
if (!isEndPointURL(nameServerAddr)) {
LOG_DEBUG("This nameServerAddr [%s] is not a endpoint. should not get Name Space.", nameServerAddr.c_str());
return false;
}
auto index = nameServerAddr.find(NAMESPACE_PREFIX);
if (index != string::npos) {
LOG_INFO("Find Name Space Prefix in nameServerAddr [%s]", nameServerAddr.c_str());
return true;
}
return false;
}
bool NameSpaceUtil::checkNameSpaceExistInNameServer(string nameServerAddr) {
auto index = nameServerAddr.find(NAMESPACE_PREFIX);
if (index != string::npos) {
LOG_INFO("Find Name Space Prefix in nameServerAddr [%s]", nameServerAddr.c_str());
return true;
}
return false;
}
string NameSpaceUtil::withoutNameSpace(string source, string nameSpace) {
if (!nameSpace.empty()) {
auto index = source.find(nameSpace);
if (index != string::npos) {
return source.substr(index + nameSpace.length() + NAMESPACE_SPLIT_FLAG.length(), source.length());
}
}
return source;
}
string NameSpaceUtil::withNameSpace(string source, string ns) {
if (!ns.empty()) {
return ns + NAMESPACE_SPLIT_FLAG + source;
}
return source;
}
bool NameSpaceUtil::hasNameSpace(string source, string ns) {
if (source.find(TraceContant::TRACE_TOPIC) != string::npos) {
LOG_DEBUG("Find Trace Topic [%s]", source.c_str());
return true;
}
if (!ns.empty() && source.length() >= ns.length() && source.find(ns) != string::npos) {
return true;
}
return false;
}
} // namespace rocketmq
| 35.509434
| 119
| 0.717322
|
tclfs
|
6188a7485f0c2870f925ec4c69b40c9ae44b23fa
| 1,729
|
hpp
|
C++
|
src/slave/qos_controller.hpp
|
ankurcha/mesos
|
46dc9979e9cc38d36dc7300db13af39bdfbfd52e
|
[
"Apache-2.0"
] | null | null | null |
src/slave/qos_controller.hpp
|
ankurcha/mesos
|
46dc9979e9cc38d36dc7300db13af39bdfbfd52e
|
[
"Apache-2.0"
] | 2
|
2015-09-29T12:09:44.000Z
|
2016-01-06T05:12:29.000Z
|
src/slave/qos_controller.hpp
|
ankurcha/mesos
|
46dc9979e9cc38d36dc7300db13af39bdfbfd52e
|
[
"Apache-2.0"
] | 4
|
2015-08-05T21:47:37.000Z
|
2018-08-31T23:40:03.000Z
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __SLAVE_QOS_CONTROLLER_HPP__
#define __SLAVE_QOS_CONTROLLER_HPP__
#include <mesos/slave/qos_controller.hpp>
#include <stout/lambda.hpp>
#include <process/owned.hpp>
namespace mesos {
namespace internal {
namespace slave {
// Forward declaration.
class NoopQoSControllerProcess;
// The NOOP QoS Controller is an empty stub, which returns a future
// which is never satisfied. Thus, the slave will never carry out any
// corrections.
class NoopQoSController : public mesos::slave::QoSController
{
public:
virtual ~NoopQoSController();
virtual Try<Nothing> initialize(
const lambda::function<process::Future<ResourceUsage>()>& usage);
virtual process::Future<std::list<mesos::slave::QoSCorrection>> corrections();
protected:
process::Owned<NoopQoSControllerProcess> process;
};
} // namespace slave {
} // namespace internal {
} // namespace mesos {
#endif // __SLAVE_QOS_CONTROLLER_HPP__
| 29.305085
| 80
| 0.757085
|
ankurcha
|
618e5ce63b7bcefddd54a2322eeadae477f2c2bd
| 1,103
|
cpp
|
C++
|
src/engine/src/dt_recv_decoder.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/engine/src/dt_recv_decoder.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/engine/src/dt_recv_decoder.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "dt_recv_decoder.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// ------------------------------------------------------------------------------------ //
// CRecvDecoder.
// ------------------------------------------------------------------------------------ //
CRecvDecoder::CRecvDecoder()
{
m_pTable = 0;
m_pClientSendTable = 0;
}
CClientSendProp::CClientSendProp()
{
m_pTableName = 0;
}
CClientSendProp::~CClientSendProp()
{
delete [] m_pTableName;
}
CClientSendTable::CClientSendTable()
{
}
CClientSendTable::~CClientSendTable()
{
delete [] m_SendTable.m_pNetTableName;
for ( int iProp=0; iProp < m_SendTable.m_nProps; iProp++ )
{
delete [] m_SendTable.m_pProps[iProp].m_pVarName;
delete [] m_SendTable.m_pProps[iProp].m_pExcludeDTName;
delete [] m_SendTable.m_pProps[iProp].m_pParentArrayPropName;
}
delete [] m_SendTable.m_pProps;
}
| 20.425926
| 90
| 0.534905
|
cstom4994
|
618e98efb125ea7259cf06097503c3f62ece2cc0
| 2,044
|
cpp
|
C++
|
src/vsg/vk/BufferView.cpp
|
jinpengxuan/VulkanSceneGraph
|
cf6c6815f1a35e1a4ec53f345ba367a3f72e30f2
|
[
"MIT"
] | null | null | null |
src/vsg/vk/BufferView.cpp
|
jinpengxuan/VulkanSceneGraph
|
cf6c6815f1a35e1a4ec53f345ba367a3f72e30f2
|
[
"MIT"
] | null | null | null |
src/vsg/vk/BufferView.cpp
|
jinpengxuan/VulkanSceneGraph
|
cf6c6815f1a35e1a4ec53f345ba367a3f72e30f2
|
[
"MIT"
] | null | null | null |
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
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.
</editor-fold> */
#include <vsg/core/Exception.h>
#include <vsg/io/Options.h>
#include <vsg/vk/BufferView.h>
using namespace vsg;
BufferView::BufferView(Buffer* buffer, VkFormat format, VkDeviceSize offset, VkDeviceSize range) :
_device(buffer->getDevice()),
_buffer(buffer)
{
VkBufferViewCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
createInfo.buffer = *buffer;
createInfo.format = format;
createInfo.offset = offset;
createInfo.range = range;
createInfo.pNext = nullptr;
if (VkResult result = vkCreateBufferView(*(buffer->getDevice()), &createInfo, _device->getAllocationCallbacks(), &_bufferView); result != VK_SUCCESS)
{
throw Exception{"Error: Failed to create BufferView.", result};
}
}
BufferView::~BufferView()
{
if (_bufferView)
{
vkDestroyBufferView(*_device, _bufferView, _device->getAllocationCallbacks());
}
}
| 46.454545
| 460
| 0.75636
|
jinpengxuan
|
618ebc733c97763f4d6ba283a096c0e8a2c63f45
| 16,301
|
cpp
|
C++
|
src/core/NEON/kernels/arm_gemm/kernels/a64_sgemm_12x8/a53.cpp
|
LeeHayun/ArmCL
|
e2542c9f35ca427286822cd0c9296f49914f78b0
|
[
"MIT"
] | 1
|
2018-08-02T06:49:04.000Z
|
2018-08-02T06:49:04.000Z
|
src/core/NEON/kernels/arm_gemm/kernels/a64_sgemm_12x8/a53.cpp
|
clydeliuyan/ComputeLibrary
|
e2542c9f35ca427286822cd0c9296f49914f78b0
|
[
"MIT"
] | null | null | null |
src/core/NEON/kernels/arm_gemm/kernels/a64_sgemm_12x8/a53.cpp
|
clydeliuyan/ComputeLibrary
|
e2542c9f35ca427286822cd0c9296f49914f78b0
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2017-2018 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#ifdef __aarch64__
#include <arm_neon.h>
#include "../../asmlib.hpp"
namespace arm_gemm
{
void a64_sgemm_asimd_12x8_a53(const float *Apanel, const float *Bpanel, float *Cpanel, int ablocks, int bblocks, int K)
{
const float *a_ptr = Apanel;
float *c_ptr = Cpanel;
for(int yb = 0; yb < ablocks; yb++)
{
const float *a_ptr0 = a_ptr;
const float *b_ptr = Bpanel;
for(int xb = 0; xb < bblocks; xb++)
{
a_ptr = a_ptr0;
// Fix up for odd lengths - set a flag if K is odd, but make
// sure we round up the iteration count.
int oddk = (K & 1);
int k = ((K + 1) / 2) - 1;
register float32x4_t a0 asm("v0");
register float32x4_t a1 asm("v1");
register float32x4_t b0 asm("v2");
register float32x4_t b1 asm("v3");
register float32x4_t b2 asm("v4");
register float32x4_t a0a asm("v5");
register float32x4_t a1a asm("v6");
__asm __volatile(
// Initialize result registers, load initial operands, prime prefetches.
"movi v8.4s, #0x0\n"
"ldr %q[a0], [%[a_ptr]]\n"
"movi v9.4s, #0x0\n"
"ldr %q[b0], [%[b_ptr]]\n"
"movi v10.4s, #0x0\n"
"ldr %q[a1], [%[a_ptr], #16]\n"
"movi v11.4s, #0x0\n"
"ldr %q[b1], [%[b_ptr], #16]\n"
"movi v12.4s, #0x0\n" ASM_PREFETCH("[%[b_ptr], #64]") "movi v13.4s, #0x0\n" ASM_PREFETCH("[%[a_ptr], #64]") "movi v14.4s, #0x0\n" ASM_PREFETCH("[%[b_ptr], #128]") "movi v15.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #128]") "movi v16.4s, #0x0\n" ASM_PREFETCH("[%[b_ptr], #192]") "movi v17.4s, #0x0\n" ASM_PREFETCH("[%[b_ptr], #256]") "movi v18.4s, #0x0\n"
ASM_PREFETCH("[%[a_ptr], #192]") "movi v19.4s, #0x0\n" ASM_PREFETCH("[%[b_ptr], #320]") "movi v20.4s, #0x0\n" ASM_PREFETCH("[%[a_ptr], #256]") "movi v21.4s, #0x0\n"
ASM_PREFETCH("[%[b_ptr], #384]")
"movi v22.4s, #0x0\n"
"movi v23.4s, #0x0\n"
"movi v24.4s, #0x0\n"
"movi v25.4s, #0x0\n"
"movi v26.4s, #0x0\n"
"movi v27.4s, #0x0\n"
"movi v28.4s, #0x0\n"
"movi v29.4s, #0x0\n"
"movi v30.4s, #0x0\n"
"movi v31.4s, #0x0\n"
// Skip loop if we are doing zero iterations of it.
"cbz %w[k], 4f\n"
"1:\n"
// Unroll 0
"ldr %d[b2], [%[b_ptr], #32]\n"
"nop\n"
"fmla v8.4s , %[b0].4s, %[a0].s[0]\n"
"ldr x20, [%[b_ptr], #40]\n"
"fmla v9.4s , %[b0].4s, %[a0].s[1]\n"
"subs %w[k], %w[k], #1\n"
"fmla v10.4s, %[b0].4s, %[a0].s[2]\n"
"ldr %d[a0a], [%[a_ptr], #32]\n"
"ins %[b2].d[1], x20\n"
"fmla v11.4s, %[b0].4s, %[a0].s[3]\n"
"ldr x20, [%[a_ptr], #40]\n"
"fmla v12.4s, %[b0].4s, %[a1].s[0]\n"
"fmla v13.4s, %[b0].4s, %[a1].s[1]\n"
"ldr %d[a1a], [%[a_ptr], #48]\n"
"ins %[a0a].d[1], x20\n"
"fmla v14.4s, %[b0].4s, %[a1].s[2]\n"
"ldr x20, [%[a_ptr], #56]\n"
"fmla v15.4s, %[b0].4s, %[a1].s[3]\n"
"fmla v16.4s, %[b1].4s, %[a0].s[0]\n"
"ldr %d[b0], [%[b_ptr], #48]\n"
"ins %[a1a].d[1], x20\n"
"fmla v17.4s, %[b1].4s, %[a0].s[1]\n"
"ldr x20, [%[b_ptr], #56]\n"
"fmla v18.4s, %[b1].4s, %[a0].s[2]\n"
"fmla v19.4s, %[b1].4s, %[a0].s[3]\n"
ASM_PREFETCH("[%[a_ptr], #320]")
"ins %[b0].d[1], x20\n"
"fmla v20.4s, %[b1].4s, %[a1].s[0]\n"
"fmla v21.4s, %[b1].4s, %[a1].s[1]\n"
"fmla v22.4s, %[b1].4s, %[a1].s[2]\n"
ASM_PREFETCH("[%[b_ptr], #448]")
"nop\n"
"fmla v23.4s, %[b1].4s, %[a1].s[3]\n"
"fmla v24.4s, %[b2].4s, %[a0].s[0]\n"
"fmla v25.4s, %[b2].4s, %[a0].s[1]\n"
"ldr %d[b1], [%[b_ptr], #64]\n"
"nop\n"
"fmla v26.4s, %[b2].4s, %[a0].s[2]\n"
"ldr x20, [%[b_ptr], #72]\n"
"fmla v27.4s, %[b2].4s, %[a0].s[3]\n"
"fmla v28.4s, %[b2].4s, %[a1].s[0]\n"
ASM_PREFETCH("[%[b_ptr], #512]")
"ins %[b1].d[1], x20\n"
"fmla v29.4s, %[b2].4s, %[a1].s[1]\n"
"fmla v30.4s, %[b2].4s, %[a1].s[2]\n"
"fmla v31.4s, %[b2].4s, %[a1].s[3]\n"
// Unroll 1
"ldr %d[b2], [%[b_ptr], #80]\n"
"nop\n"
"fmla v8.4s , %[b0].4s, %[a0a].s[0]\n"
"ldr x20, [%[b_ptr], #88]\n"
"fmla v9.4s , %[b0].4s, %[a0a].s[1]\n"
"fmla v10.4s, %[b0].4s, %[a0a].s[2]\n"
"ldr %d[a0], [%[a_ptr], #64]\n"
"ins %[b2].d[1], x20\n"
"fmla v11.4s, %[b0].4s, %[a0a].s[3]\n"
"ldr x20, [%[a_ptr], #72]\n"
"fmla v12.4s, %[b0].4s, %[a1a].s[0]\n"
"fmla v13.4s, %[b0].4s, %[a1a].s[1]\n"
"ldr %d[a1], [%[a_ptr], #80]\n"
"ins %[a0].d[1], x20\n"
"fmla v14.4s, %[b0].4s, %[a1a].s[2]\n"
"ldr x20, [%[a_ptr], #88]\n"
"fmla v15.4s, %[b0].4s, %[a1a].s[3]\n"
"fmla v16.4s, %[b1].4s, %[a0a].s[0]\n"
"ldr %d[b0], [%[b_ptr], #96]\n"
"ins %[a1].d[1], x20\n"
"fmla v17.4s, %[b1].4s, %[a0a].s[1]\n"
"ldr x20, [%[b_ptr], #104]\n"
"fmla v18.4s, %[b1].4s, %[a0a].s[2]\n"
"fmla v19.4s, %[b1].4s, %[a0a].s[3]\n"
"nop\n"
"ins %[b0].d[1], x20\n"
"fmla v20.4s, %[b1].4s, %[a1a].s[0]\n"
"fmla v21.4s, %[b1].4s, %[a1a].s[1]\n"
"fmla v22.4s, %[b1].4s, %[a1a].s[2]\n"
"nop\n"
"nop\n"
"fmla v23.4s, %[b1].4s, %[a1a].s[3]\n"
"fmla v24.4s, %[b2].4s, %[a0a].s[0]\n"
"fmla v25.4s, %[b2].4s, %[a0a].s[1]\n"
"ldr %d[b1], [%[b_ptr], #112]\n"
"nop\n"
"fmla v26.4s, %[b2].4s, %[a0a].s[2]\n"
"ldr x20, [%[b_ptr], #120]\n"
"fmla v27.4s, %[b2].4s, %[a0a].s[3]\n"
"add %[a_ptr], %[a_ptr], #64\n"
"fmla v28.4s, %[b2].4s, %[a1a].s[0]\n"
"add %[b_ptr], %[b_ptr], #96\n"
"nop\n"
"ins %[b1].d[1], x20\n"
"fmla v29.4s, %[b2].4s, %[a1a].s[1]\n"
"fmla v30.4s, %[b2].4s, %[a1a].s[2]\n"
"fmla v31.4s, %[b2].4s, %[a1a].s[3]\n"
"bne 1b\n"
// Branch here if K=1 or 2. Do the right thing for odd/even at the end.
"4:\n"
"cbnz %w[oddk], 2f\n"
// Detached final iteration. (even K)
"ldr %d[b2], [%[b_ptr], #32]\n"
"nop\n"
"fmla v8.4s , %[b0].4s, %[a0].s[0]\n"
"ldr x20, [%[b_ptr], #40]\n"
"fmla v9.4s , %[b0].4s, %[a0].s[1]\n"
"subs %w[k], %w[k], #1\n"
"fmla v10.4s, %[b0].4s, %[a0].s[2]\n"
"ldr %d[a0a], [%[a_ptr], #32]\n"
"ins %[b2].d[1], x20\n"
"fmla v11.4s, %[b0].4s, %[a0].s[3]\n"
"ldr x20, [%[a_ptr], #40]\n"
"fmla v12.4s, %[b0].4s, %[a1].s[0]\n"
"fmla v13.4s, %[b0].4s, %[a1].s[1]\n"
"ldr %d[a1a], [%[a_ptr], #48]\n"
"ins %[a0a].d[1], x20\n"
"fmla v14.4s, %[b0].4s, %[a1].s[2]\n"
"ldr x20, [%[a_ptr], #56]\n"
"fmla v15.4s, %[b0].4s, %[a1].s[3]\n"
"fmla v16.4s, %[b1].4s, %[a0].s[0]\n"
"ldr %d[b0], [%[b_ptr], #48]\n"
"ins %[a1a].d[1], x20\n"
"fmla v17.4s, %[b1].4s, %[a0].s[1]\n"
"ldr x20, [%[b_ptr], #56]\n"
"fmla v18.4s, %[b1].4s, %[a0].s[2]\n"
"fmla v19.4s, %[b1].4s, %[a0].s[3]\n"
"ins %[b0].d[1], x20\n"
"fmla v20.4s, %[b1].4s, %[a1].s[0]\n"
"fmla v21.4s, %[b1].4s, %[a1].s[1]\n"
"fmla v22.4s, %[b1].4s, %[a1].s[2]\n"
"nop\n"
"fmla v23.4s, %[b1].4s, %[a1].s[3]\n"
"fmla v24.4s, %[b2].4s, %[a0].s[0]\n"
"fmla v25.4s, %[b2].4s, %[a0].s[1]\n"
"ldr %d[b1], [%[b_ptr], #64]\n"
"nop\n"
"fmla v26.4s, %[b2].4s, %[a0].s[2]\n"
"ldr x20, [%[b_ptr], #72]\n"
"fmla v27.4s, %[b2].4s, %[a0].s[3]\n"
"fmla v28.4s, %[b2].4s, %[a1].s[0]\n"
"ins %[b1].d[1], x20\n"
"fmla v29.4s, %[b2].4s, %[a1].s[1]\n"
"fmla v30.4s, %[b2].4s, %[a1].s[2]\n"
"fmla v31.4s, %[b2].4s, %[a1].s[3]\n"
"ldr %d[b2], [%[b_ptr], #80]\n"
"nop\n"
"fmla v8.4s , %[b0].4s, %[a0a].s[0]\n"
"ldr x20, [%[b_ptr], #88]\n"
"fmla v9.4s , %[b0].4s, %[a0a].s[1]\n"
"fmla v10.4s, %[b0].4s, %[a0a].s[2]\n"
"ins %[b2].d[1], x20\n"
"fmla v11.4s, %[b0].4s, %[a0a].s[3]\n"
"fmla v12.4s, %[b0].4s, %[a1a].s[0]\n"
"fmla v13.4s, %[b0].4s, %[a1a].s[1]\n"
"fmla v14.4s, %[b0].4s, %[a1a].s[2]\n"
"fmla v15.4s, %[b0].4s, %[a1a].s[3]\n"
"fmla v16.4s, %[b1].4s, %[a0a].s[0]\n"
"fmla v17.4s, %[b1].4s, %[a0a].s[1]\n"
"fmla v18.4s, %[b1].4s, %[a0a].s[2]\n"
"fmla v19.4s, %[b1].4s, %[a0a].s[3]\n"
"fmla v20.4s, %[b1].4s, %[a1a].s[0]\n"
"fmla v21.4s, %[b1].4s, %[a1a].s[1]\n"
"fmla v22.4s, %[b1].4s, %[a1a].s[2]\n"
"fmla v23.4s, %[b1].4s, %[a1a].s[3]\n"
"fmla v24.4s, %[b2].4s, %[a0a].s[0]\n"
"fmla v25.4s, %[b2].4s, %[a0a].s[1]\n"
"fmla v26.4s, %[b2].4s, %[a0a].s[2]\n"
"fmla v27.4s, %[b2].4s, %[a0a].s[3]\n"
"fmla v28.4s, %[b2].4s, %[a1a].s[0]\n"
"fmla v29.4s, %[b2].4s, %[a1a].s[1]\n"
"add %[a_ptr], %[a_ptr], #64\n"
"fmla v30.4s, %[b2].4s, %[a1a].s[2]\n"
"add %[b_ptr], %[b_ptr], #96\n"
"fmla v31.4s, %[b2].4s, %[a1a].s[3]\n"
"b 3f\n"
// Detached final iteration. (odd K)
"2:\n"
"ldr %d[b2], [%[b_ptr], #32]\n"
"nop\n"
"fmla v8.4s , %[b0].4s, %[a0].s[0]\n"
"ldr x20, [%[b_ptr], #40]\n"
"fmla v9.4s , %[b0].4s, %[a0].s[1]\n"
"fmla v10.4s, %[b0].4s, %[a0].s[2]\n"
"ins %[b2].d[1], x20\n"
"fmla v11.4s, %[b0].4s, %[a0].s[3]\n"
"fmla v12.4s, %[b0].4s, %[a1].s[0]\n"
"fmla v13.4s, %[b0].4s, %[a1].s[1]\n"
"fmla v14.4s, %[b0].4s, %[a1].s[2]\n"
"fmla v15.4s, %[b0].4s, %[a1].s[3]\n"
"fmla v16.4s, %[b1].4s, %[a0].s[0]\n"
"fmla v17.4s, %[b1].4s, %[a0].s[1]\n"
"fmla v18.4s, %[b1].4s, %[a0].s[2]\n"
"fmla v19.4s, %[b1].4s, %[a0].s[3]\n"
"fmla v20.4s, %[b1].4s, %[a1].s[0]\n"
"fmla v21.4s, %[b1].4s, %[a1].s[1]\n"
"fmla v22.4s, %[b1].4s, %[a1].s[2]\n"
"fmla v23.4s, %[b1].4s, %[a1].s[3]\n"
"fmla v24.4s, %[b2].4s, %[a0].s[0]\n"
"fmla v25.4s, %[b2].4s, %[a0].s[1]\n"
"fmla v26.4s, %[b2].4s, %[a0].s[2]\n"
"fmla v27.4s, %[b2].4s, %[a0].s[3]\n"
"fmla v28.4s, %[b2].4s, %[a1].s[0]\n"
"fmla v29.4s, %[b2].4s, %[a1].s[1]\n"
"add %[a_ptr], %[a_ptr], #32\n"
"fmla v30.4s, %[b2].4s, %[a1].s[2]\n"
"add %[b_ptr], %[b_ptr], #48\n"
"fmla v31.4s, %[b2].4s, %[a1].s[3]\n"
// Common tail
"3:\n"
"str q8, [%[c_ptr]]\n"
"str q16, [%[c_ptr], #16]\n"
"str q24, [%[c_ptr], #32]\n"
"str q9, [%[c_ptr], #48]\n"
"str q17, [%[c_ptr], #64]\n"
"str q25, [%[c_ptr], #80]\n"
"str q10, [%[c_ptr], #96]\n"
"str q18, [%[c_ptr], #112]\n"
"str q26, [%[c_ptr], #128]\n"
"str q11, [%[c_ptr], #144]\n"
"str q19, [%[c_ptr], #160]\n"
"str q27, [%[c_ptr], #176]\n"
"str q12, [%[c_ptr], #192]\n"
"str q20, [%[c_ptr], #208]\n"
"str q28, [%[c_ptr], #224]\n"
"str q13, [%[c_ptr], #240]\n"
"str q21, [%[c_ptr], #256]\n"
"str q29, [%[c_ptr], #272]\n"
"str q14, [%[c_ptr], #288]\n"
"str q22, [%[c_ptr], #304]\n"
"str q30, [%[c_ptr], #320]\n"
"str q15, [%[c_ptr], #336]\n"
"str q23, [%[c_ptr], #352]\n"
"str q31, [%[c_ptr], #368]\n"
"add %[c_ptr], %[c_ptr], #384\n"
:
[a_ptr] "+r"(a_ptr), [b_ptr] "+r"(b_ptr), [c_ptr] "+r"(c_ptr),
[a0] "+w"(a0), [a1] "+w"(a1), [a0a] "+w"(a0a), [a1a] "+w"(a1a),
[b0] "+w"(b0), [b1] "+w"(b1), [b2] "+w"(b2), [k] "+r"(k)
: [oddk] "r"(oddk)
: "x20", "x21", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18",
"v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "cc");
}
}
}
} // namespace arm_gemm
#endif
| 44.782967
| 212
| 0.363843
|
LeeHayun
|
618fb4c9310059308c70d02e0f1564c2986ced21
| 1,153
|
cpp
|
C++
|
gym/102784/C.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | 1
|
2021-07-16T19:59:39.000Z
|
2021-07-16T19:59:39.000Z
|
gym/102784/C.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
gym/102784/C.cpp
|
albexl/codeforces-gym-submissions
|
2a51905c50fcf5d7f417af81c4c49ca5217d0753
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <random>
#include <chrono>
using namespace std;
using namespace __gnu_pbds;
#define endl '\n'
typedef long long ll;
typedef pair<int, int> pii;
// typedef tree<int, null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// template<typename T>
// static T randint(T lo, T hi){
// return uniform_int_distribution<T>(lo, hi)(rng);
// }
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
// freopen("settling.in", "r", stdin);
// freopen("settling.out", "w", stdout);
int n;
cin >> n;
ll ans = 0;
map<string, ll> mp;
for(int i = 0; i < n; i++){
string s;
ll x;
cin >> s >> x;
mp[s] = x;
}
int h, k;
cin >> h >> k;
vector<ll> v(h);
for(int i = 0; i < h; i++){
int sz;
cin >> sz;
ll cnt = 0;
while(sz--){
string x;
ll y;
cin >> x >> y;
cnt += mp[x] * y;
}
v[i] = cnt;
}
sort(v.rbegin(), v.rend());
for(int i = 0; i < k; i++)
ans += v[i];
cout << ans << endl;
return 0;
}
| 17.208955
| 102
| 0.588899
|
albexl
|
619086d3839bae0098a9d31e45062209a4d095e8
| 1,056
|
cpp
|
C++
|
src/main.cpp
|
raichea/SJR-PixelStick
|
462e7b29b54a68d7a4b4727fd5bcd0b85656ea25
|
[
"MIT"
] | 1
|
2022-01-20T16:26:02.000Z
|
2022-01-20T16:26:02.000Z
|
src/main.cpp
|
raichea/SJR-PixelStick
|
462e7b29b54a68d7a4b4727fd5bcd0b85656ea25
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
raichea/SJR-PixelStick
|
462e7b29b54a68d7a4b4727fd5bcd0b85656ea25
|
[
"MIT"
] | 1
|
2022-01-20T16:26:04.000Z
|
2022-01-20T16:26:04.000Z
|
#include "pixelstick.h"
void initConfig();
void initLeds();
void initWifi();
// void checkWifi();
void initWebserver();
void serviceClient();
void initWebSocket();
void serviceSocket();
void initOTA();
void serviceOTA();
void serviceLeds();
void checkBattery();
void checkSwitch();
void setup()
{
Serial.begin(115200);
while (!Serial) // wait for serial port to connect.
;
// delay(3000);
// Serial.setDebugOutput(true); // Get debug info from wifi library (also enables printf())
Serial.println(F("Starting setup"));
pinMode(USER_SWITCH, INPUT_PULLUP);
LittleFS.begin();
initConfig(); // Get the config data
initLeds(); // Set the LEDs up and tell the user we're alive
initWifi(); // Start the WiFi - default is AP mode, press user switch during boot for client mode
initOTA(); // Set up OTA
initWebSocket(); // Start the WebSocket server
initWebserver(); // Start the web server
}
void loop()
{
checkSwitch();
checkBattery();
serviceClient();
serviceSocket();
serviceOTA();
serviceLeds();
}
| 24.55814
| 104
| 0.680871
|
raichea
|
6191601f1f0d7e9cd410816b064fd4ceceddeb1a
| 6,270
|
cpp
|
C++
|
test/hxArrayTest.cpp
|
adrianjohnston345/hatchlingplatform
|
6113b84a0dcb944c94f6e95aa3f1b92fab1f9276
|
[
"Apache-2.0"
] | 4
|
2019-11-27T00:38:56.000Z
|
2020-04-19T05:32:01.000Z
|
test/hxArrayTest.cpp
|
adrianjohnston345/hatchlingplatform
|
6113b84a0dcb944c94f6e95aa3f1b92fab1f9276
|
[
"Apache-2.0"
] | 1
|
2021-08-06T21:30:50.000Z
|
2021-08-06T21:30:50.000Z
|
test/hxArrayTest.cpp
|
adrianjohnston345/hatchlingplatform
|
6113b84a0dcb944c94f6e95aa3f1b92fab1f9276
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017-2019 Adrian Johnston
// Copyright 2017 Leap Motion
#include <hx/hatchling.h>
#include <hx/hxArray.h>
#include <hx/hxStockpile.h>
#include <hx/hxTest.h>
HX_REGISTER_FILENAME_HASH
// ----------------------------------------------------------------------------
static class hxArrayTest* s_hxTestCurrent = hxnull;
class hxArrayTest :
public testing::Test
{
public:
struct TestObject {
TestObject() {
++s_hxTestCurrent->m_constructed;
id = s_hxTestCurrent->m_nextId--;
constructor = 0;
}
TestObject(void*) {
++s_hxTestCurrent->m_constructed;
id = s_hxTestCurrent->m_nextId--;
constructor = 1;
}
TestObject(void*, char*) {
++s_hxTestCurrent->m_constructed;
id = s_hxTestCurrent->m_nextId--;
constructor = 2;
}
TestObject(void*, char*, int*) {
++s_hxTestCurrent->m_constructed;
id = s_hxTestCurrent->m_nextId--;
constructor = 3;
}
TestObject(const TestObject& rhs) {
++s_hxTestCurrent->m_constructed;
id = rhs.id;
constructor = rhs.constructor;
}
explicit TestObject(int32_t x) {
hxAssert(x >= 0); // User supplied IDs are positive
++s_hxTestCurrent->m_constructed;
id = x;
constructor = 0;
}
~TestObject() {
++s_hxTestCurrent->m_destructed;
id = ~0u;
}
void operator=(const TestObject& rhs) { id = rhs.id; }
void operator=(int32_t x) { id = x; }
bool operator==(const TestObject& rhs) const { return id == rhs.id; }
bool operator==(int32_t x) const { return id == x; }
int32_t id;
int32_t constructor;
};
hxArrayTest() {
hxAssert(s_hxTestCurrent == hxnull);
m_constructed = 0;
m_destructed = 0;
m_nextId = -1;
s_hxTestCurrent = this;
}
~hxArrayTest() {
s_hxTestCurrent = 0;
}
bool CheckTotals(int32_t total) const {
return m_constructed == total && m_destructed == total;
}
int32_t m_constructed;
int32_t m_destructed;
int32_t m_nextId;
};
// ----------------------------------------------------------------------------
TEST_F(hxArrayTest, Null) {
{
TestObject to0;
TestObject to1;
ASSERT_EQ(to0.id, -1);
ASSERT_EQ(to1.id, -2);
}
ASSERT_TRUE(CheckTotals(2));
}
TEST_F(hxArrayTest, EmptyFull) {
hxArray<TestObject, hxAllocatorDynamicCapacity> a;
ASSERT_TRUE(a.empty());
ASSERT_TRUE(a.full());
a.reserve(1);
ASSERT_TRUE(a.empty());
ASSERT_TRUE(!a.full());
a.push_back(TestObject());
ASSERT_TRUE(!a.empty());
ASSERT_TRUE(a.full());
a.pop_back();
ASSERT_TRUE(a.empty());
ASSERT_TRUE(!a.full());
}
TEST_F(hxArrayTest, Allocators) {
hxArray<TestObject> objsDynamic;
objsDynamic.reserve(10u);
hxArray<TestObject, 10u> objsStatic;
ASSERT_EQ(objsDynamic.size(), 0u);
ASSERT_EQ(objsStatic.size(), 0u);
objsDynamic.push_back(TestObject(20));
objsDynamic.push_back(TestObject(21));
objsStatic.push_back(TestObject(20));
objsStatic.push_back(TestObject(21));
ASSERT_EQ(objsDynamic.size(), 2u);
ASSERT_EQ(objsDynamic[0], 20);
ASSERT_EQ(objsDynamic[1], 21);
ASSERT_EQ(objsStatic.size(), 2u);
ASSERT_EQ(objsStatic[0], 20);
ASSERT_EQ(objsStatic[1], 21);
objsDynamic.clear();
objsStatic.clear();
ASSERT_TRUE(CheckTotals(8));
}
TEST_F(hxArrayTest, Iteration) {
{
static const int32_t nums[3] = { 21, 22, 23 };
hxArray<TestObject, 10u> objs;
objs.push_back(TestObject(nums[0]));
objs.push_back(TestObject(nums[1]));
objs.push_back(TestObject(nums[2]));
const hxArray<TestObject, 10u>& cobjs = objs;
int32_t counter = 0;
for (hxArray<TestObject, 10u>::iterator it = objs.begin(); it != objs.end(); ++it) {
ASSERT_EQ(it->id, objs[counter].id);
ASSERT_EQ(it->id, nums[counter]);
++counter;
}
counter = 0;
for (hxArray<TestObject, 10u>::const_iterator it = cobjs.begin();
it != cobjs.end(); ++it) {
ASSERT_EQ(it->id, objs[counter].id);
ASSERT_EQ(it->id, nums[counter]);
++counter;
}
ASSERT_EQ(objs.front(), nums[0]);
ASSERT_EQ(objs.back(), nums[2]);
ASSERT_EQ(cobjs.front(), nums[0]);
ASSERT_EQ(cobjs.back(), nums[2]);
}
ASSERT_TRUE(CheckTotals(6));
}
TEST_F(hxArrayTest, Modification) {
{
static const int32_t nums[5] = { 91, 92, 93, 94, 95 };
hxArray<TestObject> objs;
objs.assign(nums, nums + (sizeof nums / sizeof *nums));
ASSERT_EQ(objs.capacity(), 5u);
ASSERT_EQ(objs.size(), 5u);
// 91, 92, 93, 94
objs.pop_back();
objs.pop_back();
objs.pop_back();
TestObject to;
objs.push_back(to);
objs.push_back((const TestObject&)to);
::new (objs.emplace_back_unconstructed()) TestObject;
// 91, 92, -1, -2, -3
objs.erase_unordered(1);
// 91, -2, -1
ASSERT_EQ(objs[0].id, 91);
ASSERT_EQ(objs[1].id, -2);
ASSERT_EQ(objs[2].id, -1);
}
ASSERT_TRUE(CheckTotals(9));
}
TEST_F(hxArrayTest, Resizing) {
{
static const int32_t nums[5] = { 51, 52, 53, 54, 55 };
hxArray<TestObject> objs;
objs.reserve(10);
objs.assign(nums);
objs.resize(3);
ASSERT_EQ(objs.size(), 3u);
ASSERT_EQ(objs[0].id, 51);
ASSERT_EQ(objs[2].id, 53);
objs.resize(4u);
ASSERT_EQ(objs.size(), 4u);
ASSERT_EQ(objs[0].id, 51);
ASSERT_EQ(objs[2].id, 53);
ASSERT_EQ(objs[3].id, -1);
ASSERT_EQ(objs.capacity(), 10u);
objs.resize(10u);
ASSERT_EQ(objs.size(), 10u);
ASSERT_EQ(objs[9].id, -7);
ASSERT_FALSE(objs.empty());
objs.clear();
ASSERT_EQ(objs.size(), 0u);
ASSERT_TRUE(objs.empty());
ASSERT_EQ(objs.capacity(), 10u);
}
ASSERT_TRUE(CheckTotals(12));
}
TEST_F(hxArrayTest, Assignment) {
{
hxArray<TestObject> objs;
objs.reserve(1);
TestObject to;
to.id = 67;
objs.push_back(to);
hxArray<TestObject> objs2;
objs2 = objs; // Assign to same type
hxArray<TestObject, 1> objs3;
objs3 = objs; // Assign to different type
hxArray<TestObject> objs4(objs); // Construct from same type
hxArray<TestObject, 1> objs5(objs); // Construct from different type
ASSERT_EQ(objs2.size(), 1u);
ASSERT_EQ(objs3.size(), 1u);
ASSERT_EQ(objs4.size(), 1u);
ASSERT_EQ(objs5.size(), 1u);
ASSERT_EQ(objs2[0].id, 67);
ASSERT_EQ(objs3[0].id, 67);
ASSERT_EQ(objs4[0].id, 67);
ASSERT_EQ(objs5[0].id, 67);
}
ASSERT_TRUE(CheckTotals(6));
}
TEST(hxArrayTest, Stockpile) {
hxStockpile<int, 3> pile;
for (int i = 4; i--;) {
pile.push_back_atomic(7);
}
ASSERT_EQ(pile.size(), 3);
void* p = pile.emplace_back_atomic();
ASSERT_EQ(p, hxnull);
}
| 21.546392
| 86
| 0.649601
|
adrianjohnston345
|
619412378592dbedbcb0fc9f2d2b901f21a14d62
| 2,757
|
cpp
|
C++
|
src/examples/games/snake/main.cpp
|
TheMrButcher/opengl_lessons
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 1
|
2016-10-25T21:15:16.000Z
|
2016-10-25T21:15:16.000Z
|
src/examples/games/snake/main.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 375
|
2016-06-04T11:27:40.000Z
|
2019-04-14T17:11:09.000Z
|
src/examples/games/snake/main.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | null | null | null |
#include <gamebase/Gamebase.h>
using namespace gamebase;
using namespace std;
class MyApp : public App
{
void load()
{
randomize();
record = 0;
restart();
connect(restartButton, restart);
timer.setPeriod(0.2);
connect(timer, step);
}
void restart()
{
banana.hide();
grapes.hide();
kiwi.hide();
portalIn.hide();
portalOut.hide();
gameoverLabel.hide();
head = IntVec2(7, 7);
dir = IntVec2(1, 0);
timer.start();
score = 0;
scoreLabel << 0;
circles.clear();
auto circle = circles.load("snake/Circle.json", 7 * 32 - 224, 7 * 32 - 224);
tailId = circle.id();
placeApple();
}
void process(Input input)
{
using namespace gamebase::InputKey;
if (input.pressed(Right))
dir = IntVec2(1, 0);
if (input.pressed(Left))
dir = IntVec2(-1, 0);
if (input.pressed(Up))
dir = IntVec2(0, 1);
if (input.pressed(Down))
dir = IntVec2(0, -1);
}
void step()
{
auto newHead = head + dir;
if (newHead.x < 0 || newHead.x > 14 || newHead.y < 0 || newHead.y > 14)
{
timer.stop();
gameoverLabel.show();
return;
}
Vec2 v(newHead.x * 32 - 224, newHead.y * 32 - 224);
auto circle = circles.load<GameObj>("snake/Circle.json", v);
auto box = circle.box();
if (circles.find(box).size() > 1)
{
timer.stop();
gameoverLabel.show();
return;
}
if (box.intersects(apple))
{
score++;
if (score > record)
{
record = score;
recordLabel << record;
}
placeApple();
}
else
{
circles.remove(tailId);
tailId++;
}
head = newHead;
scoreLabel << score;
}
void placeApple()
{
for (;;)
{
int x = randomInt(0, 14);
int y = randomInt(0, 14);
Vec2 center(x * 32 - 224, y * 32 - 224);
apple.setPos(center);
if (circles.find(apple.box()).empty())
return;
}
}
FromDesign(GameObj, apple);
FromDesign(GameObj, banana);
FromDesign(GameObj, grapes);
FromDesign(GameObj, kiwi);
FromDesign(GameObj, portalIn);
FromDesign(GameObj, portalOut);
LayerFromDesign(void, circles);
FromDesign(Button, restartButton);
FromDesign(Label, scoreLabel);
FromDesign(Label, recordLabel);
FromDesign(Label, gameoverLabel);
Timer timer;
int score;
int record;
IntVec2 head;
IntVec2 dir;
int tailId;
};
int main(int argc, char** argv)
{
MyApp app;
app.setConfig("Config.json");
app.setDesign("snake/Design.json");
if (!app.init(&argc, argv))
return 1;
app.run();
return 0;
}
| 19.692857
| 78
| 0.543707
|
TheMrButcher
|
619519a4395822901587a5c74f751b5657e97d0a
| 12,329
|
hpp
|
C++
|
hpx/runtime/actions/transfer_base_action.hpp
|
picanumber/hpx
|
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
|
[
"BSL-1.0"
] | null | null | null |
hpx/runtime/actions/transfer_base_action.hpp
|
picanumber/hpx
|
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
|
[
"BSL-1.0"
] | null | null | null |
hpx/runtime/actions/transfer_base_action.hpp
|
picanumber/hpx
|
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2007-2017 Hartmut Kaiser
// Copyright (c) 2011 Bryce Lelbach
// Copyright (c) 2011-2016 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/// \file transfer_action.hpp
#ifndef HPX_RUNTIME_ACTIONS_TRANSFER_BASE_ACTION_HPP
#define HPX_RUNTIME_ACTIONS_TRANSFER_BASE_ACTION_HPP
#include <hpx/config/defines.hpp>
#if defined(HPX_HAVE_NETWORKING)
#include <hpx/runtime/actions_fwd.hpp>
#include <hpx/assertion.hpp>
#include <hpx/runtime/actions/action_support.hpp>
#include <hpx/runtime/actions/base_action.hpp>
#include <hpx/runtime/actions/detail/invocation_count_registry.hpp>
#include <hpx/runtime/components/pinned_ptr.hpp>
#include <hpx/serialization/input_archive.hpp>
#include <hpx/serialization/output_archive.hpp>
#include <hpx/serialization/unique_ptr.hpp>
#include <hpx/traits/action_does_termination_detection.hpp>
#include <hpx/traits/action_message_handler.hpp>
#include <hpx/traits/action_priority.hpp>
#include <hpx/traits/action_schedule_thread.hpp>
#include <hpx/traits/action_serialization_filter.hpp>
#include <hpx/traits/action_stacksize.hpp>
#include <hpx/traits/action_was_object_migrated.hpp>
#include <hpx/util/get_and_reset_value.hpp>
#include <hpx/util/serialize_exception.hpp>
#include <hpx/datastructures/tuple.hpp>
#if HPX_HAVE_ITTNOTIFY != 0 && !defined(HPX_HAVE_APEX)
#include <hpx/concurrency/itt_notify.hpp>
#endif
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <type_traits>
#include <utility>
namespace hpx { namespace actions
{
///////////////////////////////////////////////////////////////////////////
// If one or more arguments of the action are non-default-constructible,
// the transfer_action does not store the argument tuple directly but a
// unique_ptr to the tuple instead.
namespace detail
{
template <typename Args>
struct argument_holder
{
argument_holder() = default;
explicit argument_holder(Args && args)
: data_(new Args(std::move(args)))
{}
template <typename ... Ts>
argument_holder(Ts && ... ts)
: data_(new Args(std::forward<Ts>(ts)...))
{}
template <typename Archive>
void serialize(Archive& ar, unsigned int const)
{
ar & data_;
}
HPX_HOST_DEVICE HPX_FORCEINLINE
Args& data()
{
HPX_ASSERT(!!data_);
return *data_;
}
#if defined(HPX_DISABLE_ASSERTS) || defined(BOOST_DISABLE_ASSERTS) || defined(NDEBUG)
constexpr HPX_HOST_DEVICE HPX_FORCEINLINE
Args const& data() const
{
return *data_;
}
#else
HPX_HOST_DEVICE HPX_FORCEINLINE
Args const& data() const
{
HPX_ASSERT(!!data_);
return *data_;
}
#endif
private:
std::unique_ptr<Args> data_;
};
}
}}
namespace hpx { namespace util
{
template <std::size_t I, typename Args>
constexpr HPX_HOST_DEVICE HPX_FORCEINLINE
typename util::tuple_element<I, Args>::type&
get(hpx::actions::detail::argument_holder<Args>& t)
{
return util::tuple_element<I, Args>::get(t.data());
}
template <std::size_t I, typename Args>
constexpr HPX_HOST_DEVICE HPX_FORCEINLINE
typename util::tuple_element<I, Args>::type const&
get(hpx::actions::detail::argument_holder<Args> const& t)
{
return util::tuple_element<I, Args>::get(t.data());
}
template <std::size_t I, typename Args>
constexpr HPX_HOST_DEVICE HPX_FORCEINLINE
typename util::tuple_element<I, Args>::type&&
get(hpx::actions::detail::argument_holder<Args>&& t)
{
return std::forward<typename util::tuple_element<I, Args>::type>(
util::get<I>(t.data()));
}
template <std::size_t I, typename Args>
constexpr HPX_HOST_DEVICE HPX_FORCEINLINE
typename util::tuple_element<I, Args>::type const&&
get(hpx::actions::detail::argument_holder<Args> const&& t)
{
return std::forward<
typename util::tuple_element<I, Args>::type const
>(util::get<I>(t.data()));
}
}}
namespace hpx { namespace actions
{
///////////////////////////////////////////////////////////////////////////
template <typename Action>
struct transfer_base_action : base_action_data
{
public:
HPX_NON_COPYABLE(transfer_base_action);
public:
typedef typename Action::component_type component_type;
typedef typename Action::derived_type derived_type;
typedef typename Action::result_type result_type;
typedef typename Action::arguments_type arguments_base_type;
typedef typename std::conditional<
std::is_constructible<arguments_base_type>::value,
arguments_base_type,
detail::argument_holder<arguments_base_type>
>::type arguments_type;
typedef typename Action::continuation_type continuation_type;
// This is the priority value this action has been instantiated with
// (statically). This value might be different from the priority member
// holding the runtime value an action has been created with
HPX_STATIC_CONSTEXPR threads::thread_priority priority_value =
traits::action_priority<Action>::value;
// This is the stacksize value this action has been instantiated with
// (statically). This value might be different from the stacksize member
// holding the runtime value an action has been created with
HPX_STATIC_CONSTEXPR threads::thread_stacksize stacksize_value =
traits::action_stacksize<Action>::value;
typedef typename Action::direct_execution direct_execution;
// construct an empty transfer_action to avoid serialization overhead
transfer_base_action() = default;
// construct an action from its arguments
template <typename... Ts>
explicit transfer_base_action(Ts&&... vs)
: base_action_data(threads::thread_priority_default,
threads::thread_stacksize_default)
, arguments_(std::forward<Ts>(vs)...)
{}
template <typename ...Ts>
transfer_base_action(threads::thread_priority priority, Ts&&... vs)
: base_action_data(priority, threads::thread_stacksize_default)
, arguments_(std::forward<Ts>(vs)...)
{}
//
~transfer_base_action() noexcept override
{
detail::register_action<derived_type>::instance.instantiate();
}
public:
/// retrieve component type
static int get_static_component_type()
{
return derived_type::get_component_type();
}
private:
/// The function \a get_component_type returns the \a component_type
/// of the component this action belongs to.
int get_component_type() const override
{
return derived_type::get_component_type();
}
/// The function \a get_action_name returns the name of this action
/// (mainly used for debugging and logging purposes).
char const* get_action_name() const override
{
return detail::get_action_name<derived_type>();
}
/// The function \a get_serialization_id returns the id which has been
/// associated with this action (mainly used for serialization purposes).
std::uint32_t get_action_id() const override
{
return detail::get_action_id<derived_type>();
}
#if HPX_HAVE_ITTNOTIFY != 0 && !defined(HPX_HAVE_APEX)
/// The function \a get_action_name_itt returns the name of this action
/// as a ITT string_handle
util::itt::string_handle const& get_action_name_itt() const override
{
return detail::get_action_name_itt<derived_type>();
}
#endif
/// The function \a get_action_type returns whether this action needs
/// to be executed in a new thread or directly.
action_flavor get_action_type() const override
{
return derived_type::get_action_type();
}
/// Return whether the embedded action is part of termination detection
bool does_termination_detection() const override
{
return traits::action_does_termination_detection<derived_type>::call();
}
/// Return whether the given object was migrated
std::pair<bool, components::pinned_ptr>
was_object_migrated(hpx::naming::gid_type const& id,
naming::address::address_type lva) override
{
return traits::action_was_object_migrated<derived_type>::call(id, lva);
}
/// Return a pointer to the filter to be used while serializing an
/// instance of this action type.
serialization::binary_filter* get_serialization_filter(
parcelset::parcel const& p) const override
{
return traits::action_serialization_filter<derived_type>::call(p);
}
/// Return a pointer to the message handler to be used for this action.
parcelset::policies::message_handler* get_message_handler(
parcelset::parcelhandler* ph, parcelset::locality const& loc,
parcelset::parcel const& p) const override
{
return traits::action_message_handler<derived_type>::
call(ph, loc, p);
}
public:
/// retrieve the N's argument
template <std::size_t N>
constexpr inline
typename util::tuple_element<N, arguments_type>::type const&
get() const
{
return util::get<N>(arguments_);
}
/// Extract the current invocation count for this action
static std::int64_t get_invocation_count(bool reset)
{
return util::get_and_reset_value(invocation_count_, reset);
}
// serialization support
// loading ...
void load_base(hpx::serialization::input_archive & ar)
{
ar >> arguments_;
this->base_action_data::load_base(ar);
}
// saving ...
void save_base(hpx::serialization::output_archive & ar)
{
ar << arguments_;
this->base_action_data::save_base(ar);
}
protected:
arguments_type arguments_;
private:
static std::atomic<std::int64_t> invocation_count_;
protected:
static void increment_invocation_count()
{
++invocation_count_;
}
};
template <typename Action>
std::atomic<std::int64_t>
transfer_base_action<Action>::invocation_count_(0);
namespace detail
{
template <typename Action>
void register_remote_action_invocation_count(
invocation_count_registry& registry)
{
registry.register_class(
hpx::actions::detail::get_action_name<Action>(),
&transfer_base_action<Action>::get_invocation_count
);
}
}
///////////////////////////////////////////////////////////////////////////
template <std::size_t N, typename Action>
constexpr inline typename util::tuple_element<
N, typename transfer_action<Action>::arguments_type
>::type const& get(transfer_base_action<Action> const& args)
{
return args.template get<N>();
}
}}
#if defined(HPX_HAVE_PARCELPORT_ACTION_COUNTERS)
#include <hpx/runtime/parcelset/detail/per_action_data_counter_registry.hpp>
namespace hpx { namespace parcelset { namespace detail
{
/// \cond NOINTERNAL
template <typename Action>
void register_per_action_data_counter_types(
per_action_data_counter_registry& registry)
{
registry.register_class(
hpx::actions::detail::get_action_name<Action>()
);
}
/// \endcond
}}}
#endif
#endif
#endif
| 33.594005
| 85
| 0.631357
|
picanumber
|
619788a04d01038851f426d457bf9232ae750ad1
| 8,802
|
cpp
|
C++
|
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwp_emac.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | null | null | null |
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwp_emac.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | null | null | null |
features/netsocket/emac-drivers/TARGET_UNISOC_EMAC/uwp_emac.cpp
|
caixue901102/mbed-os
|
483833a8d4612845408fea5b1986d20ab8428580
|
[
"Apache-2.0"
] | 4
|
2018-12-10T12:03:54.000Z
|
2019-01-26T02:46:40.000Z
|
#include <stdlib.h>
#include "mbed_shared_queues.h"
#include "netsocket/nsapi_types.h"
#include "lwip/arch.h"
#include "debug.h"
#include "uwp_emac.h"
#include "uwp_wifi_main.h"
#include "sipc.h"
#include "uwp_sys_wrapper.h"
#include "uwp_buf_mgmt.h"
// TODO:need confirm
#define UWP_HWADDR_SIZE (6)
#define UWP_ETH_MTU_SIZE 1500
#define UWP_ETH_IF_NAME "st"
#define RX_PRIORITY (osPriorityNormal)
#define TX_PRIORITY (osPriorityNormal)
#define PHY_PRIORITY (osPriorityNormal)
extern void *packet_rx_queue;
UWP_EMAC::UWP_EMAC()
{
}
/**
* This function should do the actual transmission of the packet. The packet is
* contained in the memory buffer chain that is passed to the function.
*
* @param buf the MAC packet to send (e.g. IP packet including MAC addresses and type)
* @return true if the packet could be sent
* false value if the packet couldn't be sent
*
* @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
* strange results. You might consider waiting for space in the DMA queue
* to become availale since the stack doesn't retry to send a packet
* dropped because of memory failure (except for the TCP timers).
*/
bool UWP_EMAC::link_out(emac_mem_buf_t *buf)
{
#if 1
emac_mem_buf_t *q, *p = buf;
u32_t actual_txlen = 0;
u8_t *data;
u8_t *pos;
//struct pbuf *p_init = (struct pbuf *)buf;
LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output enter, p:%08x\n", p));
#if ETH_PAD_SIZE
//pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
data = (u8_t *)malloc(1530);
pos = data+16;
//printf("TXBUFF:%p\r\n",data);
if(data == NULL){
LWIP_DEBUGF(NETIF_DEBUG, ("rda91h_low_level_output, no PKT buf\r\n"));
memory_manager->free(buf);//SYS_ARCH_DEC(p_init->ref, 1);
return false;
}
for(q = p; q != NULL; q = memory_manager->get_next(q))
{
/* Send the data from the pbuf to the interface, one pbuf at a
time. The size of the data in each pbuf is kept in the ->len
variable. */
memcpy(pos, memory_manager->get_ptr(q), memory_manager->get_len(q));//reserve wid header length
actual_txlen += memory_manager->get_len(q);
pos += memory_manager->get_len(q);
if(actual_txlen > 1514 || actual_txlen > memory_manager->get_total_len(p))
{
LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output err, actual_txlen:%d, tot_len%d\n", actual_txlen, memory_manager->get_total_len(p)));
memory_manager->free(buf);//SYS_ARCH_DEC(p_init->ref, 1);
return false;
}
}
/* Signal rda5996 that packet should be sent */
if(actual_txlen == memory_manager->get_total_len(p))
{
uwp_mgmt_tx(data,actual_txlen);
#if ETH_PAD_SIZE
//pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
//LINK_STATS_INC(link.xmit);
memory_manager->free(buf);//SYS_ARCH_DEC(p_init->ref, 1);
return true;
}
LWIP_DEBUGF(NETIF_DEBUG, ("low_level_output pkt len mismatch, actual_txlen:%d, tot_len%d\n",
actual_txlen, memory_manager->get_total_len(p)));
memory_manager->free(buf);//SYS_ARCH_DEC(p_init->ref, 1);
#endif
return false;
}
/**
* Should allocate a contiguous memory buffer and transfer the bytes of the incoming
* packet to the buffer.
*
* @param buf If a frame was received and the memory buffer allocation was successful, a memory
* buffer filled with the received packet (including MAC header)
* @return negative value when no more frames,
* zero when frame is received
*/
emac_mem_buf_t * UWP_EMAC::low_level_input(uint8_t *data, int len)
{
emac_mem_buf_t *p, *q;
u16_t index = 0;
LWIP_DEBUGF(NETIF_DEBUG, ("low_level_input enter, rxlen:%d\n", len));
/* Obtain the size of the packet and put it into the "len"
variable. */
if(!len)
{
return NULL;
}
#if ETH_PAD_SIZE
//len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif
/* We allocate a pbuf chain of pbufs from the pool. */
p = memory_manager->alloc_pool(len, 0);
if (p != NULL)
{
#if ETH_PAD_SIZE
//pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* We iterate over the pbuf chain until we have read the entire
* packet into the pbuf. */
for(q = p; q != NULL; q = memory_manager->get_next(q))
{
/* Read enough bytes to fill this pbuf in the chain. The
* available data in the pbuf is given by the q->len
* variable.
* This does not necessarily have to be a memcpy, you can also preallocate
* pbufs for a DMA-enabled MAC and after receiving truncate it to the
* actually received size. In this case, ensure the tot_len member of the
* pbuf is the sum of the chained pbuf len members.
*/
/* load rx data from 96 to local mem_pool */
memcpy(memory_manager->get_ptr(q), &data[index], memory_manager->get_len(q));
index += memory_manager->get_len(q);
if(index >= len)
{
break;
}
}
/* acknowledge rda5996 that packet has been read(); */
//Nothing to do here
#if ETH_PAD_SIZE
//pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
//LINK_STATS_INC(link.recv);
}
else
{
/* Drop this packet */
LWIP_DEBUGF(NETIF_DEBUG, ("low_level_input pbuf_alloc fail, rxlen:%d\n", len));
//LINK_STATS_INC(link.memerr);
//LINK_STATS_INC(link.drop);
return NULL;
}
return p;
}
/** \brief Attempt to read a packet from the EMAC interface.
*
*/
void UWP_EMAC::packet_rx()
{
//printf("%s\r\n",__func__);
#if 1
uwp_wifi_msg_t msg = NULL;
packet_rx_queue = k_msg_create(10);
/* move received packet into a new buf */
while (1) {
emac_mem_buf_t *p = NULL;
k_msg_get(packet_rx_queue, &msg, osWaitForever);
//printf("rx type:%d\r\n",msg->type);
switch(msg->type)
{
case 0:
p = low_level_input((unsigned char*)msg->arg1, msg->arg2);
if (p == NULL) {
//rda_sem_release((void*)msg->arg3);
break;
}
//rda_sem_release((void*)msg->arg3);
if (p) {
//printf("free RXBUFF:%p\r\n",msg->arg1-msg->arg3);
uwp_pkt_buf_free((void *)(msg->arg1-msg->arg3));
emac_link_input_cb(p);
}
break;
case 1:
emac_link_state_cb(msg->arg1);
break;
default:
break;
}
free(msg);
}
#endif
}
void UWP_EMAC::thread_function(void *pvParameters)
{
printf("%s\r\n",__func__);
#if 1
static struct UWP_EMAC *uwp_enet = static_cast<UWP_EMAC *>(pvParameters);
uwp_enet->packet_rx();
#endif
}
bool UWP_EMAC::power_up()
{
static int thread_inited = 0;
printf("%s\r\n",__func__);
if(!thread_inited){
void *ret = k_thread_create("packet_rx", UWP_EMAC::thread_function, this, NULL, DEFAULT_THREAD_STACKSIZE*5, PHY_PRIORITY);
thread_inited = 1;
return (ret != NULL);
}
return true;
}
uint32_t UWP_EMAC::get_mtu_size() const
{
return UWP_ETH_MTU_SIZE;
}
uint32_t UWP_EMAC::get_align_preference() const
{
return 0;
}
void UWP_EMAC::get_ifname(char *name, uint8_t size) const
{
memcpy(name, UWP_ETH_IF_NAME, (size < sizeof(UWP_ETH_IF_NAME)) ? size : sizeof(UWP_ETH_IF_NAME));
}
uint8_t UWP_EMAC::get_hwaddr_size() const
{
return UWP_HWADDR_SIZE;
}
bool UWP_EMAC::get_hwaddr(uint8_t *addr) const
{
uwp_mgmt_getmac(addr);
return true;
}
void UWP_EMAC::set_hwaddr(const uint8_t *addr)
{
/* No-op at this stage */
}
void UWP_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)
{
emac_link_input_cb = input_cb;
}
void UWP_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)
{
emac_link_state_cb = state_cb;
}
void UWP_EMAC::add_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void UWP_EMAC::remove_multicast_group(const uint8_t *addr)
{
/* No-op at this stage */
}
void UWP_EMAC::set_all_multicast(bool all)
{
/* No-op at this stage */
}
void UWP_EMAC::power_down()
{
/* No-op at this stage */
}
void UWP_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)
{
memory_manager = &mem_mngr;
}
UWP_EMAC &UWP_EMAC::get_instance()
{
static UWP_EMAC emac;
return emac;
}
// Weak so a module can override
MBED_WEAK EMAC &EMAC::get_default_instance()
{
return UWP_EMAC::get_instance();
}
| 27.166667
| 141
| 0.629743
|
caixue901102
|
6197d0651e8ef67eba61d39fbdffee035f06963a
| 257
|
cpp
|
C++
|
benchmarks/speed3d_c2c.cpp
|
jli111/heffte_osc_a2av
|
59d69500cb86ef6a37212326c35cd85176f45526
|
[
"BSD-3-Clause"
] | 6
|
2021-03-05T18:19:02.000Z
|
2022-03-08T10:47:00.000Z
|
benchmarks/speed3d_c2c.cpp
|
jli111/heffte_osc_a2av
|
59d69500cb86ef6a37212326c35cd85176f45526
|
[
"BSD-3-Clause"
] | 1
|
2021-07-09T14:26:17.000Z
|
2021-07-09T14:26:17.000Z
|
benchmarks/speed3d_c2c.cpp
|
jli111/heffte_osc_a2av
|
59d69500cb86ef6a37212326c35cd85176f45526
|
[
"BSD-3-Clause"
] | 1
|
2021-12-15T16:45:41.000Z
|
2021-12-15T16:45:41.000Z
|
/*
-- heFFTe --
Univ. of Tennessee, Knoxville
@date
Performance test for 3D FFTs using heFFTe to compute 3D complex-to-complex transforms
*/
#define BENCH_INPUT std::complex<precision_type>
#define BENCH_C2C
#include "speed3d.h"
| 21.416667
| 93
| 0.688716
|
jli111
|
619a008cd2519a2703cb0a4463ace40b108a4dba
| 27,923
|
cpp
|
C++
|
src/libbrep/debug_plot.cpp
|
ejno/brlcad
|
b21b3e1728ade0fea2d36a105609566cb114c382
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
src/libbrep/debug_plot.cpp
|
ejno/brlcad
|
b21b3e1728ade0fea2d36a105609566cb114c382
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
src/libbrep/debug_plot.cpp
|
ejno/brlcad
|
b21b3e1728ade0fea2d36a105609566cb114c382
|
[
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null |
/* D E B U G _ P L O T . C P P
* BRL-CAD
*
* Copyright (c) 2014-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file debug_plot.cpp
*
* DebugPlot implementation. Currently borrows code from librt to
* handle the creation of vlists for brep geometry and conversion of
* those vlists to unix plot files.
*/
#include <iostream>
#include <sstream>
#include <string>
#include "bu/log.h"
#include "bn.h"
#include "raytrace.h"
#include "vmath.h"
#include "debug_plot.h"
#include "brep_except.h"
static unsigned char surface1_color[] = {0, 0, 62};
static unsigned char surface2_color[] = {62, 0, 0};
static unsigned char surface1_highlight_color[] = {56, 56, 255};
static unsigned char surface2_highlight_color[] = {255, 56, 56};
static unsigned char tangent_color[] = {255, 255, 255};
static unsigned char transverse_color[] = {255, 255, 0};
static unsigned char overlap_color[] = {0, 255, 0};
static unsigned char accepted_outerloop_color[] = {0, 255, 0};
static unsigned char accepted_innerloop_color[] = {255, 0, 0};
static unsigned char unknown_outerloop_color[] = {158, 158, 0};
static unsigned char unknown_innerloop_color[] = {158, 158, 0};
static unsigned char rejected_outerloop_color[] = {0, 62, 0};
static unsigned char rejected_innerloop_color[] = {62, 0, 0};
DebugPlot::DebugPlot(const char *basename) :
prefix(basename),
have_surfaces(false),
brep1_surf_count(0),
brep2_surf_count(0),
linked_curve_count(0)
{
BU_LIST_INIT(&vlist_free_list);
}
DebugPlot::~DebugPlot()
{
struct bn_vlist *vp;
while (BU_LIST_WHILE(vp, bn_vlist, &vlist_free_list)) {
BU_LIST_DEQUEUE(&(vp->l));
bu_free((char *)vp, "bn_vlist");
}
}
int
DebugPlot::SurfacePairs(void)
{
return (int)intersecting_surfaces.size();
}
int
DebugPlot::IntersectingIsocurves(int ssx_idx)
{
int max_isocsx_idx = (int)ssx_isocsx_events.size() - 1;
if (ssx_idx < 0 || ssx_idx > max_isocsx_idx) {
std::cerr << "DebugPlot::IntersectingIsocurves passed invalid ssx index.\n";
return 0;
}
return (int)ssx_isocsx_events[ssx_idx].size();
}
int
DebugPlot::LinkedCurves(void)
{
return linked_curve_count;
}
HIDDEN void
rt_vlist_to_uplot(FILE *fp, const struct bu_list *vhead)
{
struct bn_vlist *vp;
for (BU_LIST_FOR(vp, bn_vlist, vhead)) {
int i;
int nused = vp->nused;
const int *cmd = vp->cmd;
point_t *pt = vp->pt;
for (i = 0; i < nused; i++, cmd++, pt++) {
switch (*cmd) {
case BN_VLIST_POLY_START:
case BN_VLIST_TRI_START:
break;
case BN_VLIST_POLY_MOVE:
case BN_VLIST_LINE_MOVE:
case BN_VLIST_TRI_MOVE:
pdv_3move(fp, *pt);
break;
case BN_VLIST_POLY_DRAW:
case BN_VLIST_POLY_END:
case BN_VLIST_LINE_DRAW:
case BN_VLIST_TRI_DRAW:
case BN_VLIST_TRI_END:
pdv_3cont(fp, *pt);
break;
default:
bu_log("rt_vlist_to_uplot: unknown vlist cmd x%x\n",
*cmd);
}
}
}
}
HIDDEN void
write_plot_to_file(
const char *filename,
const struct bu_list *vhead,
const unsigned char *color)
{
FILE *fp = fopen(filename, "w");
if (!color) {
unsigned char clr[] = {255, 0, 0};
color = clr;
}
pl_linmod(fp, "solid");
pl_color(fp, color[0], color[1], color[2]);
rt_vlist_to_uplot(fp, vhead);
fclose(fp);
}
void
DebugPlot::WriteLog()
{
std::ostringstream filename;
// First write out empty plots of different colors, we use this to
// "erase" unwanted overlays when running the dplot command.
struct bu_list vhead;
BU_LIST_INIT(&vhead);
point_t origin = {0.0, 0.0, 0.0};
BN_ADD_VLIST(&vlist_free_list, &vhead, origin, BN_VLIST_LINE_MOVE);
filename << prefix << "_empty0.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, tangent_color);
filename.str("");
filename << prefix << "_empty1.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, transverse_color);
filename.str("");
filename << prefix << "_empty2.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, overlap_color);
filename.str("");
filename << prefix << "_empty3.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, surface1_color);
filename.str("");
filename << prefix << "_empty4.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, surface2_color);
filename.str("");
filename << prefix << "_empty5.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, surface1_highlight_color);
filename.str("");
filename << prefix << "_empty6.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, surface2_highlight_color);
filename.str("");
filename << prefix << "_empty7.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, accepted_outerloop_color);
filename.str("");
filename << prefix << "_empty8.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, accepted_innerloop_color);
filename.str("");
filename << prefix << "_empty9.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, unknown_outerloop_color);
filename.str("");
filename << prefix << "_empty10.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, unknown_innerloop_color);
filename.str("");
filename << prefix << "_empty11.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, rejected_outerloop_color);
filename.str("");
filename << prefix << "_empty12.plot3";
write_plot_to_file(filename.str().c_str(), &vhead, rejected_innerloop_color);
// create dplot log file
filename.str("");
filename << prefix << ".dplot";
FILE *fp = fopen(filename.str().c_str(), "w");
// write out surface-surface intersections
fprintf(fp, "surfaces %d %d\n", brep1_surf_count, brep2_surf_count);
for (size_t i = 0; i < intersecting_surfaces.size(); ++i) {
std::pair<int, int> intersecting = intersecting_surfaces[i];
int events, b1_isocurves, intersecting_isocurves, b1_clipped, b2_clipped;
try {
events = ssx_events.at(i);
} catch (std::out_of_range &e) {
events = 0;
}
try {
std::pair<int, int> ccount = ssx_clipped_curves.at(i);
b1_clipped = ccount.first;
b2_clipped = ccount.second;
} catch (std::out_of_range &e) {
b1_clipped = b2_clipped = 0;
}
try {
b1_isocurves = ssx_isocsx_brep1_curves.at(i);
} catch (std::out_of_range &e) {
b1_isocurves = 0;
}
try {
intersecting_isocurves = (int)ssx_isocsx_events.at(i).size();
} catch (std::out_of_range &e) {
intersecting_isocurves = 0;
}
// b1si b2si finalevents b1ccurves b2ccurves b1_isocurve_xs total_isocurve_xs isocsx0_event0 ...
fprintf(fp, "ssx %d %d %d %d %d %d %d", intersecting.first,
intersecting.second, events, b1_clipped, b2_clipped,
b1_isocurves, intersecting_isocurves);
if (ssx_isocsx_events.size() > i) {
for (size_t j = 0; j < ssx_isocsx_events[i].size(); ++j) {
fprintf(fp, " %d", ssx_isocsx_events[i][j]);
}
}
fprintf(fp, "\n");
}
// write out linked curve count
if (linked_curve_count > 0) {
fprintf(fp, "linkedcurves %d\n", linked_curve_count);
}
// write out split faces
size_t split_faces = split_face_outerloop_curves.size();
if (split_faces > 0) {
fprintf(fp, "splitfaces %d\n", (int)split_faces);
}
for (size_t i = 0; i < split_faces; ++i) {
fprintf(fp, "splitface %d %d %d\n", (int)i,
split_face_outerloop_curves[i],
split_face_innerloop_curves[i]);
}
fclose(fp);
BN_FREE_VLIST(&vlist_free_list, &vhead);
}
HIDDEN double
find_next_t(const ON_Curve* crv, double start_t, double step, double max_dist)
{
ON_Interval dom = crv->Domain();
ON_3dPoint prev_pt = crv->PointAt(dom.ParameterAt(start_t));
ON_3dPoint next_pt;
// ensure that (start + step) < 1.0
if (start_t + step > 1.0) {
step = 1.0 - start_t - BN_TOL_DIST;
}
// reduce step until next point is within tolerance
while (step > BN_TOL_DIST) {
next_pt = crv->PointAt(dom.ParameterAt(start_t + step));
if (prev_pt.DistanceTo(next_pt) <= max_dist) {
return start_t + step;
}
step /= 2.0;
}
// if we couldn't find a point within tolerance, give up and jump
// to end of domain
return 1.0;
}
void
DebugPlot::Plot3DCurve(
const ON_Curve *crv,
const char *filename,
unsigned char *color,
struct bu_list *vlist /* = NULL */)
{
struct bu_list vhead_tmp;
BU_LIST_INIT(&vhead_tmp);
struct bu_list *vhead = &vhead_tmp;
if (vlist) {
vhead = vlist;
}
ON_Interval crv_dom = crv->Domain();
// Insert first point.
point_t pt1;
ON_3dPoint p;
p = crv->PointAt(crv_dom.ParameterAt(0.0));
VMOVE(pt1, p);
BN_ADD_VLIST(&vlist_free_list, vhead, pt1, BN_VLIST_LINE_MOVE);
/* Dynamic sampling approach - start with an initial guess
* for the next point of one tenth of the domain length
* further down the domain from the previous value. Set a
* maximum physical distance between points of 100 times
* the model tolerance. Reduce the increment until the
* tolerance is satisfied, then add the point and use it
* as the starting point for the next calculation until
* the whole domain is finished. Perhaps it would be more
* ideal to base the tolerance on some fraction of the
* curve bounding box dimensions?
*/
double t = 0.0;
while (t < 1.0) {
t = find_next_t(crv, t, 0.1, BN_TOL_DIST * 100);
p = crv->PointAt(crv_dom.ParameterAt(t));
VMOVE(pt1, p);
BN_ADD_VLIST(&vlist_free_list, vhead, pt1, BN_VLIST_LINE_DRAW);
}
if (!vlist) {
write_plot_to_file(filename, vhead, color);
BN_FREE_VLIST(&vlist_free_list, vhead);
}
}
void
DebugPlot::Plot3DCurveFrom2D(
const ON_Surface *surf,
const ON_Curve *crv,
const char *filename,
unsigned char *color,
bool decorate /* = false */)
{
struct bu_list vhead;
BU_LIST_INIT(&vhead);
ON_Interval crv_dom = crv->Domain();
ON_3dPoint p, uv;
// Insert first point.
point_t pt1, first_pt, last_pt, prev_pt;
ON_3dVector normal;
uv = crv->PointAt(crv_dom.ParameterAt(0.0));
surf->EvNormal(uv.x, uv.y, p, normal);
VMOVE(first_pt, p);
uv = crv->PointAt(crv_dom.ParameterAt(1.0));
surf->EvNormal(uv.x, uv.y, p, normal);
VMOVE(last_pt, p);
bool closed = false;
if (VNEAR_EQUAL(first_pt, last_pt, BN_TOL_DIST)) {
closed = true;
}
VMOVE(pt1, first_pt);
BN_ADD_VLIST(&vlist_free_list, &vhead, pt1, BN_VLIST_LINE_MOVE);
/* Dynamic sampling approach - start with an initial guess
* for the next point of one tenth of the domain length
* further down the domain from the previous value. Set a
* maximum physical distance between points of 100 times
* the model tolerance. Reduce the increment until the
* tolerance is satisfied, then add the point and use it
* as the starting point for the next calculation until
* the whole domain is finished. Perhaps it would be more
* ideal to base the tolerance on some fraction of the
* curve bounding box dimensions?
*/
double t = 0.0;
bool first = true;
double min_mag = BN_TOL_DIST * 10.0;
double mag_tan = min_mag;
vect_t tangent = {0.0, 0.0, min_mag};
vect_t perp, barb;
while (t < 1.0) {
t = find_next_t(crv, t, 0.1, BN_TOL_DIST * 100);
uv = crv->PointAt(crv_dom.ParameterAt(t));
surf->EvNormal(uv.x, uv.y, p, normal);
VMOVE(prev_pt, pt1);
VMOVE(pt1, p);
if (first || !VNEAR_EQUAL(pt1, prev_pt, BN_TOL_DIST)) {
VSUB2(tangent, pt1, prev_pt);
}
if (decorate && first) {
first = false;
mag_tan = DIST_PNT_PNT(prev_pt, pt1);
mag_tan = FMAX(mag_tan, min_mag);
VUNITIZE(tangent);
VCROSS(perp, tangent, normal);
if (!closed) {
VSCALE(tangent, tangent, mag_tan);
VUNITIZE(perp);
VSCALE(perp, perp, mag_tan);
VADD3(barb, prev_pt, tangent, perp);
BN_ADD_VLIST(&vlist_free_list, &vhead, barb, BN_VLIST_LINE_DRAW);
BN_ADD_VLIST(&vlist_free_list, &vhead, prev_pt, BN_VLIST_LINE_MOVE);
VSCALE(perp, perp, -1.0);
VADD3(barb, prev_pt, tangent, perp);
BN_ADD_VLIST(&vlist_free_list, &vhead, barb, BN_VLIST_LINE_DRAW);
BN_ADD_VLIST(&vlist_free_list, &vhead, prev_pt, BN_VLIST_LINE_MOVE);
}
}
BN_ADD_VLIST(&vlist_free_list, &vhead, pt1, BN_VLIST_LINE_DRAW);
}
if (decorate) {
VUNITIZE(tangent);
VSCALE(tangent, tangent, -mag_tan);
VCROSS(perp, tangent, normal);
VUNITIZE(perp);
VSCALE(perp, perp, mag_tan);
VADD2(barb, pt1, perp);
if (!closed) {
VADD2(barb, barb, tangent);
}
BN_ADD_VLIST(&vlist_free_list, &vhead, barb, BN_VLIST_LINE_DRAW);
BN_ADD_VLIST(&vlist_free_list, &vhead, pt1, BN_VLIST_LINE_MOVE);
VSCALE(perp, perp, -1.0);
VADD2(barb, pt1, perp);
if (!closed) {
VADD2(barb, barb, tangent);
}
BN_ADD_VLIST(&vlist_free_list, &vhead, barb, BN_VLIST_LINE_DRAW);
}
write_plot_to_file(filename, &vhead, color);
BN_FREE_VLIST(&vlist_free_list, &vhead);
}
void
DebugPlot::PlotBoundaryIsocurves(
struct bu_list *vlist,
const ON_Surface &surf,
int knot_dir)
{
int surf_dir = 1 - knot_dir;
int knot_count = surf.SpanCount(surf_dir) + 1;
double *surf_knots = new double[knot_count];
surf.GetSpanVector(surf_dir, surf_knots);
// knots that can be boundaries of Bezier patches
ON_SimpleArray<double> surf_bknots;
surf_bknots.Append(surf_knots[0]);
for (int i = 1; i < knot_count; i++) {
if (surf_knots[i] > *(surf_bknots.Last())) {
surf_bknots.Append(surf_knots[i]);
}
}
delete[] surf_knots;
if (surf.IsClosed(surf_dir)) {
surf_bknots.Remove();
}
for (int i = 0; i < surf_bknots.Count(); i++) {
ON_Curve *surf_boundary_iso = surf.IsoCurve(knot_dir, surf_bknots[i]);
Plot3DCurve(surf_boundary_iso, NULL, NULL, vlist);
delete surf_boundary_iso;
}
}
void
DebugPlot::PlotSurface(
const ON_Surface &surf,
const char *filename,
unsigned char *color)
{
struct bu_list vhead;
BU_LIST_INIT(&vhead);
PlotBoundaryIsocurves(&vhead, surf, 0);
PlotBoundaryIsocurves(&vhead, surf, 1);
write_plot_to_file(filename, &vhead, color);
BN_FREE_VLIST(&vlist_free_list, &vhead);
}
void
DebugPlot::Surfaces(const ON_Brep *brep1, const ON_Brep *brep2)
{
if (!brep1 || !brep2) {
std::cerr << "error: dplot_surfaces: NULL args\n";
return;
}
brep1_surf_count = brep1->m_S.Count();
for (int i = 0; i < brep1->m_S.Count(); i++) {
ON_Surface *surf = brep1->m_S[i];
std::ostringstream filename;
filename << prefix << "_brep1_surface" << i << ".plot3";
PlotSurface(*surf, filename.str().c_str(), surface1_color);
}
brep2_surf_count = brep2->m_S.Count();
for (int i = 0; i < brep2->m_S.Count(); i++) {
ON_Surface *surf = brep2->m_S[i];
std::ostringstream filename;
filename << prefix << "_brep2_surface" << i << ".plot3";
PlotSurface(*surf, filename.str().c_str(), surface2_color);
}
have_surfaces = true;
}
int get_subcurve_inside_faces(const ON_Brep *brep1, const ON_Brep *brep2, int face_i1, int face_i2, ON_SSX_EVENT *event);
void
DebugPlot::SSX(
const ON_ClassArray<ON_SSX_EVENT> &events,
const ON_Brep *brep1, int brep1_surf,
const ON_Brep *brep2, int brep2_surf)
{
ON_Surface *surf;
std::ostringstream filename;
// create highlighted plot of brep1 surface if it doesn't exist
filename << prefix << "_highlight_brep1_surface" << brep1_surf << ".plot3";
if (!bu_file_exists(filename.str().c_str(), NULL)) {
surf = brep1->m_S[brep1_surf];
PlotSurface(*surf, filename.str().c_str(), surface1_highlight_color);
}
// create highlighted plot of brep2 surface if it doesn't exist
filename.str("");
filename << prefix << "_highlight_brep2_surface" << brep2_surf << ".plot3";
if (!bu_file_exists(filename.str().c_str(), NULL)) {
surf = brep2->m_S[brep2_surf];
PlotSurface(*surf, filename.str().c_str(), surface2_highlight_color);
}
// create plot of the intersections between these surfaces
surf = brep1->m_S[brep1_surf];
size_t ssx_idx = intersecting_surfaces.size();
int plot_count = 0;
for (int i = 0; i < events.Count(); ++i) {
filename.str("");
filename << prefix << "_ssx" << ssx_idx << "_event" << plot_count <<
".plot3";
if (events[i].m_type == ON_SSX_EVENT::ssx_tangent) {
Plot3DCurveFrom2D(surf, events[i].m_curveA,
filename.str().c_str(), tangent_color, true);
++plot_count;
} else if (events[i].m_type == ON_SSX_EVENT::ssx_transverse) {
Plot3DCurveFrom2D(surf, events[i].m_curveA,
filename.str().c_str(), transverse_color, true);
++plot_count;
} else if (events[i].m_type == ON_SSX_EVENT::ssx_overlap) {
Plot3DCurveFrom2D(surf, events[i].m_curveA,
filename.str().c_str(), overlap_color, true);
++plot_count;
}
}
// stash surface indices and event count
std::pair<int, int> ssx_pair(brep1_surf, brep2_surf);
intersecting_surfaces.push_back(ssx_pair);
ssx_events.push_back(plot_count);
}
void
DebugPlot::IsoCSX(
const ON_SimpleArray<ON_X_EVENT> &events,
const ON_Curve *isocurve,
bool is_brep1_iso) // is the isocurve from brep1?
{
size_t ssx_idx = intersecting_surfaces.size();
// create plot of the intersections between the curve and surface
while (ssx_isocsx_events.size() < (ssx_idx + 1)) {
ssx_isocsx_events.push_back(std::vector<int>());
}
size_t isocsx_idx = ssx_isocsx_events[ssx_idx].size();
int plot_count = 0;
for (int i = 0; i < events.Count(); ++i) {
if (events[i].m_type == ON_X_EVENT::csx_overlap) {
std::ostringstream filename;
filename << prefix << "_ssx" << ssx_idx << "_isocsx" << isocsx_idx
<< "_event" << plot_count++ << ".plot3";
try {
ON_Curve *event_curve = sub_curve(isocurve, events[i].m_a[0],
events[i].m_a[1]);
Plot3DCurve(event_curve, filename.str().c_str(), overlap_color);
} catch (InvalidInterval &e) {
std::cerr << "error: IsoCSX event contains degenerate interval\n";
}
}
}
if (plot_count) {
// create highlighted plot of isocurve if it doesn't already exist
std::ostringstream filename;
filename << prefix << "_highlight_ssx" << ssx_idx << "_isocurve" <<
isocsx_idx << ".plot3";
if (!bu_file_exists(filename.str().c_str(), NULL)) {
if (is_brep1_iso) {
Plot3DCurve(isocurve, filename.str().c_str(),
surface1_highlight_color);
} else {
Plot3DCurve(isocurve, filename.str().c_str(),
surface2_highlight_color);
}
}
// remember event count for this isocsx
ssx_isocsx_events[ssx_idx].push_back(plot_count);
// remember how many events are for brep1 isocurve and brep2 surface,
if (is_brep1_iso) {
while (ssx_isocsx_brep1_curves.size() < (ssx_idx + 1)) {
ssx_isocsx_brep1_curves.push_back(0);
}
++ssx_isocsx_brep1_curves[ssx_idx];
}
}
}
void
DebugPlot::ClippedFaceCurves(
const ON_Surface *surf1,
const ON_Surface *surf2,
const ON_SimpleArray<ON_Curve *> &face1_curves,
const ON_SimpleArray<ON_Curve *> &face2_curves)
{
// plot clipped tangent/transverse/overlap curves
size_t ssx_idx = intersecting_surfaces.size() - 1;
for (int i = 0; i < face1_curves.Count(); ++i) {
std::ostringstream filename;
filename << prefix << "_ssx" << ssx_idx << "_brep1face_clipped_curve" << i << ".plot3";
Plot3DCurveFrom2D(surf1, face1_curves[i], filename.str().c_str(),
surface1_highlight_color, true);
}
for (int i = 0; i < face2_curves.Count(); ++i) {
std::ostringstream filename;
filename << prefix << "_ssx" << ssx_idx << "_brep2face_clipped_curve" << i << ".plot3";
Plot3DCurveFrom2D(surf2, face2_curves[i], filename.str().c_str(),
surface2_highlight_color, true);
}
while (ssx_clipped_curves.size() < (ssx_idx + 1)) {
ssx_clipped_curves.push_back(std::pair<int, int>(0, 0));
}
std::pair<int, int> counts(face1_curves.Count(), face2_curves.Count());
ssx_clipped_curves[ssx_idx] = counts;
}
struct TrimmedFace {
// curve segments in the face's outer loop
ON_SimpleArray<ON_Curve *> m_outerloop;
// several inner loops, each has some curves
std::vector<ON_SimpleArray<ON_Curve *> > m_innerloop;
const ON_BrepFace *m_face;
enum {
UNKNOWN = -1,
NOT_BELONG = 0,
BELONG = 1
} m_belong_to_final;
bool m_rev;
// Default constructor
TrimmedFace()
{
m_face = NULL;
m_belong_to_final = UNKNOWN;
m_rev = false;
}
// Destructor
~TrimmedFace()
{
// Delete the curve segments if it's not belong to the result.
if (m_belong_to_final != BELONG) {
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
delete m_outerloop[i];
m_outerloop[i] = NULL;
}
}
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
delete m_innerloop[i][j];
m_innerloop[i][j] = NULL;
}
}
}
}
}
TrimmedFace *Duplicate() const
{
TrimmedFace *out = new TrimmedFace();
out->m_face = m_face;
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
out->m_outerloop.Append(m_outerloop[i]->Duplicate());
}
}
out->m_innerloop = m_innerloop;
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
out->m_innerloop[i][j] = m_innerloop[i][j]->Duplicate();
}
}
}
return out;
}
};
void
DebugPlot::SplitFaces(
const ON_ClassArray<ON_SimpleArray<TrimmedFace *> > &split_faces)
{
for (int i = 0; i < split_faces.Count(); ++i) {
for (int j = 0; j < split_faces[i].Count(); ++j) {
TrimmedFace *face = split_faces[i][j];
unsigned char *outerloop_color = unknown_outerloop_color;
unsigned char *innerloop_color = unknown_innerloop_color;
switch (face->m_belong_to_final) {
case TrimmedFace::NOT_BELONG:
outerloop_color = rejected_outerloop_color;
innerloop_color = rejected_innerloop_color;
break;
case TrimmedFace::BELONG:
outerloop_color = accepted_outerloop_color;
innerloop_color = accepted_innerloop_color;
break;
default:
outerloop_color = unknown_outerloop_color;
innerloop_color = unknown_innerloop_color;
}
int split_face_count = split_face_outerloop_curves.size();
for (int k = 0; k < face->m_outerloop.Count(); ++k) {
std::ostringstream filename;
filename << prefix << "_split_face" << split_face_count <<
"_outerloop_curve" << k << ".plot3";
Plot3DCurveFrom2D(face->m_face->SurfaceOf(),
face->m_outerloop[k], filename.str().c_str(),
outerloop_color);
}
split_face_outerloop_curves.push_back(face->m_outerloop.Count());
int innerloop_count = 0;
for (size_t k = 0; k < face->m_innerloop.size(); ++k) {
for (int l = 0; l < face->m_innerloop[k].Count(); ++l) {
std::ostringstream filename;
filename << prefix << "_split_face" << split_face_count <<
"_innerloop_curve" << innerloop_count++ << ".plot3";
Plot3DCurveFrom2D(face->m_face->SurfaceOf(),
face->m_innerloop[k][l], filename.str().c_str(),
innerloop_color);
}
}
split_face_innerloop_curves.push_back(innerloop_count);
}
}
}
void append_to_polycurve(ON_Curve *curve, ON_PolyCurve &polycurve);
struct SSICurve {
ON_Curve *m_curve;
SSICurve()
{
m_curve = NULL;
}
SSICurve(ON_Curve *curve)
{
m_curve = curve;
}
SSICurve *Duplicate() const
{
SSICurve *out = new SSICurve();
if (out != NULL) {
*out = *this;
out->m_curve = m_curve->Duplicate();
}
return out;
}
};
struct LinkedCurve {
private:
ON_Curve *m_curve; // an explicit storage of the whole curve
public:
// The curves contained in this LinkedCurve, including
// the information needed by the connectivity graph
ON_SimpleArray<SSICurve> m_ssi_curves;
// Default constructor
LinkedCurve()
{
m_curve = NULL;
}
~LinkedCurve()
{
if (m_curve) {
delete m_curve;
}
m_curve = NULL;
}
LinkedCurve &operator= (const LinkedCurve &_lc)
{
m_curve = _lc.m_curve ? _lc.m_curve->Duplicate() : NULL;
m_ssi_curves = _lc.m_ssi_curves;
return *this;
}
ON_3dPoint PointAtStart() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves[0].m_curve->PointAtStart();
} else {
return ON_3dPoint::UnsetPoint;
}
}
ON_3dPoint PointAtEnd() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves.Last()->m_curve->PointAtEnd();
} else {
return ON_3dPoint::UnsetPoint;
}
}
bool IsClosed() const
{
if (m_ssi_curves.Count() == 0) {
return false;
}
return PointAtStart().DistanceTo(PointAtEnd()) < ON_ZERO_TOLERANCE;
}
bool IsValid() const
{
// Check whether the curve has "gaps".
for (int i = 1; i < m_ssi_curves.Count(); i++) {
if (m_ssi_curves[i].m_curve->PointAtStart().DistanceTo(m_ssi_curves[i - 1].m_curve->PointAtEnd()) >= ON_ZERO_TOLERANCE) {
bu_log("The LinkedCurve is not valid.\n");
return false;
}
}
return true;
}
bool Reverse()
{
ON_SimpleArray<SSICurve> new_array;
for (int i = m_ssi_curves.Count() - 1; i >= 0; i--) {
if (!m_ssi_curves[i].m_curve->Reverse()) {
return false;
}
new_array.Append(m_ssi_curves[i]);
}
m_ssi_curves = new_array;
return true;
}
void Append(const LinkedCurve &lc)
{
m_ssi_curves.Append(lc.m_ssi_curves.Count(), lc.m_ssi_curves.Array());
}
void Append(const SSICurve &sc)
{
m_ssi_curves.Append(sc);
}
void AppendCurvesToArray(ON_SimpleArray<ON_Curve *> &arr) const
{
for (int i = 0; i < m_ssi_curves.Count(); i++) {
arr.Append(m_ssi_curves[i].m_curve->Duplicate());
}
}
const ON_Curve *Curve()
{
if (m_curve != NULL) {
return m_curve;
}
if (m_ssi_curves.Count() == 0 || !IsValid()) {
return NULL;
}
ON_PolyCurve *polycurve = new ON_PolyCurve;
for (int i = 0; i < m_ssi_curves.Count(); i++) {
append_to_polycurve(m_ssi_curves[i].m_curve->Duplicate(), *polycurve);
}
m_curve = polycurve;
return m_curve;
}
const ON_3dPoint PointAt(double t)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_3dPoint::UnsetPoint;
}
return c->PointAt(t);
}
const ON_Interval Domain()
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_Interval::EmptyInterval;
}
return c->Domain();
}
ON_Curve *SubCurve(double t1, double t2)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return NULL;
}
try {
return sub_curve(c, t1, t2);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
return NULL;
}
}
};
void
DebugPlot::LinkedCurves(
const ON_Surface *surf,
ON_ClassArray<LinkedCurve> &linked_curves)
{
for (int i = 0; i < linked_curves.Count(); ++i) {
const ON_Curve *linked_curve = linked_curves[i].Curve();
std::ostringstream filename;
filename << prefix << "_linked_curve" << linked_curve_count++ << ".plot3";
Plot3DCurveFrom2D(surf, linked_curve, filename.str().c_str(), transverse_color);
}
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 28.176589
| 126
| 0.661247
|
ejno
|
619ae2367cb562599aa5b4c8c9980d7dd1d042f5
| 373
|
cpp
|
C++
|
src/libserver/src/serverconnectionfactory.cpp
|
tsaah/whisper
|
afe9fd000ed3ebd684d78193ce0c12217bb68fde
|
[
"MIT"
] | 1
|
2021-03-22T07:22:43.000Z
|
2021-03-22T07:22:43.000Z
|
src/libserver/src/serverconnectionfactory.cpp
|
tsaah/whisper
|
afe9fd000ed3ebd684d78193ce0c12217bb68fde
|
[
"MIT"
] | null | null | null |
src/libserver/src/serverconnectionfactory.cpp
|
tsaah/whisper
|
afe9fd000ed3ebd684d78193ce0c12217bb68fde
|
[
"MIT"
] | null | null | null |
#include "serverconnectionfactory.h"
#include <connection.h>
namespace whisper {
namespace server {
QTcpSocket *ServerConnectionFactory::create(qintptr handle) {
auto* socket = new common::Connection;
if (socket != nullptr && socket->setSocketDescriptor(handle)) {
return socket;
}
return nullptr;
}
} // namespace server
} // namespace whisper
| 20.722222
| 67
| 0.705094
|
tsaah
|
619c51bfcfbbfddab1b1b73df7e8542ad6a92bf2
| 1,321
|
cc
|
C++
|
src/flutter/shell/platform/linux_embedded/surface/egl_utils.cc
|
TomohideMorimoto/flutter-embedded-linux
|
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
|
[
"BSD-3-Clause"
] | 743
|
2021-03-09T07:56:39.000Z
|
2022-03-30T20:22:32.000Z
|
src/flutter/shell/platform/linux_embedded/surface/egl_utils.cc
|
TomohideMorimoto/flutter-embedded-linux
|
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
|
[
"BSD-3-Clause"
] | 165
|
2021-03-09T06:44:39.000Z
|
2022-03-25T20:48:03.000Z
|
src/flutter/shell/platform/linux_embedded/surface/egl_utils.cc
|
TomohideMorimoto/flutter-embedded-linux
|
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
|
[
"BSD-3-Clause"
] | 59
|
2021-03-09T04:25:01.000Z
|
2022-03-29T19:15:46.000Z
|
// Copyright 2021 Sony Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux_embedded/surface/egl_utils.h"
#include <EGL/egl.h>
#include <string>
#include <vector>
namespace flutter {
std::string get_egl_error_cause() {
static const std::vector<std::pair<EGLint, std::string>> table = {
{EGL_SUCCESS, "EGL_SUCCESS"},
{EGL_NOT_INITIALIZED, "EGL_NOT_INITIALIZED"},
{EGL_BAD_ACCESS, "EGL_BAD_ACCESS"},
{EGL_BAD_ALLOC, "EGL_BAD_ALLOC"},
{EGL_BAD_ATTRIBUTE, "EGL_BAD_ATTRIBUTE"},
{EGL_BAD_CONTEXT, "EGL_BAD_CONTEXT"},
{EGL_BAD_CONFIG, "EGL_BAD_CONFIG"},
{EGL_BAD_CURRENT_SURFACE, "EGL_BAD_CURRENT_SURFACE"},
{EGL_BAD_DISPLAY, "EGL_BAD_DISPLAY"},
{EGL_BAD_SURFACE, "EGL_BAD_SURFACE"},
{EGL_BAD_MATCH, "EGL_BAD_MATCH"},
{EGL_BAD_PARAMETER, "EGL_BAD_PARAMETER"},
{EGL_BAD_NATIVE_PIXMAP, "EGL_BAD_NATIVE_PIXMAP"},
{EGL_BAD_NATIVE_WINDOW, "EGL_BAD_NATIVE_WINDOW"},
{EGL_CONTEXT_LOST, "EGL_CONTEXT_LOST"},
};
auto egl_error = eglGetError();
for (auto t : table) {
if (egl_error == t.first) {
return std::string("eglGetError: " + t.second);
}
}
return nullptr;
}
} // namespace flutter
| 30.72093
| 73
| 0.692657
|
TomohideMorimoto
|
61a70b8afdf2e7dcc350a153d07edd7295051b92
| 21,060
|
cc
|
C++
|
server/modules/filter/topfilter/topfilter.cc
|
DatabasKarlsson/MaxScale
|
ccf90f2e5d28f589eecd54bcb3fb20dfec5b14ff
|
[
"BSD-3-Clause"
] | null | null | null |
server/modules/filter/topfilter/topfilter.cc
|
DatabasKarlsson/MaxScale
|
ccf90f2e5d28f589eecd54bcb3fb20dfec5b14ff
|
[
"BSD-3-Clause"
] | 1
|
2021-02-12T10:08:58.000Z
|
2021-02-18T02:57:57.000Z
|
server/modules/filter/topfilter/topfilter.cc
|
ThomasDai/MaxScale
|
766afedbada386b4402b8dbb21805e7eaba52323
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2024-11-26
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
/**
* @file topfilter.c - Top N Longest Running Queries
* @verbatim
*
* TOPN Filter - Query Log All. A primitive query logging filter, simply
* used to verify the filter mechanism for downstream filters. All queries
* that are passed through the filter will be written to file.
*
* The filter makes no attempt to deal with query packets that do not fit
* in a single GWBUF.
*
* A single option may be passed to the filter, this is the name of the
* file to which the queries are logged. A serial number is appended to this
* name in order that each session logs to a different file.
*
* Date Who Description
* 18/06/2014 Mark Riddoch Addition of source and user filters
*
* @endverbatim
*/
#define MXS_MODULE_NAME "topfilter"
#include <maxscale/ccdefs.hh>
#include <stdio.h>
#include <fcntl.h>
#include <maxscale/filter.hh>
#include <maxscale/modinfo.hh>
#include <maxscale/modutil.hh>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <regex.h>
#include <maxbase/atomic.h>
#include <maxbase/alloc.h>
/*
* The filter entry points
*/
static MXS_FILTER* createInstance(const char* name, mxs::ConfigParameters*);
static MXS_FILTER_SESSION* newSession(MXS_FILTER* instance,
MXS_SESSION* session,
SERVICE* service,
mxs::Downstream* down,
mxs::Upstream* up);
static void closeSession(MXS_FILTER* instance, MXS_FILTER_SESSION* session);
static void freeSession(MXS_FILTER* instance, MXS_FILTER_SESSION* session);
static int routeQuery(MXS_FILTER* instance, MXS_FILTER_SESSION* fsession, GWBUF* queue);
static int clientReply(MXS_FILTER* instance,
MXS_FILTER_SESSION* fsession,
GWBUF* buffer,
const mxs::ReplyRoute& down,
const mxs::Reply& reply);
static json_t* diagnostics(const MXS_FILTER* instance, const MXS_FILTER_SESSION* fsession);
static uint64_t getCapabilities(MXS_FILTER* instance);
/**
* A instance structure, the assumption is that the option passed
* to the filter is simply a base for the filename to which the queries
* are logged.
*
* To this base a session number is attached such that each session will
* have a unique name.
*/
typedef struct
{
int sessions; /* Session count */
int topN; /* Number of queries to store */
char* filebase; /* Base of fielname to log into */
char* source; /* The source of the client connection */
char* user; /* A user name to filter on */
char* match; /* Optional text to match against */
regex_t re; /* Compiled regex text */
char* exclude; /* Optional text to match against for exclusion */
regex_t exre; /* Compiled regex nomatch text */
} TOPN_INSTANCE;
/**
* Structure to hold the Top N queries
*/
typedef struct topnq
{
struct timeval duration;
char* sql;
} TOPNQ;
/**
* The session structure for this TOPN filter.
* This stores the downstream filter information, such that the
* filter is able to pass the query on to the next filter (or router)
* in the chain.
*
* It also holds the file descriptor to which queries are written.
*/
typedef struct
{
mxs::Downstream* down;
mxs::Upstream* up;
int active;
char* clientHost;
char* userName;
char* filename;
int fd;
struct timeval start;
char* current;
TOPNQ** top;
int n_statements;
struct timeval total;
struct timeval connect;
struct timeval disconnect;
} TOPN_SESSION;
static const MXS_ENUM_VALUE option_values[] =
{
{"ignorecase", REG_ICASE },
{"case", 0 },
{"extended", REG_EXTENDED},
{NULL}
};
extern "C"
{
/**
* The module entry point routine. It is this routine that
* must populate the structure that is referred to as the
* "module object", this is a structure with the set of
* external entry points for this module.
*
* @return The module object
*/
MXS_MODULE* MXS_CREATE_MODULE()
{
static MXS_FILTER_OBJECT MyObject =
{
createInstance,
newSession,
closeSession,
freeSession,
routeQuery,
clientReply,
diagnostics,
getCapabilities,
NULL, // No destroyInstance
};
static MXS_MODULE info =
{
MXS_MODULE_API_FILTER,
MXS_MODULE_GA,
MXS_FILTER_VERSION,
"A top N query "
"logging filter",
"V1.0.1",
RCAP_TYPE_CONTIGUOUS_INPUT,
&MyObject,
NULL,
NULL,
NULL,
NULL,
{
{"count", MXS_MODULE_PARAM_COUNT, "10" },
{"filebase", MXS_MODULE_PARAM_STRING, NULL, MXS_MODULE_OPT_REQUIRED},
{"match", MXS_MODULE_PARAM_STRING},
{"exclude", MXS_MODULE_PARAM_STRING},
{"source", MXS_MODULE_PARAM_STRING},
{"user", MXS_MODULE_PARAM_STRING},
{
"options",
MXS_MODULE_PARAM_ENUM,
"ignorecase",
MXS_MODULE_OPT_NONE,
option_values
},
{MXS_END_MODULE_PARAMS}
}
};
return &info;
}
}
/**
* Create an instance of the filter for a particular service
* within MaxScale.
*
* @param name The name of the instance (as defined in the config file).
* @param options The options for this filter
* @param params The array of name/value pair parameters for the filter
*
* @return The instance data for this new instance
*/
static MXS_FILTER* createInstance(const char* name, mxs::ConfigParameters* params)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*)MXS_MALLOC(sizeof(TOPN_INSTANCE));
if (my_instance)
{
my_instance->sessions = 0;
my_instance->topN = params->get_integer("count");
my_instance->match = params->get_c_str_copy("match");
my_instance->exclude = params->get_c_str_copy("exclude");
my_instance->source = params->get_c_str_copy("source");
my_instance->user = params->get_c_str_copy("user");
my_instance->filebase = params->get_c_str_copy("filebase");
int cflags = params->get_enum("options", option_values);
bool error = false;
if (my_instance->match
&& regcomp(&my_instance->re, my_instance->match, cflags))
{
MXS_ERROR("Invalid regular expression '%s'"
" for the 'match' parameter.",
my_instance->match);
regfree(&my_instance->re);
MXS_FREE(my_instance->match);
my_instance->match = NULL;
error = true;
}
if (my_instance->exclude
&& regcomp(&my_instance->exre, my_instance->exclude, cflags))
{
MXS_ERROR("Invalid regular expression '%s'"
" for the 'nomatch' parameter.\n",
my_instance->exclude);
regfree(&my_instance->exre);
MXS_FREE(my_instance->exclude);
my_instance->exclude = NULL;
error = true;
}
if (error)
{
if (my_instance->exclude)
{
regfree(&my_instance->exre);
MXS_FREE(my_instance->exclude);
}
if (my_instance->match)
{
regfree(&my_instance->re);
MXS_FREE(my_instance->match);
}
MXS_FREE(my_instance->filebase);
MXS_FREE(my_instance->source);
MXS_FREE(my_instance->user);
MXS_FREE(my_instance);
my_instance = NULL;
}
}
return (MXS_FILTER*) my_instance;
}
/**
* Associate a new session with this instance of the filter.
*
* Create the file to log to and open it.
*
* @param instance The filter instance data
* @param session The session itself
* @return Session specific data for this session
*/
static MXS_FILTER_SESSION* newSession(MXS_FILTER* instance,
MXS_SESSION* session,
SERVICE* service,
mxs::Downstream* down,
mxs::Upstream* up)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*) instance;
TOPN_SESSION* my_session;
int i;
const char* remote, * user;
if ((my_session = static_cast<TOPN_SESSION*>(MXS_CALLOC(1, sizeof(TOPN_SESSION)))) != NULL)
{
if ((my_session->filename =
(char*) MXS_MALLOC(strlen(my_instance->filebase) + 20))
== NULL)
{
MXS_FREE(my_session);
return NULL;
}
sprintf(my_session->filename, "%s.%lu", my_instance->filebase, session->id());
my_session->top = (TOPNQ**) MXS_CALLOC(my_instance->topN + 1, sizeof(TOPNQ*));
MXS_ABORT_IF_NULL(my_session->top);
for (i = 0; i < my_instance->topN; i++)
{
my_session->top[i] = (TOPNQ*) MXS_CALLOC(1, sizeof(TOPNQ));
MXS_ABORT_IF_NULL(my_session->top[i]);
my_session->top[i]->sql = NULL;
}
my_session->n_statements = 0;
my_session->total.tv_sec = 0;
my_session->total.tv_usec = 0;
my_session->current = NULL;
my_session->down = down;
my_session->up = up;
if ((remote = session_get_remote(session)) != NULL)
{
my_session->clientHost = MXS_STRDUP_A(remote);
}
else
{
my_session->clientHost = NULL;
}
if ((user = session_get_user(session)) != NULL)
{
my_session->userName = MXS_STRDUP_A(user);
}
else
{
my_session->userName = NULL;
}
my_session->active = 1;
if (my_instance->source && my_session->clientHost && strcmp(my_session->clientHost,
my_instance->source))
{
my_session->active = 0;
}
if (my_instance->user && my_session->userName && strcmp(my_session->userName,
my_instance->user))
{
my_session->active = 0;
}
sprintf(my_session->filename,
"%s.%d",
my_instance->filebase,
my_instance->sessions);
gettimeofday(&my_session->connect, NULL);
}
return (MXS_FILTER_SESSION*)my_session;
}
/**
* Close a session with the filter, this is the mechanism
* by which a filter may cleanup data structure etc.
* In the case of the TOPN filter we simple close the file descriptor.
*
* @param instance The filter instance data
* @param session The session being closed
*/
static void closeSession(MXS_FILTER* instance, MXS_FILTER_SESSION* session)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*) instance;
TOPN_SESSION* my_session = (TOPN_SESSION*) session;
struct timeval diff;
int i;
FILE* fp;
int statements;
gettimeofday(&my_session->disconnect, NULL);
timersub((&my_session->disconnect), &(my_session->connect), &diff);
if ((fp = fopen(my_session->filename, "w")) != NULL)
{
statements = my_session->n_statements != 0 ? my_session->n_statements : 1;
fprintf(fp,
"Top %d longest running queries in session.\n",
my_instance->topN);
fprintf(fp, "==========================================\n\n");
fprintf(fp, "Time (sec) | Query\n");
fprintf(fp, "-----------+-----------------------------------------------------------------\n");
for (i = 0; i < my_instance->topN; i++)
{
if (my_session->top[i]->sql)
{
fprintf(fp,
"%10.3f | %s\n",
(double) ((my_session->top[i]->duration.tv_sec * 1000)
+ (my_session->top[i]->duration.tv_usec / 1000)) / 1000,
my_session->top[i]->sql);
}
}
fprintf(fp, "-----------+-----------------------------------------------------------------\n");
struct tm tm;
localtime_r(&my_session->connect.tv_sec, &tm);
char buffer[32]; // asctime_r documentation requires 26
asctime_r(&tm, buffer);
fprintf(fp, "\n\nSession started %s", buffer);
if (my_session->clientHost)
{
fprintf(fp,
"Connection from %s\n",
my_session->clientHost);
}
if (my_session->userName)
{
fprintf(fp,
"Username %s\n",
my_session->userName);
}
fprintf(fp,
"\nTotal of %d statements executed.\n",
statements);
fprintf(fp,
"Total statement execution time %5d.%d seconds\n",
(int) my_session->total.tv_sec,
(int) my_session->total.tv_usec / 1000);
fprintf(fp,
"Average statement execution time %9.3f seconds\n",
(double) ((my_session->total.tv_sec * 1000)
+ (my_session->total.tv_usec / 1000))
/ (1000 * statements));
fprintf(fp,
"Total connection time %5d.%d seconds\n",
(int) diff.tv_sec,
(int) diff.tv_usec / 1000);
fclose(fp);
}
}
/**
* Free the memory associated with the session
*
* @param instance The filter instance
* @param session The filter session
*/
static void freeSession(MXS_FILTER* instance, MXS_FILTER_SESSION* session)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*) instance;
TOPN_SESSION* my_session = (TOPN_SESSION*) session;
MXS_FREE(my_session->current);
for (int i = 0; i < my_instance->topN; i++)
{
MXS_FREE(my_session->top[i]->sql);
MXS_FREE(my_session->top[i]);
}
MXS_FREE(my_session->top);
MXS_FREE(my_session->clientHost);
MXS_FREE(my_session->userName);
MXS_FREE(my_session->filename);
MXS_FREE(my_session);
return;
}
/**
* The routeQuery entry point. This is passed the query buffer
* to which the filter should be applied. Once applied the
* query should normally be passed to the downstream component
* (filter or router) in the filter chain.
*
* @param instance The filter instance data
* @param session The filter session
* @param queue The query data
*/
static int routeQuery(MXS_FILTER* instance, MXS_FILTER_SESSION* session, GWBUF* queue)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*) instance;
TOPN_SESSION* my_session = (TOPN_SESSION*) session;
char* ptr;
if (my_session->active)
{
if ((ptr = modutil_get_SQL(queue)) != NULL)
{
if ((my_instance->match == NULL
|| regexec(&my_instance->re, ptr, 0, NULL, 0) == 0)
&& (my_instance->exclude == NULL
|| regexec(&my_instance->exre, ptr, 0, NULL, 0) != 0))
{
my_session->n_statements++;
if (my_session->current)
{
MXS_FREE(my_session->current);
}
gettimeofday(&my_session->start, NULL);
my_session->current = ptr;
}
else
{
MXS_FREE(ptr);
}
}
}
/* Pass the query downstream */
return my_session->down->routeQuery(my_session->down->instance,
my_session->down->session,
queue);
}
static int cmp_topn(const void* va, const void* vb)
{
TOPNQ** a = (TOPNQ**) va;
TOPNQ** b = (TOPNQ**) vb;
if ((*b)->duration.tv_sec == (*a)->duration.tv_sec)
{
return (*b)->duration.tv_usec - (*a)->duration.tv_usec;
}
return (*b)->duration.tv_sec - (*a)->duration.tv_sec;
}
static int clientReply(MXS_FILTER* instance,
MXS_FILTER_SESSION* session,
GWBUF* buffer,
const mxs::ReplyRoute& down,
const mxs::Reply& reply)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*) instance;
TOPN_SESSION* my_session = (TOPN_SESSION*) session;
struct timeval tv, diff;
int i, inserted;
if (my_session->current)
{
gettimeofday(&tv, NULL);
timersub(&tv, &(my_session->start), &diff);
timeradd(&(my_session->total), &diff, &(my_session->total));
inserted = 0;
for (i = 0; i < my_instance->topN; i++)
{
if (my_session->top[i]->sql == NULL)
{
my_session->top[i]->sql = my_session->current;
my_session->top[i]->duration = diff;
inserted = 1;
break;
}
}
if (inserted == 0 && ((diff.tv_sec > my_session->top[my_instance->topN - 1]->duration.tv_sec)
|| (diff.tv_sec == my_session->top[my_instance->topN - 1]->duration.tv_sec
&& diff.tv_usec
> my_session->top[my_instance->topN - 1]->duration.tv_usec)))
{
MXS_FREE(my_session->top[my_instance->topN - 1]->sql);
my_session->top[my_instance->topN - 1]->sql = my_session->current;
my_session->top[my_instance->topN - 1]->duration = diff;
inserted = 1;
}
if (inserted)
{
qsort(my_session->top,
my_instance->topN,
sizeof(TOPNQ*),
cmp_topn);
}
else
{
MXS_FREE(my_session->current);
}
my_session->current = NULL;
}
/* Pass the result upstream */
return my_session->up->clientReply(my_session->up->instance,
my_session->up->session,
buffer,
down,
reply);
}
/**
* Diagnostics routine
*
* If fsession is NULL then print diagnostics on the filter
* instance as a whole, otherwise print diagnostics for the
* particular session.
*
* @param instance The filter instance
* @param fsession Filter session, may be NULL
*/
static json_t* diagnostics(const MXS_FILTER* instance, const MXS_FILTER_SESSION* fsession)
{
TOPN_INSTANCE* my_instance = (TOPN_INSTANCE*)instance;
TOPN_SESSION* my_session = (TOPN_SESSION*)fsession;
json_t* rval = json_object();
json_object_set_new(rval, "report_size", json_integer(my_instance->topN));
if (my_instance->source)
{
json_object_set_new(rval, "source", json_string(my_instance->source));
}
if (my_instance->user)
{
json_object_set_new(rval, "user", json_string(my_instance->user));
}
if (my_instance->match)
{
json_object_set_new(rval, "match", json_string(my_instance->match));
}
if (my_instance->exclude)
{
json_object_set_new(rval, "exclude", json_string(my_instance->exclude));
}
if (my_session)
{
json_object_set_new(rval, "session_filename", json_string(my_session->filename));
json_t* arr = json_array();
for (int i = 0; i < my_instance->topN; i++)
{
if (my_session->top[i]->sql)
{
double exec_time = ((my_session->top[i]->duration.tv_sec * 1000.0)
+ (my_session->top[i]->duration.tv_usec / 1000.0)) / 1000.0;
json_t* obj = json_object();
json_object_set_new(obj, "rank", json_integer(i + 1));
json_object_set_new(obj, "time", json_real(exec_time));
json_object_set_new(obj, "sql", json_string(my_session->top[i]->sql));
json_array_append_new(arr, obj);
}
}
json_object_set_new(rval, "top_queries", arr);
}
return rval;
}
/**
* Capability routine.
*
* @return The capabilities of the filter.
*/
static uint64_t getCapabilities(MXS_FILTER* instance)
{
return RCAP_TYPE_NONE;
}
| 32.103659
| 104
| 0.553561
|
DatabasKarlsson
|
61aad0da5061a8b7892b1bb71bced6592fe61ac2
| 1,735
|
hpp
|
C++
|
src/Factory/Simulation/BFER/BFER_std.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2022-02-17T08:47:47.000Z
|
2022-02-17T08:47:47.000Z
|
src/Factory/Simulation/BFER/BFER_std.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | null | null | null |
src/Factory/Simulation/BFER/BFER_std.hpp
|
WilliamMajor/aff3ct
|
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
|
[
"MIT"
] | 1
|
2021-11-24T01:54:41.000Z
|
2021-11-24T01:54:41.000Z
|
#ifndef FACTORY_SIMULATION_BFER_STD_HPP_
#define FACTORY_SIMULATION_BFER_STD_HPP_
#include <string>
#include <map>
#include "Tools/Arguments/Argument_tools.hpp"
#include "Factory/Module/Codec/Codec_SIHO.hpp"
#include "Factory/Simulation/BFER/BFER.hpp"
namespace aff3ct
{
namespace simulation
{
template <typename B, typename R, typename Q>
class BFER_std;
}
}
namespace aff3ct
{
namespace factory
{
extern const std::string BFER_std_name;
extern const std::string BFER_std_prefix;
struct BFER_std : BFER
{
class parameters : public BFER::parameters
{
public:
// ------------------------------------------------------------------------------------------------- PARAMETERS
// module parameters
// Codec_SIHO::parameters *cdc = nullptr;
// ---------------------------------------------------------------------------------------------------- METHODS
explicit parameters(const std::string &p = BFER_std_prefix);
virtual ~parameters() = default;
BFER_std::parameters* clone() const;
// setters
// void set_cdc(Codec_SIHO::parameters *cdc) { this->cdc = cdc; BFER::parameters::set_cdc(cdc); }
const Codec_SIHO::parameters* get_cdc() const;
// parameters construction
void get_description(tools::Argument_map_info &args) const;
void store (const tools::Argument_map_value &vals);
void get_headers (std::map<std::string,header_list>& headers, const bool full = true) const;
// builder
template <typename B = int, typename R = float, typename Q = R>
simulation::BFER_std<B,R,Q>* build() const;
};
template <typename B = int, typename R = float, typename Q = R>
static simulation::BFER_std<B,R,Q>* build(const parameters ¶ms);
};
}
}
#endif /* FACTORY_SIMULATION_BFER_STD_HPP_ */
| 28.442623
| 113
| 0.647839
|
WilliamMajor
|
61ab43eabbe07d8144ffb1874ee17c32b2ce12b0
| 1,016
|
cpp
|
C++
|
source/cards/sources/move-condition.cpp
|
mexus/medici2
|
8ffadc0f72459e5b59f12460575925e5a578a389
|
[
"MIT"
] | null | null | null |
source/cards/sources/move-condition.cpp
|
mexus/medici2
|
8ffadc0f72459e5b59f12460575925e5a578a389
|
[
"MIT"
] | null | null | null |
source/cards/sources/move-condition.cpp
|
mexus/medici2
|
8ffadc0f72459e5b59f12460575925e5a578a389
|
[
"MIT"
] | null | null | null |
#include <cards/move-condition.h>
#include <algorithm>
namespace cards {
MoveCondition::MoveCondition(size_t position, const std::shared_ptr<Condition>& condition)
: position_(position), condition_(condition) {}
bool MoveCondition::CheckSequence(const std::vector<Card>& cards) const {
if (position_ >= cards.size()) {
return false;
}
std::vector<Card> shifted_deck(cards.begin() + position_, cards.end());
return condition_->CheckSequence(shifted_deck);
}
std::vector<Sequence> MoveCondition::GetVariants(const Sequence& applied_sequence,
Storage storage) const {
auto shifted_applied_sequence = applied_sequence.ShiftLeft(position_);
auto variants = condition_->GetVariants(shifted_applied_sequence, storage);
std::transform(
variants.begin(), variants.end(), variants.begin(),
[this](const Sequence& sequence) { return sequence.ShiftRight(position_); });
return applied_sequence + variants;
}
}
| 36.285714
| 90
| 0.690945
|
mexus
|
61abed85910aa62dad08a3dc827b63f826462cba
| 3,872
|
hpp
|
C++
|
include/GlobalNamespace/LightPairRotationEventEffect_RotationData.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/LightPairRotationEventEffect_RotationData.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/LightPairRotationEventEffect_RotationData.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: LightPairRotationEventEffect
#include "GlobalNamespace/LightPairRotationEventEffect.hpp"
// Including type: UnityEngine.Quaternion
#include "UnityEngine/Quaternion.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x38
#pragma pack(push, 1)
// Autogenerated type: LightPairRotationEventEffect/RotationData
class LightPairRotationEventEffect::RotationData : public ::Il2CppObject {
public:
// public System.Boolean enabled
// Size: 0x1
// Offset: 0x10
bool enabled;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: enabled and: rotationSpeed
char __padding0[0x3] = {};
// public System.Single rotationSpeed
// Size: 0x4
// Offset: 0x14
float rotationSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// public UnityEngine.Quaternion startRotation
// Size: 0x10
// Offset: 0x18
UnityEngine::Quaternion startRotation;
// Field size check
static_assert(sizeof(UnityEngine::Quaternion) == 0x10);
// public UnityEngine.Transform transform
// Size: 0x8
// Offset: 0x28
UnityEngine::Transform* transform;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// public System.Single startRotationAngle
// Size: 0x4
// Offset: 0x30
float startRotationAngle;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single rotationAngle
// Size: 0x4
// Offset: 0x34
float rotationAngle;
// Field size check
static_assert(sizeof(float) == 0x4);
// Creating value type constructor for type: RotationData
RotationData(bool enabled_ = {}, float rotationSpeed_ = {}, UnityEngine::Quaternion startRotation_ = {}, UnityEngine::Transform* transform_ = {}, float startRotationAngle_ = {}, float rotationAngle_ = {}) noexcept : enabled{enabled_}, rotationSpeed{rotationSpeed_}, startRotation{startRotation_}, transform{transform_}, startRotationAngle{startRotationAngle_}, rotationAngle{rotationAngle_} {}
// public System.Void .ctor()
// Offset: 0x11FED2C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LightPairRotationEventEffect::RotationData* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::LightPairRotationEventEffect::RotationData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LightPairRotationEventEffect::RotationData*, creationType>()));
}
}; // LightPairRotationEventEffect/RotationData
#pragma pack(pop)
static check_size<sizeof(LightPairRotationEventEffect::RotationData), 52 + sizeof(float)> __GlobalNamespace_LightPairRotationEventEffect_RotationDataSizeCheck;
static_assert(sizeof(LightPairRotationEventEffect::RotationData) == 0x38);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LightPairRotationEventEffect::RotationData*, "", "LightPairRotationEventEffect/RotationData");
| 45.552941
| 398
| 0.713326
|
darknight1050
|
ba06e521487c08b81adcb7f1a4e0f43718508383
| 914
|
hpp
|
C++
|
gui/dialogs/dialogeditunit.hpp
|
lkeegan/spatial-model-editor
|
5dcb06550607b0a734acddd8b719035b68e35307
|
[
"MIT"
] | 4
|
2019-07-18T15:05:09.000Z
|
2020-03-14T09:50:07.000Z
|
gui/dialogs/dialogeditunit.hpp
|
lkeegan/spatial-model-editor
|
5dcb06550607b0a734acddd8b719035b68e35307
|
[
"MIT"
] | 328
|
2019-06-30T12:03:01.000Z
|
2020-10-05T15:56:35.000Z
|
gui/dialogs/dialogeditunit.hpp
|
lkeegan/spatial-model-editor
|
5dcb06550607b0a734acddd8b719035b68e35307
|
[
"MIT"
] | 1
|
2019-06-08T22:47:14.000Z
|
2019-06-08T22:47:14.000Z
|
#pragma once
#include "sme/model_units.hpp"
#include <QDialog>
#include <memory>
namespace Ui {
class DialogEditUnit;
}
class DialogEditUnit : public QDialog {
Q_OBJECT
public:
explicit DialogEditUnit(const sme::model::Unit &unit,
const QString &unitType = {},
QWidget *parent = nullptr);
~DialogEditUnit();
const sme::model::Unit &getUnit() const;
private:
std::unique_ptr<Ui::DialogEditUnit> ui;
sme::model::Unit u;
bool validMultipler{true};
bool validScale{true};
bool validExponent{true};
void updateLblBaseUnits();
void setIsValidState(QWidget *widget, bool valid,
const QString &errorMessage = {});
void txtName_textEdited(const QString &text);
void txtMultiplier_textEdited(const QString &text);
void txtScale_textEdited(const QString &text);
void txtExponent_textEdited(const QString &text);
};
| 26.114286
| 57
| 0.683807
|
lkeegan
|
ba089712b85354f90687f6f9481f5a94ba20b2a7
| 1,271
|
cpp
|
C++
|
floating-point/sse-avx-mix.cpp
|
Secure-AI-Systems-Group/Hardware-Effects
|
9839e0e2a4cfe7bb7be15c2a3050b4e279b8a67b
|
[
"MIT"
] | 2,434
|
2018-11-18T20:31:23.000Z
|
2022-03-22T14:04:01.000Z
|
floating-point/sse-avx-mix.cpp
|
xiaoxiaohuoshan/hardware-effects
|
6748195c1799b3a5ea8eb43ae4ce594c865639d8
|
[
"MIT"
] | 22
|
2018-11-19T03:14:38.000Z
|
2022-01-21T07:48:46.000Z
|
floating-point/sse-avx-mix.cpp
|
xiaoxiaohuoshan/hardware-effects
|
6748195c1799b3a5ea8eb43ae4ce594c865639d8
|
[
"MIT"
] | 136
|
2018-11-19T00:57:18.000Z
|
2022-03-22T11:47:58.000Z
|
/**
* Code adapted from https://stackoverflow.com/questions/41303780/why-is-this-sse-code-6-times-slower-without-vzeroupper-on-skylake
*/
#include <immintrin.h>
#include <iostream>
#include <chrono>
#ifndef REPETITIONS
#define REPETITIONS 100 * 1024 * 1024
#endif
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: sse-avx-mix <zero-upper>" << std::endl;
return 1;
}
// execute AVX-256 instruction, just to make sure
float data[16];
for (int i = 0; i < 16; i++) data[i] = (float) i;
__asm__ __volatile__(
"vmovups (%0, %%rcx), %%ymm0" // move data to YMM0
:: "r"(data): "%ymm0"
);
using Clock = std::chrono::steady_clock;
auto start = Clock::now();
if (std::stoi(argv[1]) == 1)
{
__asm__ __volatile__("vzeroupper" :::); // zero upper parts of AVX registers
}
int r = 0;
for (int i = 0; i < REPETITIONS; i++)
{
__m128d a = _mm_set_sd(i);
__m128d b = _mm_add_sd(a, a);
__m128d sqr = _mm_sqrt_sd(a, b);
r += _mm_movemask_pd(sqr);
}
std::cerr << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count() << std::endl;
std::cout << r << std::endl;
return 0;
}
| 24.921569
| 131
| 0.572777
|
Secure-AI-Systems-Group
|
ba0a217e3671c14dc9bab13e91ecd1f6b87fd1a6
| 1,901
|
cpp
|
C++
|
SampleMathematics/NonlocalBlowup/GpuAvrPyramid2.cpp
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | null | null | null |
SampleMathematics/NonlocalBlowup/GpuAvrPyramid2.cpp
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | null | null | null |
SampleMathematics/NonlocalBlowup/GpuAvrPyramid2.cpp
|
CRIMSONCardiovascularModelling/WildMagic5
|
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
|
[
"BSL-1.0"
] | null | null | null |
// Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.3.0 (2010/09/07)
#include "GpuAvrPyramid2.h"
const GLchar* GpuAvrPyramid2::msQuadAverage =
"float result = 0.25*(f00 + f10 + f01 + f11);";
//----------------------------------------------------------------------------
GpuAvrPyramid2::GpuAvrPyramid2 (int dimension0, int dimension1,
const Image2<float>& initial, bool& success)
:
GpuPyramid2("", msQuadAverage, dimension0, dimension1, initial, success),
mAverage(0.0f)
{
}
//----------------------------------------------------------------------------
GpuAvrPyramid2::GpuAvrPyramid2 (int dimension0, int dimension1,
GLuint texture0, GLuint texture1, GLuint frameBuffer0,
GLuint frameBuffer1, bool& success)
:
GpuPyramid2("", msQuadAverage, dimension0, dimension1, texture0, texture1,
frameBuffer0, frameBuffer1, success),
mAverage(0.0f)
{
}
//----------------------------------------------------------------------------
GpuAvrPyramid2::~GpuAvrPyramid2 ()
{
}
//----------------------------------------------------------------------------
float GpuAvrPyramid2::GetAverage () const
{
return mAverage;
}
//----------------------------------------------------------------------------
bool GpuAvrPyramid2::OnPostDraw (int level, int, int frameBuffer)
{
if (level + 1 == mNumLevels)
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFrameBuffer[frameBuffer]);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
glReadPixels(0, 0, 1, 1, GL_RED, GL_FLOAT, &mAverage);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glReadBuffer(GL_BACK);
}
return true;
}
//----------------------------------------------------------------------------
| 34.563636
| 78
| 0.530247
|
CRIMSONCardiovascularModelling
|
ba0a755029a67c45441111439059afcbf1ae19ec
| 629
|
cpp
|
C++
|
src/ChainSword/src/StateMachine/States/StartState.cpp
|
LePetitAtelierDeJon/ChainSword
|
acdcf8d26589eeb6df2c8db4caf39bf21b990c14
|
[
"MIT"
] | null | null | null |
src/ChainSword/src/StateMachine/States/StartState.cpp
|
LePetitAtelierDeJon/ChainSword
|
acdcf8d26589eeb6df2c8db4caf39bf21b990c14
|
[
"MIT"
] | null | null | null |
src/ChainSword/src/StateMachine/States/StartState.cpp
|
LePetitAtelierDeJon/ChainSword
|
acdcf8d26589eeb6df2c8db4caf39bf21b990c14
|
[
"MIT"
] | null | null | null |
#include "StateMachine/States/StartState.h"
#include "ChainSword.h"
void StartState::execute(ChainSword *context, unsigned long millis)
{
context->lightController()->execute(millis);
if (context->lightController()->isEffectStopped(STARTUP_ANIMATION))
{
stateMachine_->makeTransition(IDLE_TRANSITION, millis);
}
}
void StartState::enter(ChainSword *context, unsigned long millis)
{
Serial.println("-- Starting... --");
context->lightController()->SetEffect(STARTUP_ANIMATION, millis);
}
void StartState::exit(ChainSword *context, unsigned long millis)
{
Serial.println("-- Setup Done --");
}
| 28.590909
| 71
| 0.720191
|
LePetitAtelierDeJon
|
ba0adadbe7d2b43840a7d5be7084e3da64df25a9
| 2,097
|
cpp
|
C++
|
src/FastAccelStepperHoming.cpp
|
HX2003/FastAccelStepperHoming
|
6e4603242d38ca43ebb92011ec92c0ac4e2591ba
|
[
"MIT"
] | 1
|
2022-03-07T06:21:26.000Z
|
2022-03-07T06:21:26.000Z
|
src/FastAccelStepperHoming.cpp
|
HX2003/FastAccelStepperHoming
|
6e4603242d38ca43ebb92011ec92c0ac4e2591ba
|
[
"MIT"
] | null | null | null |
src/FastAccelStepperHoming.cpp
|
HX2003/FastAccelStepperHoming
|
6e4603242d38ca43ebb92011ec92c0ac4e2591ba
|
[
"MIT"
] | null | null | null |
#include "FastAccelStepperHoming.h"
void FastAccelStepperHoming::init(FastAccelStepper* stepper) {
_stepper = stepper;
}
void FastAccelStepperHoming::setLimitPin(uint8_t limitPin, uint8_t mode){
_limitPin = limitPin;
_limitPinSet = true;
pinMode(limitPin, mode);
_limitPinState = digitalRead(limitPin);
attachInterrupt(digitalPinToInterrupt(limitPin), std::bind(&FastAccelStepperHoming::limit_isr, this), CHANGE);
}
void FastAccelStepperHoming::setHomingSpeedInUs(uint32_t homing_step_us) {
_homing_step_us = homing_step_us;
}
void FastAccelStepperHoming::setHomingPulloffSteps(uint32_t homing_pulloff_steps) {
_homing_pulloff_steps = homing_pulloff_steps;
}
void FastAccelStepperHoming::setInvertLimitPin(bool invertLimitPin) {
_invertLimitPin = invertLimitPin;
}
void FastAccelStepperHoming::home() {
if(_limitPinSet) {
_initial_step_us = _stepper->getSpeedInUs();
if(_homing_step_us != 0){
_stepper->setSpeedInUs(_homing_step_us);
}
if(_limitPinState == _invertLimitPin) {
//We are some distance away from the limit sensor
//So try to move towards it, assuming it is in the negative direction
_homingHome = true;
_stepper->moveByAcceleration(-_stepper->getAcceleration());
} else {
//We are near the limit sensor
_homingHome = false;
_stepper->moveByAcceleration(_stepper->getAcceleration());
}
_isHoming = true;
}
}
bool FastAccelStepperHoming::isHomingComplete(){
if(!_isHoming && !_stepper->isRunning()){
return true;
}
return false;
}
void ARDUINO_ISR_ATTR FastAccelStepperHoming::limit_isr() {
bool pinState = digitalRead(_limitPin); // Save current state so we can compare with the last saved pin state to ignore false triggers
if(_isHoming && _limitPinState != pinState) {
if((!pinState == _invertLimitPin && _homingHome) || (pinState == _invertLimitPin && !_homingHome)){
_stepper->forceStopAndNewPosition(0);
_stepper->setSpeedInUs(_initial_step_us);
_stepper->move(_homing_pulloff_steps);
}
_isHoming = false; //Note, the stepper may still be in motion
}
_limitPinState = pinState;
}
| 29.957143
| 135
| 0.756319
|
HX2003
|
ba0c1dcfde039fc5eb336b2794999e031680816c
| 1,749
|
hpp
|
C++
|
src/Utils/framebuffer.hpp
|
AlexanderVeselov/RayTracing
|
d6df361c1054a1ebaf67c82805c44f94a4cda7c7
|
[
"MIT"
] | 90
|
2017-08-06T10:13:59.000Z
|
2022-03-19T09:49:43.000Z
|
src/Utils/framebuffer.hpp
|
AlexanderVeselov/RayTracing
|
d6df361c1054a1ebaf67c82805c44f94a4cda7c7
|
[
"MIT"
] | 2
|
2017-06-08T02:16:56.000Z
|
2020-03-24T01:10:48.000Z
|
src/Utils/framebuffer.hpp
|
AlexanderVeselov/RayTracing
|
d6df361c1054a1ebaf67c82805c44f94a4cda7c7
|
[
"MIT"
] | 15
|
2017-08-06T12:58:54.000Z
|
2022-03-31T05:45:46.000Z
|
/*****************************************************************************
MIT License
Copyright(c) 2021 Alexander Veselov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softwareand 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 noticeand 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.
*****************************************************************************/
#pragma once
#include "mathlib/mathlib.hpp"
#include "GpuWrappers/gl_graphics_pipeline.hpp"
class Framebuffer
{
public:
Framebuffer(std::uint32_t width, std::uint32_t height);
void Present();
std::uint32_t GetWidth() const { return width_; }
std::uint32_t GetHeight() const { return height_; }
GLuint GetGLImage() const { return render_texture_; }
private:
std::uint32_t width_;
std::uint32_t height_;
GraphicsPipeline draw_pipeline_;
GLuint render_texture_;
};
| 38.866667
| 79
| 0.701544
|
AlexanderVeselov
|
ba0c5c0d5715b75b3a29ee7f0b91f1f7a5c18466
| 416
|
hh
|
C++
|
src/events/StdioMessages.hh
|
D15C0DE/openMSX
|
5119a9657de4b82115c745f670cdc55dc7363133
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 320
|
2015-06-16T20:32:33.000Z
|
2022-03-26T17:03:27.000Z
|
src/events/StdioMessages.hh
|
D15C0DE/openMSX
|
5119a9657de4b82115c745f670cdc55dc7363133
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2,592
|
2015-05-30T12:12:21.000Z
|
2022-03-31T17:16:15.000Z
|
src/events/StdioMessages.hh
|
D15C0DE/openMSX
|
5119a9657de4b82115c745f670cdc55dc7363133
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 74
|
2015-06-18T19:51:15.000Z
|
2022-03-24T15:09:33.000Z
|
#ifndef STDIOMESSAGES_HH
#define STDIOMESSAGES_HH
#include "CliListener.hh"
namespace openmsx {
class StdioMessages final : public CliListener
{
public:
void log(CliComm::LogLevel level, std::string_view message) noexcept override;
void update(CliComm::UpdateType type, std::string_view machine,
std::string_view name, std::string_view value) noexcept override;
};
} // namespace openmsx
#endif
| 20.8
| 79
| 0.759615
|
D15C0DE
|
ba0d5bef7e5e1df7535ba0b7f2877bbd9a7ef82a
| 686
|
cpp
|
C++
|
codechef/FEB20/CASH.cpp
|
udayan14/Competitive_Coding
|
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
|
[
"MIT"
] | null | null | null |
codechef/FEB20/CASH.cpp
|
udayan14/Competitive_Coding
|
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
|
[
"MIT"
] | null | null | null |
codechef/FEB20/CASH.cpp
|
udayan14/Competitive_Coding
|
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<limits.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
int n,k;
cin >> n >> k;
unsigned long long int a[n];
for(int i=0 ; i<n ; ++i)
cin >> a[i];
unsigned long long int fwd[n];
unsigned long long int bwd[n];
fwd[0] = a[0] % k;
for(int i=1 ; i<n ; ++i)
fwd[i] = (fwd[i-1] + a[i])%k;
bwd[n-1] = 0;
for(int i=n-2 ; i>=0 ; --i){
bwd[i] = bwd[i+1] + (k - (a[i+1]%k))%k;
}
long long int curr_min = INT_MAX;
for(int i=0 ; i<n ; ++i){
if(fwd[i]>=bwd[i] && fwd[i]-bwd[i]<=curr_min){
curr_min = fwd[i] - bwd[i];
}
}
cout << curr_min << "\n";
}
}
| 20.176471
| 49
| 0.514577
|
udayan14
|
ba114b94affdfc2a34e94922af627fc0b07c2c2d
| 6,955
|
cpp
|
C++
|
tsp_tabu_search/testing_unit.cpp
|
chengwei920412/travelling-salesman-problem-tsp
|
b99e9a2743dd340778ed3db70a4eb6c4fc8cdfab
|
[
"MIT"
] | 2
|
2021-12-15T13:37:28.000Z
|
2021-12-15T13:37:32.000Z
|
tsp_tabu_search/testing_unit.cpp
|
chengwei920412/travelling-salesman-problem-tsp
|
b99e9a2743dd340778ed3db70a4eb6c4fc8cdfab
|
[
"MIT"
] | null | null | null |
tsp_tabu_search/testing_unit.cpp
|
chengwei920412/travelling-salesman-problem-tsp
|
b99e9a2743dd340778ed3db70a4eb6c4fc8cdfab
|
[
"MIT"
] | 2
|
2021-05-03T07:47:22.000Z
|
2021-11-30T05:59:59.000Z
|
#include "testing_unit.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include "timer.h"
#include <list>
testing_unit::testing_unit(string input_file_name, int number_of_repeats, int optimal_path_cost,
vector<int> optimal_path_nodes)
{
input_file_name_ = input_file_name;
number_of_repeats_ = number_of_repeats;
optimal_path_.cost = optimal_path_cost;
optimal_path_.nodes = optimal_path_nodes;
load_graph(input_file_name);
}
testing_unit::~testing_unit()
{
delete graph_;
}
void testing_unit::run_tests()
{
cout << input_file_name_ << endl;
timer t{};
for (int i = 0; i < number_of_repeats_; i++)
{
solution_path_.cost = 0;
solution_path_.nodes.clear();
t.start();
solution_path_ = run_tabu();
t.stop();
save_data_.times.push_back(t.elapsed_time());
save_data_.solutions.push_back(solution_path_);
save_data_.errors.push_back(calculate_path_cost_error(solution_path_.cost));
print_test_result(i);
}
cout << endl;
}
double testing_unit::random01()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
return dis(gen);
}
int testing_unit::random_int(int a, int b)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(a, b);
return dist(gen);
}
int testing_unit::myrandom(int i)
{
return std::rand() % i;
}
testing_unit::path testing_unit::run_tabu()
{
tabu_list tabu = { graph_->get_size() / 4 };
path x_0 = random_start_solution();
path x_opt = x_0;
int ctr = 0;
int max_iterations = (int)pow(graph_->get_size(), 2);
high_resolution_clock::time_point start_time = high_resolution_clock::now();
for (int i = 0; i < max_iterations; i++)
{
ctr++;
x_0 = aspiration_plus(tabu, x_0, x_opt.cost);
if (x_0.cost < x_opt.cost)
{
x_opt = x_0;
ctr = 0;
}
tabu.add(x_0.att_i, x_0.att_j, graph_->get_size()/3);
//tabu.add(x_0.nodes, graph_->get_size()/3);
tabu.update_cadences_and_delete_elements();
if (ctr >= graph_->get_size())
{
ctr = 0;
x_0 = random_start_solution();
if (x_0.cost < x_opt.cost)
{
x_opt = x_0;
}
}
if (duration_cast<duration<double>>(high_resolution_clock::now() - start_time).count() > 120.0)
{
break;
}
}
return x_opt;
}
testing_unit::path testing_unit::random_start_solution()
{
path p;
p.nodes.push_back(0);
for (int i = 1; i < graph_->get_size(); i++)
{
p.nodes.push_back(i);
}
p.nodes.push_back(0);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(p.nodes.begin() + 1, p.nodes.end() - 1, std::default_random_engine(seed));
p.cost = calculate_path_cost(p.nodes);
return p;
}
testing_unit::path testing_unit::greedy_start_solution()
{
bool* in_path = new bool[graph_->get_size()];
in_path[0] = true;
for (int i = 1; i < graph_->get_size(); i++)
{
in_path[i] = false;
}
path p;
p.nodes.push_back(0);
for (int i = 1; i < graph_->get_size(); i++)
{
int min_node_id = -1;
int min_node_cost = INT_MAX;
for (int j = 1; j < graph_->get_size(); j++)
{
if (in_path[j] == true)
continue;
int cost = graph_->get_value_at(i - 1, j);
if (cost < min_node_cost)
{
min_node_id = j;
min_node_cost = cost;
}
}
if (min_node_id != -1)
{
p.nodes.push_back(min_node_id);
in_path[min_node_id] = true;
}
}
p.nodes.push_back(0);
p.cost = calculate_path_cost(p.nodes);
delete[] in_path;
return p;
}
std::vector<testing_unit::path> testing_unit::find_n_solutions(path p)
{
std::vector<path> paths = {};
for (int i = 1; i < p.nodes.size() - 3; i++)
{
for (int j = i + 1; j < p.nodes.size() - 2; j++)
{
path path_swap = p;
std::swap(path_swap.nodes[i], path_swap.nodes[j]);
path_swap.cost = calculate_path_cost(path_swap.nodes);
path_swap.att_i = i;
path_swap.att_j = j;
paths.push_back(path_swap);
}
}
return paths;
}
void testing_unit::print_test_result(int i)
{
cout << "[" << i + 1 << "/" << number_of_repeats_ << "]";
cout << " Optimal path cost: " << optimal_path_.cost << endl;
cout << "\tOptimal path nodes: ";
if (optimal_path_.nodes.empty() || optimal_path_.nodes[0] == -1) cout << "NoData";
else for (auto n : optimal_path_.nodes) cout << n << " ";
cout << endl;
cout << "\tSolution path cost: " << solution_path_.cost << endl;
cout << "\tSolution path nodes: ";
if (solution_path_.nodes.empty()) cout << "NoData";
else for (auto n : solution_path_.nodes) cout << n << " ";
cout << endl;
cout << "\tSolution path cost error: ";
cout << fixed << setprecision(3) << save_data_.errors.back() * 100.0 << "%" << endl;
cout << "\tTime: ";
cout << fixed << setprecision(9) << save_data_.times.back() << endl << endl;
}
void testing_unit::save_tests_results(ofstream& fout)
{
fout << input_file_name_ << "\t";
fout << number_of_repeats_ << "\t";
fout << optimal_path_.cost << "\t";
if (optimal_path_.nodes.empty()) fout << "NoData.";
else for (auto n : optimal_path_.nodes) fout << n << " ";
fout << endl;
for (int i = 0; i < save_data_.times.size(); i++)
{
fout << fixed << setprecision(9) << save_data_.times[i];
fout << "\t";
fout << save_data_.solutions[i].cost;
fout << "\t";
fout << fixed << setprecision(2) << save_data_.errors[i] * 100.0;
fout << "\t";
for (auto n : save_data_.solutions[i].nodes)
{
fout << n << " ";
}
fout << endl;
}
fout << endl;
}
testing_unit::path testing_unit::aspiration_plus(tabu_list tabu, path x0, int best_cost)
{
std::vector<path> n_solutions = find_n_solutions(x0);
for (auto& x : n_solutions)
{
x.mval = x.cost - x0.cost;
}
std::sort(n_solutions.begin(), n_solutions.end(), [](const path& left, const path& right)
{
return (left.mval < right.mval);
});
for (auto& x : n_solutions)
{
if (x.mval < 0)
{
if (!tabu.contains(x.att_i, x.att_j) || x.cost < best_cost)
{
return x;
break;
}
}
else
{
return x0;
}
}
return x0;
}
void testing_unit::load_graph(string file_name)
{
ifstream fin(file_name);
if (fin.is_open())
{
int graph_size;
fin >> graph_size;
graph_ = new graph(graph_size);
graph_->load_from_file(fin);
}
fin.close();
}
int testing_unit::calculate_path_cost(vector<int> nodes)
{
int cost = 0;
for (int i = 0; i < nodes.size() - 1; i++)
{
int index_a = nodes[i];
int index_b = nodes[i + 1];
cost += graph_->get_value_at(index_a, index_b);
}
return cost;
}
double testing_unit::calculate_path_cost_error(int cost)
{
// If optimal solution path cost is not given.
if (optimal_path_.cost == 0)
{
return -1;
}
return (static_cast<double>(cost) - optimal_path_.cost) / optimal_path_.cost;
}
| 22.079365
| 98
| 0.617973
|
chengwei920412
|
ba125dbf7a15ef39bec7e268666208bc18432079
| 384
|
hpp
|
C++
|
src/problems/101-150/133/problem133.hpp
|
abeccaro/project-euler
|
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
|
[
"MIT"
] | 1
|
2019-12-25T10:17:15.000Z
|
2019-12-25T10:17:15.000Z
|
src/problems/101-150/133/problem133.hpp
|
abeccaro/project-euler
|
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
|
[
"MIT"
] | null | null | null |
src/problems/101-150/133/problem133.hpp
|
abeccaro/project-euler
|
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
|
[
"MIT"
] | null | null | null |
//
// Created by Alex Beccaro on 25/11/2019.
//
#ifndef PROJECT_EULER_PROBLEM133_HPP
#define PROJECT_EULER_PROBLEM133_HPP
#include <cstdint>
namespace problems {
class problem133 {
public:
/**
* Solves problem
* @return The solution
*/
static uint32_t solve(uint32_t ub = 100000);
};
}
#endif //PROJECT_EULER_PROBLEM133_HPP
| 16.695652
| 52
| 0.645833
|
abeccaro
|
ba1b25afef3bc02ff3523d93e72e142fb339fb7a
| 320
|
hpp
|
C++
|
src/ControlSystem/NamespaceDocs.hpp
|
kidder/spectre
|
97ae95f72320f9f67895d3303824e64de6fd9077
|
[
"MIT"
] | 117
|
2017-04-08T22:52:48.000Z
|
2022-03-25T07:23:36.000Z
|
src/ControlSystem/NamespaceDocs.hpp
|
GitHimanshuc/spectre
|
4de4033ba36547113293fe4dbdd77591485a4aee
|
[
"MIT"
] | 3,177
|
2017-04-07T21:10:18.000Z
|
2022-03-31T23:55:59.000Z
|
src/ControlSystem/NamespaceDocs.hpp
|
geoffrey4444/spectre
|
9350d61830b360e2d5b273fdd176dcc841dbefb0
|
[
"MIT"
] | 85
|
2017-04-07T19:36:13.000Z
|
2022-03-01T10:21:00.000Z
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
/// \ingroup ControlSystemGroup
/// Control systems and related functionality
namespace control_system {
/// \ingroup ControlSystemGroup
/// All Actions related to the control system
namespace Actions {}
} // namespace control_system
| 24.615385
| 45
| 0.76875
|
kidder
|
ba1c05878f68058d93ddf1774e029126cbecc908
| 1,277
|
cpp
|
C++
|
cudaaligner/src/alignment.cpp
|
r-mafi/ClaraGenomicsAnalysis
|
a33d606af7902f27d5cf86a80099061bb1a34603
|
[
"Apache-2.0"
] | null | null | null |
cudaaligner/src/alignment.cpp
|
r-mafi/ClaraGenomicsAnalysis
|
a33d606af7902f27d5cf86a80099061bb1a34603
|
[
"Apache-2.0"
] | 1
|
2020-07-17T13:57:56.000Z
|
2020-07-17T13:57:56.000Z
|
cudaaligner/src/alignment.cpp
|
r-mafi/ClaraGenomicsAnalysis
|
a33d606af7902f27d5cf86a80099061bb1a34603
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include <claraparabricks/genomeworks/cudaaligner/alignment.hpp>
#include <iostream>
namespace claraparabricks
{
namespace genomeworks
{
namespace cudaaligner
{
std::ostream& operator<<(std::ostream& os, const FormattedAlignment& formatted_alignment)
{
std::size_t line_length = (formatted_alignment.linebreak_after == 0) ? formatted_alignment.query.size() : formatted_alignment.linebreak_after;
for (std::size_t i = 0; i < formatted_alignment.query.size(); i += line_length)
{
os << formatted_alignment.query.substr(i, line_length) << '\n'
<< formatted_alignment.pairing.substr(i, line_length) << '\n'
<< formatted_alignment.target.substr(i, line_length) << '\n';
}
os << std::endl;
return os;
}
} // namespace cudaaligner
} // namespace genomeworks
} // namespace claraparabricks
| 30.404762
| 146
| 0.7361
|
r-mafi
|
ba1c50187f157d531898b4c89bb0dab94a5a223b
| 1,378
|
hpp
|
C++
|
Doremi/Core/Include/EventHandler/Events/DamageTakenEvent.hpp
|
meraz/doremi
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:05.000Z
|
2020-03-23T15:42:05.000Z
|
Doremi/Core/Include/EventHandler/Events/DamageTakenEvent.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | null | null | null |
Doremi/Core/Include/EventHandler/Events/DamageTakenEvent.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:06.000Z
|
2020-03-23T15:42:06.000Z
|
#include <Doremi/Core/Include/EventHandler/Events/Event.hpp>
namespace Doremi
{
namespace Core
{
/**
Contains info on damage taken, make sure not to send to much of these since they are sent over network
*/
struct DamageTakenEvent : public Event
{
EntityID entityId;
float damage;
DamageTakenEvent(const float& p_damage, const EntityID& p_entityId)
: damage(p_damage), entityId(p_entityId), Event(EventType::DamageTaken)
{
}
DamageTakenEvent() : entityId(0), damage(0), Event(EventType::DamageTaken) {}
/**
Write object to stream
*/
void Write(Streamer* p_streamer, uint32_t& op_bitsWritten) override
{
p_streamer->WriteUnsignedInt32(entityId);
p_streamer->WriteFloat(damage);
op_bitsWritten += sizeof(EntityID) * 8 + sizeof(float) * 8;
}
/**
Read object from stream
*/
void Read(Streamer* p_streamer, uint32_t& op_bitsRead) override
{
entityId = p_streamer->ReadUnsignedInt32();
damage = p_streamer->ReadFloat();
op_bitsRead += sizeof(EntityID) * 8 + sizeof(float) * 8;
}
};
}
}
| 33.609756
| 110
| 0.537736
|
meraz
|
ba1c89847ff91713c378c26b74c6f3fed642666f
| 2,891
|
hpp
|
C++
|
Engine/Header/Engine/CEngine.hpp
|
Aredhele/OOM-Engine
|
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
|
[
"MIT"
] | 9
|
2018-07-21T00:30:35.000Z
|
2021-09-04T02:54:11.000Z
|
Engine/Header/Engine/CEngine.hpp
|
Aredhele/OOM-Engine
|
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
|
[
"MIT"
] | null | null | null |
Engine/Header/Engine/CEngine.hpp
|
Aredhele/OOM-Engine
|
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
|
[
"MIT"
] | 1
|
2021-12-03T14:12:41.000Z
|
2021-12-03T14:12:41.000Z
|
/// \file CEngine.hpp
/// \date 21/07/2018
/// \project OOM-Engine
/// \package Engine
/// \author Vincent STEHLY--CALISTO
#ifndef OOM_ENGINE_C_ENGINE_HPP__
#define OOM_ENGINE_C_ENGINE_HPP__
#include <vector>
#include <GLM/glm.hpp>
// Forward declartion
struct GLFWwindow;
namespace Oom
{
// Forward declaration
// Basic components
class CBehavior;
class CTransform;
class CGameObject;
// Engines
class CString;
class CRenderer;
class CAudioEngine;
class CPhysicWorld;
class CEngine
{
public:
bool Initialize ();
void Release ();
void Run ();
public:
// Game objects
static CGameObject* Instantiate ();
static CGameObject* Instantiate (CTransform* parent);
static CGameObject* Instantiate (const glm::vec3& position);
static CGameObject* Instantiate (const glm::vec3& position, const glm::vec3& scale);
static CGameObject* Instantiate (const glm::vec3& position, const glm::vec3& scale, const glm::vec3& orientation);
static void Destroy (CGameObject* p_game_object);
static void Destroy (CGameObject* p_game_object, float delay);
static void DestroyImmediate (CGameObject* p_game_object);
static CGameObject* Find (const CString& name);
static CGameObject* FindWithTag (const CString& tag);
static std::vector<CGameObject*> FindGameObjectsWithTag (const CString& tag);
static
const std::vector<CGameObject*>& GetAllGameObjects();
public:
// Tools
static void ShowMouse ();
static void HideMouse ();
static void SetMousePosition (const glm::vec2& position);
static glm::tvec3<double> GetMousePosition ();
static glm::vec2 GetWindowSize ();
static bool IsKeyPressed (int key_code);
static bool IsKeyReleased (int key_code);
static bool IsMouseButtonPressed (int button);
static bool IsMouseButtonReleased (int button);
static void Exit ();
private:
friend class CBehavior;
friend class CGameObject;
void ReadConfiguration ();
void GameObjectUpdate (GLFWwindow* p_window, float delta_time);
void BehaviorUpdate (GLFWwindow* p_window, float delta_time);
static void RegisterBehavior (CBehavior* p_behavior);
static void UnregisterBehavior (CBehavior* p_behavior);
private:
static CEngine* sp_instance;
private:
bool m_running;
CRenderer* mp_renderer = nullptr;
CPhysicWorld* mp_physic_world = nullptr;
CAudioEngine* mp_audio_engine = nullptr;
std::vector<CBehavior* > m_behaviors;
std::vector<CGameObject*> m_game_objects;
};
}
#endif // !OOM_ENGINE_C_ENGINE_HPP__
| 28.623762
| 142
| 0.642338
|
Aredhele
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.