hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53d5fcb7b78180656bbda184adfb26786391c665 | 1,322 | cpp | C++ | datasets/github_cpp_10/7/150.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/7/150.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/7/150.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null |
#include <iostream>
#include <vector>
using iter = std::vector<int>::iterator;
void sort(iter begin, iter end);
void merge(iter begin, iter mid, iter end);
int main(void) {
std::vector<int> ivec{2, 5, 4, 7, 6, 9, 1, 4, 0};
sort(ivec.begin(), prev(ivec.end()));
std::cout << "Sorted vector: " << std::endl;
for(auto const i : ivec)
std::cout << i << ' ';
std::cout << std::endl;
return 0;
}
void sort(iter begin, iter end) {
if(begin >= end)
return;
iter mid = begin;
std::advance(mid, std::distance(begin, end) / 2);
sort(begin, mid);
sort(std::next(mid), end);
merge(begin, mid, end);
}
void merge(iter begin, iter mid, iter end) {
std::vector<int> ivecOne, ivecTwo;
iter iterOne = begin, iterTwo = std::next(mid);
while(iterOne <= mid)
ivecOne.push_back(*iterOne++);
while(iterTwo <= end)
ivecTwo.push_back(*iterTwo++);
iterOne = ivecOne.begin();
iterTwo = ivecTwo.begin();
while(iterOne != ivecOne.end() && iterTwo != ivecTwo.end()) {
if(*iterOne < *iterTwo)
*begin++ = *iterOne++;
else
*begin++ = *iterTwo++;
}
while(iterOne != ivecOne.end())
*begin++ = *iterOne++;
while(iterTwo != ivecTwo.end())
*begin++ = *iterTwo++;
}
| 20.984127 | 65 | 0.55295 | [
"vector"
] |
53d7f1f5b20f67e868d7608664ce2074d1d2bfad | 659 | cpp | C++ | 1192.cpp | viniciusmalloc/uri | e9554669a50a6d392e3bce49fc21cbfaa353c85f | [
"MIT"
] | 1 | 2022-02-11T21:12:38.000Z | 2022-02-11T21:12:38.000Z | 1192.cpp | viniciusmalloc/uri | e9554669a50a6d392e3bce49fc21cbfaa353c85f | [
"MIT"
] | null | null | null | 1192.cpp | viniciusmalloc/uri | e9554669a50a6d392e3bce49fc21cbfaa353c85f | [
"MIT"
] | 1 | 2019-10-01T03:01:50.000Z | 2019-10-01T03:01:50.000Z | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <vector>
#define mp make_pair
#define pb push_back
using namespace std;
typedef pair<int, int> ii;
const int INF = 0x3f3f3f3f;
int main()
{
char a[3];
int n;
scanf("%d", &n);
getchar();
while (n--) {
scanf(" %[^\n]", a);
int x = a[0] - 48, y = a[2] - 48;
if (a[0] == a[2])
printf("%d\n", x * y);
else if (a[1] <= 'Z')
printf("%d\n", y - x);
else
printf("%d\n", x + y);
}
return 0;
}
| 18.305556 | 42 | 0.46434 | [
"vector"
] |
53e31e3e65a9d100fd0e8755c574762f99f7ba66 | 4,345 | hh | C++ | hackt_docker/hackt/src/Object/expr/const_param_expr_list.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/Object/expr/const_param_expr_list.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/Object/expr/const_param_expr_list.hh | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | /**
\file "Object/expr/const_param_expr_list.hh"
Classes related to constant expressions.
NOTE: this file was spanwed from "Object/art_object_expr_const.h"
for revision history tracking purposes.
$Id: const_param_expr_list.hh,v 1.20 2009/09/14 21:16:54 fang Exp $
*/
#ifndef __HAC_OBJECT_EXPR_CONST_PARAM_EXPR_LIST_H__
#define __HAC_OBJECT_EXPR_CONST_PARAM_EXPR_LIST_H__
#include <vector>
#include "Object/expr/param_expr_list.hh"
#include "util/boolean_types.hh"
//=============================================================================
namespace HAC {
namespace entity {
class const_param;
class dynamic_param_expr_list;
using std::vector;
using util::good_bool;
using util::persistent_object_manager;
//=============================================================================
/**
List of strictly constant param expressions.
Only scalar expressions allowed, no array indirections or collections.
TODO: liberate from param_expr_list base class eventually.
*/
class const_param_expr_list : public param_expr_list,
protected vector<count_ptr<const const_param> > {
friend class dynamic_param_expr_list;
typedef const_param_expr_list this_type;
typedef param_expr_list interface_type;
protected:
typedef vector<count_ptr<const const_param> > parent_type;
public:
typedef parent_type::value_type value_type;
typedef parent_type::reference reference;
typedef parent_type::const_reference const_reference;
typedef parent_type::iterator iterator;
typedef parent_type::const_iterator const_iterator;
typedef parent_type::reverse_iterator reverse_iterator;
typedef parent_type::const_reverse_iterator const_reverse_iterator;
public:
const_param_expr_list();
explicit
const_param_expr_list(const parent_type::value_type&);
// lazy: use default copy constructor
// const_param_expr_list(const const_param_expr_list& pl);
/**
uses std::copy to initialize a sequence.
*/
template <class InIter>
const_param_expr_list(InIter b, InIter e) :
interface_type(), parent_type(b, e) {
}
~const_param_expr_list();
size_t
size(void) const;
ostream&
what(ostream& o) const;
ostream&
dump(ostream& o) const;
ostream&
dump(ostream& o, const expr_dump_context&) const;
ostream&
dump_raw(ostream&) const;
ostream&
dump_raw_from(ostream&, const size_t) const;
ostream&
dump_formatted(ostream&, const char*, const char*, const char*) const;
ostream&
dump_range(ostream&, const expr_dump_context&,
const size_t, const size_t) const;
using parent_type::front;
using parent_type::back;
count_ptr<const param_expr>
at(const size_t) const;
#if 0
using parent_type::operator[];
#else
const_reference
operator [] (const size_t) const;
#endif
using parent_type::begin;
using parent_type::end;
using parent_type::empty;
using parent_type::push_back;
bool
is_all_true(void) const;
static
bool
is_all_true(const parent_type&);
bool
may_be_equivalent(const param_expr_list& p) const;
bool
must_be_equivalent(const param_expr_list& p) const;
/// checks equivalence up to the end of the strict argument list
bool
must_be_equivalent(const this_type&, const size_t s) const;
/// only checks the relaxed parameters of this list against the argument
bool
is_tail_equivalent(const this_type&) const;
/// checks entire list
bool
must_be_equivalent(const this_type&) const;
bool
is_static_constant(void) const { return true; }
bool
is_relaxed_formal_dependent(void) const { return false; }
void
accept(nonmeta_expr_visitor&) const;
count_ptr<dynamic_param_expr_list>
to_dynamic_list(void) const;
// need unroll context in case formals list depends on these actuals!
good_bool
must_validate_template_arguments(
const template_formals_list_type&,
const unroll_context&) const;
bool
operator < (const this_type&) const;
/**
Dereference and compare (less-than) functor.
*/
struct less_ptr {
bool
operator () (const value_type&, const value_type&) const;
}; // end struct less
public:
void
collect_transient_info_base(persistent_object_manager&) const;
PERSISTENT_METHODS_DECLARATIONS
}; // end class const_param_expr_list
//=============================================================================
} // end namespace HAC
} // end namespace entity
#endif // __HAC_OBJECT_EXPR_CONST_PARAM_EXPR_LIST_H__
| 24.828571 | 79 | 0.734177 | [
"object",
"vector"
] |
53e83c46cb0c3ecb07b5a57573a03e470a26fcea | 54,222 | cc | C++ | lib/wabt/src/binary-reader-interpreter.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | lib/wabt/src/binary-reader-interpreter.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | lib/wabt/src/binary-reader-interpreter.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | /*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "binary-reader-interpreter.h"
#include <cassert>
#include <cinttypes>
#include <cstdarg>
#include <cstdio>
#include <vector>
#include "binary-error-handler.h"
#include "binary-reader-nop.h"
#include "interpreter.h"
#include "type-checker.h"
#include "writer.h"
#define CHECK_RESULT(expr) \
do { \
if (WABT_FAILED(expr)) \
return wabt::Result::Error; \
} while (0)
namespace wabt {
using namespace interpreter;
namespace {
typedef std::vector<Index> IndexVector;
typedef std::vector<IstreamOffset> IstreamOffsetVector;
typedef std::vector<IstreamOffsetVector> IstreamOffsetVectorVector;
struct Label {
Label(IstreamOffset offset, IstreamOffset fixup_offset);
IstreamOffset offset;
IstreamOffset fixup_offset;
};
Label::Label(IstreamOffset offset, IstreamOffset fixup_offset)
: offset(offset), fixup_offset(fixup_offset) {}
struct ElemSegmentInfo {
ElemSegmentInfo(Index* dst, Index func_index)
: dst(dst), func_index(func_index) {}
Index* dst;
Index func_index;
};
struct DataSegmentInfo {
DataSegmentInfo(void* dst_data, const void* src_data, IstreamOffset size)
: dst_data(dst_data), src_data(src_data), size(size) {}
void* dst_data; // Not owned.
const void* src_data; // Not owned.
IstreamOffset size;
};
class BinaryReaderInterpreter : public BinaryReaderNop {
public:
BinaryReaderInterpreter(Environment* env,
DefinedModule* module,
std::unique_ptr<OutputBuffer> istream,
BinaryErrorHandler* error_handler);
wabt::Result ReadBinary(DefinedModule* out_module);
std::unique_ptr<OutputBuffer> ReleaseOutputBuffer();
// Implement BinaryReader.
bool OnError(const char* message) override;
wabt::Result EndModule() override;
wabt::Result OnTypeCount(Index count) override;
wabt::Result OnType(Index index,
Index param_count,
Type* param_types,
Index result_count,
Type* result_types) override;
wabt::Result OnImportCount(Index count) override;
wabt::Result OnImport(Index index,
StringSlice module_name,
StringSlice field_name) override;
wabt::Result OnImportFunc(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index func_index,
Index sig_index) override;
wabt::Result OnImportTable(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index table_index,
Type elem_type,
const Limits* elem_limits) override;
wabt::Result OnImportMemory(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index memory_index,
const Limits* page_limits) override;
wabt::Result OnImportGlobal(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index global_index,
Type type,
bool mutable_) override;
wabt::Result OnFunctionCount(Index count) override;
wabt::Result OnFunction(Index index, Index sig_index) override;
wabt::Result OnTable(Index index,
Type elem_type,
const Limits* elem_limits) override;
wabt::Result OnMemory(Index index, const Limits* limits) override;
wabt::Result OnGlobalCount(Index count) override;
wabt::Result BeginGlobal(Index index, Type type, bool mutable_) override;
wabt::Result EndGlobalInitExpr(Index index) override;
wabt::Result OnExport(Index index,
ExternalKind kind,
Index item_index,
StringSlice name) override;
wabt::Result OnStartFunction(Index func_index) override;
wabt::Result BeginFunctionBody(Index index) override;
wabt::Result OnLocalDeclCount(Index count) override;
wabt::Result OnLocalDecl(Index decl_index, Index count, Type type) override;
wabt::Result OnBinaryExpr(wabt::Opcode opcode) override;
wabt::Result OnBlockExpr(Index num_types, Type* sig_types) override;
wabt::Result OnBrExpr(Index depth) override;
wabt::Result OnBrIfExpr(Index depth) override;
wabt::Result OnBrTableExpr(Index num_targets,
Index* target_depths,
Index default_target_depth) override;
wabt::Result OnCallExpr(Index func_index) override;
wabt::Result OnCallIndirectExpr(Index sig_index) override;
wabt::Result OnCompareExpr(wabt::Opcode opcode) override;
wabt::Result OnConvertExpr(wabt::Opcode opcode) override;
wabt::Result OnCurrentMemoryExpr() override;
wabt::Result OnDropExpr() override;
wabt::Result OnElseExpr() override;
wabt::Result OnEndExpr() override;
wabt::Result OnF32ConstExpr(uint32_t value_bits) override;
wabt::Result OnF64ConstExpr(uint64_t value_bits) override;
wabt::Result OnGetGlobalExpr(Index global_index) override;
wabt::Result OnGetLocalExpr(Index local_index) override;
wabt::Result OnGrowMemoryExpr() override;
wabt::Result OnI32ConstExpr(uint32_t value) override;
wabt::Result OnI64ConstExpr(uint64_t value) override;
wabt::Result OnIfExpr(Index num_types, Type* sig_types) override;
wabt::Result OnLoadExpr(wabt::Opcode opcode,
uint32_t alignment_log2,
Address offset) override;
wabt::Result OnLoopExpr(Index num_types, Type* sig_types) override;
wabt::Result OnNopExpr() override;
wabt::Result OnReturnExpr() override;
wabt::Result OnSelectExpr() override;
wabt::Result OnSetGlobalExpr(Index global_index) override;
wabt::Result OnSetLocalExpr(Index local_index) override;
wabt::Result OnStoreExpr(wabt::Opcode opcode,
uint32_t alignment_log2,
Address offset) override;
wabt::Result OnTeeLocalExpr(Index local_index) override;
wabt::Result OnUnaryExpr(wabt::Opcode opcode) override;
wabt::Result OnUnreachableExpr() override;
wabt::Result EndFunctionBody(Index index) override;
wabt::Result EndElemSegmentInitExpr(Index index) override;
wabt::Result OnElemSegmentFunctionIndex(Index index,
Index func_index) override;
wabt::Result OnDataSegmentData(Index index,
const void* data,
Address size) override;
wabt::Result OnInitExprF32ConstExpr(Index index, uint32_t value) override;
wabt::Result OnInitExprF64ConstExpr(Index index, uint64_t value) override;
wabt::Result OnInitExprGetGlobalExpr(Index index,
Index global_index) override;
wabt::Result OnInitExprI32ConstExpr(Index index, uint32_t value) override;
wabt::Result OnInitExprI64ConstExpr(Index index, uint64_t value) override;
private:
Label* GetLabel(Index depth);
Label* TopLabel();
void PushLabel(IstreamOffset offset, IstreamOffset fixup_offset);
void PopLabel();
bool HandleError(Offset offset, const char* message);
void PrintError(const char* format, ...);
Index TranslateSigIndexToEnv(Index sig_index);
FuncSignature* GetSignatureByModuleIndex(Index sig_index);
Index TranslateFuncIndexToEnv(Index func_index);
Index TranslateModuleFuncIndexToDefined(Index func_index);
Func* GetFuncByModuleIndex(Index func_index);
Index TranslateGlobalIndexToEnv(Index global_index);
Global* GetGlobalByModuleIndex(Index global_index);
Type GetGlobalTypeByModuleIndex(Index global_index);
Index TranslateLocalIndex(Index local_index);
Type GetLocalTypeByIndex(Func* func, Index local_index);
IstreamOffset GetIstreamOffset();
wabt::Result EmitDataAt(IstreamOffset offset,
const void* data,
IstreamOffset size);
wabt::Result EmitData(const void* data, IstreamOffset size);
wabt::Result EmitOpcode(wabt::Opcode opcode);
wabt::Result EmitOpcode(interpreter::Opcode opcode);
wabt::Result EmitI8(uint8_t value);
wabt::Result EmitI32(uint32_t value);
wabt::Result EmitI64(uint64_t value);
wabt::Result EmitI32At(IstreamOffset offset, uint32_t value);
wabt::Result EmitDropKeep(uint32_t drop, uint8_t keep);
wabt::Result AppendFixup(IstreamOffsetVectorVector* fixups_vector,
Index index);
wabt::Result EmitBrOffset(Index depth, IstreamOffset offset);
wabt::Result GetBrDropKeepCount(Index depth,
Index* out_drop_count,
Index* out_keep_count);
wabt::Result GetReturnDropKeepCount(Index* out_drop_count,
Index* out_keep_count);
wabt::Result EmitBr(Index depth, Index drop_count, Index keep_count);
wabt::Result EmitBrTableOffset(Index depth);
wabt::Result FixupTopLabel();
wabt::Result EmitFuncOffset(DefinedFunc* func, Index func_index);
wabt::Result CheckLocal(Index local_index);
wabt::Result CheckGlobal(Index global_index);
wabt::Result CheckImportKind(Import* import, ExternalKind expected_kind);
wabt::Result CheckImportLimits(const Limits* declared_limits,
const Limits* actual_limits);
wabt::Result CheckHasMemory(wabt::Opcode opcode);
wabt::Result CheckAlign(uint32_t alignment_log2, Address natural_alignment);
wabt::Result AppendExport(Module* module,
ExternalKind kind,
Index item_index,
StringSlice name);
HostImportDelegate::ErrorCallback MakePrintErrorCallback();
BinaryErrorHandler* error_handler = nullptr;
Environment* env = nullptr;
DefinedModule* module = nullptr;
DefinedFunc* current_func = nullptr;
TypeChecker typechecker;
std::vector<Label> label_stack;
IstreamOffsetVectorVector func_fixups;
IstreamOffsetVectorVector depth_fixups;
MemoryWriter istream_writer;
IstreamOffset istream_offset = 0;
/* mappings from module index space to env index space; this won't just be a
* translation, because imported values will be resolved as well */
IndexVector sig_index_mapping;
IndexVector func_index_mapping;
IndexVector global_index_mapping;
Index num_func_imports = 0;
Index num_global_imports = 0;
// Changes to linear memory and tables should not apply if a validation error
// occurs; these vectors cache the changes that must be applied after we know
// that there are no validation errors.
std::vector<ElemSegmentInfo> elem_segment_infos;
std::vector<DataSegmentInfo> data_segment_infos;
/* values cached so they can be shared between callbacks */
TypedValue init_expr_value;
IstreamOffset table_offset = 0;
bool is_host_import = false;
HostModule* host_import_module = nullptr;
Index import_env_index = 0;
};
BinaryReaderInterpreter::BinaryReaderInterpreter(
Environment* env,
DefinedModule* module,
std::unique_ptr<OutputBuffer> istream,
BinaryErrorHandler* error_handler)
: error_handler(error_handler),
env(env),
module(module),
istream_writer(std::move(istream)),
istream_offset(istream_writer.output_buffer().size()) {
typechecker.set_error_callback(
[this](const char* msg) { PrintError("%s", msg); });
}
std::unique_ptr<OutputBuffer> BinaryReaderInterpreter::ReleaseOutputBuffer() {
return istream_writer.ReleaseOutputBuffer();
}
Label* BinaryReaderInterpreter::GetLabel(Index depth) {
assert(depth < label_stack.size());
return &label_stack[label_stack.size() - depth - 1];
}
Label* BinaryReaderInterpreter::TopLabel() {
return GetLabel(0);
}
bool BinaryReaderInterpreter::HandleError(Offset offset, const char* message) {
return error_handler->OnError(offset, message);
}
void WABT_PRINTF_FORMAT(2, 3)
BinaryReaderInterpreter::PrintError(const char* format, ...) {
WABT_SNPRINTF_ALLOCA(buffer, length, format);
HandleError(kInvalidOffset, buffer);
}
Index BinaryReaderInterpreter::TranslateSigIndexToEnv(Index sig_index) {
assert(sig_index < sig_index_mapping.size());
return sig_index_mapping[sig_index];
}
FuncSignature* BinaryReaderInterpreter::GetSignatureByModuleIndex(
Index sig_index) {
return env->GetFuncSignature(TranslateSigIndexToEnv(sig_index));
}
Index BinaryReaderInterpreter::TranslateFuncIndexToEnv(Index func_index) {
assert(func_index < func_index_mapping.size());
return func_index_mapping[func_index];
}
Index BinaryReaderInterpreter::TranslateModuleFuncIndexToDefined(
Index func_index) {
assert(func_index >= num_func_imports);
return func_index - num_func_imports;
}
Func* BinaryReaderInterpreter::GetFuncByModuleIndex(Index func_index) {
return env->GetFunc(TranslateFuncIndexToEnv(func_index));
}
Index BinaryReaderInterpreter::TranslateGlobalIndexToEnv(Index global_index) {
return global_index_mapping[global_index];
}
Global* BinaryReaderInterpreter::GetGlobalByModuleIndex(Index global_index) {
return env->GetGlobal(TranslateGlobalIndexToEnv(global_index));
}
Type BinaryReaderInterpreter::GetGlobalTypeByModuleIndex(Index global_index) {
return GetGlobalByModuleIndex(global_index)->typed_value.type;
}
Type BinaryReaderInterpreter::GetLocalTypeByIndex(Func* func,
Index local_index) {
assert(!func->is_host);
return func->as_defined()->param_and_local_types[local_index];
}
IstreamOffset BinaryReaderInterpreter::GetIstreamOffset() {
return istream_offset;
}
wabt::Result BinaryReaderInterpreter::EmitDataAt(IstreamOffset offset,
const void* data,
IstreamOffset size) {
return istream_writer.WriteData(offset, data, size);
}
wabt::Result BinaryReaderInterpreter::EmitData(const void* data,
IstreamOffset size) {
CHECK_RESULT(EmitDataAt(istream_offset, data, size));
istream_offset += size;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EmitOpcode(wabt::Opcode opcode) {
return EmitData(&opcode, sizeof(uint8_t));
}
wabt::Result BinaryReaderInterpreter::EmitOpcode(interpreter::Opcode opcode) {
return EmitData(&opcode, sizeof(uint8_t));
}
wabt::Result BinaryReaderInterpreter::EmitI8(uint8_t value) {
return EmitData(&value, sizeof(value));
}
wabt::Result BinaryReaderInterpreter::EmitI32(uint32_t value) {
return EmitData(&value, sizeof(value));
}
wabt::Result BinaryReaderInterpreter::EmitI64(uint64_t value) {
return EmitData(&value, sizeof(value));
}
wabt::Result BinaryReaderInterpreter::EmitI32At(IstreamOffset offset,
uint32_t value) {
return EmitDataAt(offset, &value, sizeof(value));
}
wabt::Result BinaryReaderInterpreter::EmitDropKeep(uint32_t drop,
uint8_t keep) {
assert(drop != UINT32_MAX);
assert(keep <= 1);
if (drop > 0) {
if (drop == 1 && keep == 0) {
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Drop));
} else {
CHECK_RESULT(EmitOpcode(interpreter::Opcode::DropKeep));
CHECK_RESULT(EmitI32(drop));
CHECK_RESULT(EmitI8(keep));
}
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::AppendFixup(
IstreamOffsetVectorVector* fixups_vector,
Index index) {
if (index >= fixups_vector->size())
fixups_vector->resize(index + 1);
(*fixups_vector)[index].push_back(GetIstreamOffset());
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EmitBrOffset(Index depth,
IstreamOffset offset) {
if (offset == kInvalidIstreamOffset) {
/* depth_fixups stores the depth counting up from zero, where zero is the
* top-level function scope. */
depth = label_stack.size() - 1 - depth;
CHECK_RESULT(AppendFixup(&depth_fixups, depth));
}
CHECK_RESULT(EmitI32(offset));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::GetBrDropKeepCount(
Index depth,
Index* out_drop_count,
Index* out_keep_count) {
TypeChecker::Label* label;
CHECK_RESULT(typechecker.GetLabel(depth, &label));
*out_keep_count =
label->label_type != LabelType::Loop ? label->sig.size() : 0;
if (typechecker.IsUnreachable()) {
*out_drop_count = 0;
} else {
*out_drop_count =
(typechecker.type_stack_size() - label->type_stack_limit) -
*out_keep_count;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::GetReturnDropKeepCount(
Index* out_drop_count,
Index* out_keep_count) {
if (WABT_FAILED(GetBrDropKeepCount(label_stack.size() - 1, out_drop_count,
out_keep_count))) {
return wabt::Result::Error;
}
*out_drop_count += current_func->param_and_local_types.size();
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EmitBr(Index depth,
Index drop_count,
Index keep_count) {
CHECK_RESULT(EmitDropKeep(drop_count, keep_count));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Br));
CHECK_RESULT(EmitBrOffset(depth, GetLabel(depth)->offset));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EmitBrTableOffset(Index depth) {
Index drop_count, keep_count;
CHECK_RESULT(GetBrDropKeepCount(depth, &drop_count, &keep_count));
CHECK_RESULT(EmitBrOffset(depth, GetLabel(depth)->offset));
CHECK_RESULT(EmitI32(drop_count));
CHECK_RESULT(EmitI8(keep_count));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::FixupTopLabel() {
IstreamOffset offset = GetIstreamOffset();
Index top = label_stack.size() - 1;
if (top >= depth_fixups.size()) {
/* nothing to fixup */
return wabt::Result::Ok;
}
IstreamOffsetVector& fixups = depth_fixups[top];
for (IstreamOffset fixup : fixups)
CHECK_RESULT(EmitI32At(fixup, offset));
fixups.clear();
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EmitFuncOffset(DefinedFunc* func,
Index func_index) {
if (func->offset == kInvalidIstreamOffset) {
Index defined_index = TranslateModuleFuncIndexToDefined(func_index);
CHECK_RESULT(AppendFixup(&func_fixups, defined_index));
}
CHECK_RESULT(EmitI32(func->offset));
return wabt::Result::Ok;
}
bool BinaryReaderInterpreter::OnError(const char* message) {
return HandleError(state->offset, message);
}
wabt::Result BinaryReaderInterpreter::OnTypeCount(Index count) {
Index sig_count = env->GetFuncSignatureCount();
sig_index_mapping.resize(count);
for (Index i = 0; i < count; ++i)
sig_index_mapping[i] = sig_count + i;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnType(Index index,
Index param_count,
Type* param_types,
Index result_count,
Type* result_types) {
assert(TranslateSigIndexToEnv(index) == env->GetFuncSignatureCount());
env->EmplaceBackFuncSignature(param_count, param_types, result_count,
result_types);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnImportCount(Index count) {
module->imports.resize(count);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnImport(Index index,
StringSlice module_name,
StringSlice field_name) {
Import* import = &module->imports[index];
import->module_name = dup_string_slice(module_name);
import->field_name = dup_string_slice(field_name);
Module* module = env->FindRegisteredModule(import->module_name);
if (!module) {
PrintError("unknown import module \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(import->module_name));
return wabt::Result::Error;
}
if (module->is_host) {
/* We don't yet know the kind of a host import module, so just assume it
* exists for now. We'll fail later (in on_import_* below) if it doesn't
* exist). */
is_host_import = true;
host_import_module = module->as_host();
} else {
Export* export_ = module->GetExport(import->field_name);
if (!export_) {
PrintError("unknown module field \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(import->field_name));
return wabt::Result::Error;
}
import->kind = export_->kind;
is_host_import = false;
import_env_index = export_->index;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckLocal(Index local_index) {
Index max_local_index = current_func->param_and_local_types.size();
if (local_index >= max_local_index) {
PrintError("invalid local_index: %" PRIindex " (max %" PRIindex ")",
local_index, max_local_index);
return wabt::Result::Error;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckGlobal(Index global_index) {
Index max_global_index = global_index_mapping.size();
if (global_index >= max_global_index) {
PrintError("invalid global_index: %" PRIindex " (max %" PRIindex ")",
global_index, max_global_index);
return wabt::Result::Error;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckImportKind(
Import* import,
ExternalKind expected_kind) {
if (import->kind != expected_kind) {
PrintError("expected import \"" PRIstringslice "." PRIstringslice
"\" to have kind %s, not %s",
WABT_PRINTF_STRING_SLICE_ARG(import->module_name),
WABT_PRINTF_STRING_SLICE_ARG(import->field_name),
get_kind_name(expected_kind), get_kind_name(import->kind));
return wabt::Result::Error;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckImportLimits(
const Limits* declared_limits,
const Limits* actual_limits) {
if (actual_limits->initial < declared_limits->initial) {
PrintError("actual size (%" PRIu64 ") smaller than declared (%" PRIu64 ")",
actual_limits->initial, declared_limits->initial);
return wabt::Result::Error;
}
if (declared_limits->has_max) {
if (!actual_limits->has_max) {
PrintError("max size (unspecified) larger than declared (%" PRIu64 ")",
declared_limits->max);
return wabt::Result::Error;
} else if (actual_limits->max > declared_limits->max) {
PrintError("max size (%" PRIu64 ") larger than declared (%" PRIu64 ")",
actual_limits->max, declared_limits->max);
return wabt::Result::Error;
}
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::AppendExport(Module* module,
ExternalKind kind,
Index item_index,
StringSlice name) {
if (module->export_bindings.FindIndex(name) != kInvalidIndex) {
PrintError("duplicate export \"" PRIstringslice "\"",
WABT_PRINTF_STRING_SLICE_ARG(name));
return wabt::Result::Error;
}
module->exports.emplace_back(dup_string_slice(name), kind, item_index);
Export* export_ = &module->exports.back();
module->export_bindings.emplace(string_slice_to_string(export_->name),
Binding(module->exports.size() - 1));
return wabt::Result::Ok;
}
HostImportDelegate::ErrorCallback
BinaryReaderInterpreter::MakePrintErrorCallback() {
return [this](const char* msg) { PrintError("%s", msg); };
}
wabt::Result BinaryReaderInterpreter::OnImportFunc(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index func_index,
Index sig_index) {
Import* import = &module->imports[import_index];
import->func.sig_index = TranslateSigIndexToEnv(sig_index);
Index func_env_index;
if (is_host_import) {
HostFunc* func = new HostFunc(import->module_name, import->field_name,
import->func.sig_index);
env->EmplaceBackFunc(func);
FuncSignature* sig = env->GetFuncSignature(func->sig_index);
CHECK_RESULT(host_import_module->import_delegate->ImportFunc(
import, func, sig, MakePrintErrorCallback()));
assert(func->callback);
func_env_index = env->GetFuncCount() - 1;
AppendExport(host_import_module, ExternalKind::Func, func_env_index,
import->field_name);
} else {
CHECK_RESULT(CheckImportKind(import, ExternalKind::Func));
Func* func = env->GetFunc(import_env_index);
if (!env->FuncSignaturesAreEqual(import->func.sig_index, func->sig_index)) {
PrintError("import signature mismatch");
return wabt::Result::Error;
}
func_env_index = import_env_index;
}
func_index_mapping.push_back(func_env_index);
num_func_imports++;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnImportTable(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index table_index,
Type elem_type,
const Limits* elem_limits) {
if (module->table_index != kInvalidIndex) {
PrintError("only one table allowed");
return wabt::Result::Error;
}
Import* import = &module->imports[import_index];
if (is_host_import) {
Table* table = env->EmplaceBackTable(*elem_limits);
CHECK_RESULT(host_import_module->import_delegate->ImportTable(
import, table, MakePrintErrorCallback()));
CHECK_RESULT(CheckImportLimits(elem_limits, &table->limits));
module->table_index = env->GetTableCount() - 1;
AppendExport(host_import_module, ExternalKind::Table, module->table_index,
import->field_name);
} else {
CHECK_RESULT(CheckImportKind(import, ExternalKind::Table));
Table* table = env->GetTable(import_env_index);
CHECK_RESULT(CheckImportLimits(elem_limits, &table->limits));
import->table.limits = *elem_limits;
module->table_index = import_env_index;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnImportMemory(
Index import_index,
StringSlice module_name,
StringSlice field_name,
Index memory_index,
const Limits* page_limits) {
if (module->memory_index != kInvalidIndex) {
PrintError("only one memory allowed");
return wabt::Result::Error;
}
Import* import = &module->imports[import_index];
if (is_host_import) {
Memory* memory = env->EmplaceBackMemory();
CHECK_RESULT(host_import_module->import_delegate->ImportMemory(
import, memory, MakePrintErrorCallback()));
CHECK_RESULT(CheckImportLimits(page_limits, &memory->page_limits));
module->memory_index = env->GetMemoryCount() - 1;
AppendExport(host_import_module, ExternalKind::Memory, module->memory_index,
import->field_name);
} else {
CHECK_RESULT(CheckImportKind(import, ExternalKind::Memory));
Memory* memory = env->GetMemory(import_env_index);
CHECK_RESULT(CheckImportLimits(page_limits, &memory->page_limits));
import->memory.limits = *page_limits;
module->memory_index = import_env_index;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnImportGlobal(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index global_index,
Type type,
bool mutable_) {
Import* import = &module->imports[import_index];
Index global_env_index = env->GetGlobalCount() - 1;
if (is_host_import) {
Global* global = env->EmplaceBackGlobal(TypedValue(type), mutable_);
CHECK_RESULT(host_import_module->import_delegate->ImportGlobal(
import, global, MakePrintErrorCallback()));
global_env_index = env->GetGlobalCount() - 1;
AppendExport(host_import_module, ExternalKind::Global, global_env_index,
import->field_name);
} else {
CHECK_RESULT(CheckImportKind(import, ExternalKind::Global));
// TODO: check type and mutability
import->global.type = type;
import->global.mutable_ = mutable_;
global_env_index = import_env_index;
}
global_index_mapping.push_back(global_env_index);
num_global_imports++;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnFunctionCount(Index count) {
for (Index i = 0; i < count; ++i)
func_index_mapping.push_back(env->GetFuncCount() + i);
func_fixups.resize(count);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnFunction(Index index, Index sig_index) {
env->EmplaceBackFunc(new DefinedFunc(TranslateSigIndexToEnv(sig_index)));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnTable(Index index,
Type elem_type,
const Limits* elem_limits) {
if (module->table_index != kInvalidIndex) {
PrintError("only one table allowed");
return wabt::Result::Error;
}
env->EmplaceBackTable(*elem_limits);
module->table_index = env->GetTableCount() - 1;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnMemory(Index index,
const Limits* page_limits) {
if (module->memory_index != kInvalidIndex) {
PrintError("only one memory allowed");
return wabt::Result::Error;
}
env->EmplaceBackMemory(*page_limits);
module->memory_index = env->GetMemoryCount() - 1;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnGlobalCount(Index count) {
for (Index i = 0; i < count; ++i)
global_index_mapping.push_back(env->GetGlobalCount() + i);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::BeginGlobal(Index index,
Type type,
bool mutable_) {
assert(TranslateGlobalIndexToEnv(index) == env->GetGlobalCount());
env->EmplaceBackGlobal(TypedValue(type), mutable_);
init_expr_value.type = Type::Void;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EndGlobalInitExpr(Index index) {
Global* global = GetGlobalByModuleIndex(index);
if (init_expr_value.type != global->typed_value.type) {
PrintError("type mismatch in global, expected %s but got %s.",
get_type_name(global->typed_value.type),
get_type_name(init_expr_value.type));
return wabt::Result::Error;
}
global->typed_value = init_expr_value;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnInitExprF32ConstExpr(
Index index,
uint32_t value_bits) {
init_expr_value.type = Type::F32;
init_expr_value.value.f32_bits = value_bits;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnInitExprF64ConstExpr(
Index index,
uint64_t value_bits) {
init_expr_value.type = Type::F64;
init_expr_value.value.f64_bits = value_bits;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnInitExprGetGlobalExpr(
Index index,
Index global_index) {
if (global_index >= num_global_imports) {
PrintError("initializer expression can only reference an imported global");
return wabt::Result::Error;
}
Global* ref_global = GetGlobalByModuleIndex(global_index);
if (ref_global->mutable_) {
PrintError("initializer expression cannot reference a mutable global");
return wabt::Result::Error;
}
init_expr_value = ref_global->typed_value;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnInitExprI32ConstExpr(Index index,
uint32_t value) {
init_expr_value.type = Type::I32;
init_expr_value.value.i32 = value;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnInitExprI64ConstExpr(Index index,
uint64_t value) {
init_expr_value.type = Type::I64;
init_expr_value.value.i64 = value;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnExport(Index index,
ExternalKind kind,
Index item_index,
StringSlice name) {
switch (kind) {
case ExternalKind::Func:
item_index = TranslateFuncIndexToEnv(item_index);
break;
case ExternalKind::Table:
item_index = module->table_index;
break;
case ExternalKind::Memory:
item_index = module->memory_index;
break;
case ExternalKind::Global: {
item_index = TranslateGlobalIndexToEnv(item_index);
Global* global = env->GetGlobal(item_index);
if (global->mutable_) {
PrintError("mutable globals cannot be exported");
return wabt::Result::Error;
}
break;
}
case ExternalKind::Except:
// TODO(karlschimpf) Define
WABT_FATAL("BinaryReaderInterpreter::OnExport(except) not implemented");
break;
}
return AppendExport(module, kind, item_index, name);
}
wabt::Result BinaryReaderInterpreter::OnStartFunction(Index func_index) {
Index start_func_index = TranslateFuncIndexToEnv(func_index);
Func* start_func = env->GetFunc(start_func_index);
FuncSignature* sig = env->GetFuncSignature(start_func->sig_index);
if (sig->param_types.size() != 0) {
PrintError("start function must be nullary");
return wabt::Result::Error;
}
if (sig->result_types.size() != 0) {
PrintError("start function must not return anything");
return wabt::Result::Error;
}
module->start_func_index = start_func_index;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EndElemSegmentInitExpr(Index index) {
if (init_expr_value.type != Type::I32) {
PrintError("type mismatch in elem segment, expected i32 but got %s",
get_type_name(init_expr_value.type));
return wabt::Result::Error;
}
table_offset = init_expr_value.value.i32;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnElemSegmentFunctionIndex(
Index index,
Index func_index) {
assert(module->table_index != kInvalidIndex);
Table* table = env->GetTable(module->table_index);
if (table_offset >= table->func_indexes.size()) {
PrintError("elem segment offset is out of bounds: %u >= max value %" PRIzd,
table_offset, table->func_indexes.size());
return wabt::Result::Error;
}
Index max_func_index = func_index_mapping.size();
if (func_index >= max_func_index) {
PrintError("invalid func_index: %" PRIindex " (max %" PRIindex ")",
func_index, max_func_index);
return wabt::Result::Error;
}
elem_segment_infos.emplace_back(&table->func_indexes[table_offset++],
TranslateFuncIndexToEnv(func_index));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnDataSegmentData(Index index,
const void* src_data,
Address size) {
assert(module->memory_index != kInvalidIndex);
Memory* memory = env->GetMemory(module->memory_index);
if (init_expr_value.type != Type::I32) {
PrintError("type mismatch in data segment, expected i32 but got %s",
get_type_name(init_expr_value.type));
return wabt::Result::Error;
}
Address address = init_expr_value.value.i32;
uint64_t end_address =
static_cast<uint64_t>(address) + static_cast<uint64_t>(size);
if (end_address > memory->data.size()) {
PrintError("data segment is out of bounds: [%" PRIaddress ", %" PRIu64
") >= max value %" PRIzd,
address, end_address, memory->data.size());
return wabt::Result::Error;
}
if (size > 0)
data_segment_infos.emplace_back(&memory->data[address], src_data, size);
return wabt::Result::Ok;
}
void BinaryReaderInterpreter::PushLabel(IstreamOffset offset,
IstreamOffset fixup_offset) {
label_stack.emplace_back(offset, fixup_offset);
}
void BinaryReaderInterpreter::PopLabel() {
label_stack.pop_back();
/* reduce the depth_fixups stack as well, but it may be smaller than
* label_stack so only do it conditionally. */
if (depth_fixups.size() > label_stack.size()) {
depth_fixups.erase(depth_fixups.begin() + label_stack.size(),
depth_fixups.end());
}
}
wabt::Result BinaryReaderInterpreter::BeginFunctionBody(Index index) {
DefinedFunc* func = GetFuncByModuleIndex(index)->as_defined();
FuncSignature* sig = env->GetFuncSignature(func->sig_index);
func->offset = GetIstreamOffset();
func->local_decl_count = 0;
func->local_count = 0;
current_func = func;
depth_fixups.clear();
label_stack.clear();
/* fixup function references */
Index defined_index = TranslateModuleFuncIndexToDefined(index);
IstreamOffsetVector& fixups = func_fixups[defined_index];
for (IstreamOffset fixup : fixups)
CHECK_RESULT(EmitI32At(fixup, func->offset));
/* append param types */
for (Type param_type : sig->param_types)
func->param_and_local_types.push_back(param_type);
CHECK_RESULT(typechecker.BeginFunction(&sig->result_types));
/* push implicit func label (equivalent to return) */
PushLabel(kInvalidIstreamOffset, kInvalidIstreamOffset);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EndFunctionBody(Index index) {
FixupTopLabel();
Index drop_count, keep_count;
CHECK_RESULT(GetReturnDropKeepCount(&drop_count, &keep_count));
CHECK_RESULT(typechecker.EndFunction());
CHECK_RESULT(EmitDropKeep(drop_count, keep_count));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Return));
PopLabel();
current_func = nullptr;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnLocalDeclCount(Index count) {
current_func->local_decl_count = count;
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnLocalDecl(Index decl_index,
Index count,
Type type) {
current_func->local_count += count;
for (Index i = 0; i < count; ++i)
current_func->param_and_local_types.push_back(type);
if (decl_index == current_func->local_decl_count - 1) {
/* last local declaration, allocate space for all locals. */
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Alloca));
CHECK_RESULT(EmitI32(current_func->local_count));
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckHasMemory(wabt::Opcode opcode) {
if (module->memory_index == kInvalidIndex) {
PrintError("%s requires an imported or defined memory.",
get_opcode_name(opcode));
return wabt::Result::Error;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::CheckAlign(uint32_t alignment_log2,
Address natural_alignment) {
if (alignment_log2 >= 32 || (1U << alignment_log2) > natural_alignment) {
PrintError("alignment must not be larger than natural alignment (%u)",
natural_alignment);
return wabt::Result::Error;
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnUnaryExpr(wabt::Opcode opcode) {
CHECK_RESULT(typechecker.OnUnary(opcode));
CHECK_RESULT(EmitOpcode(opcode));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnBinaryExpr(wabt::Opcode opcode) {
CHECK_RESULT(typechecker.OnBinary(opcode));
CHECK_RESULT(EmitOpcode(opcode));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnBlockExpr(Index num_types,
Type* sig_types) {
TypeVector sig(sig_types, sig_types + num_types);
CHECK_RESULT(typechecker.OnBlock(&sig));
PushLabel(kInvalidIstreamOffset, kInvalidIstreamOffset);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnLoopExpr(Index num_types,
Type* sig_types) {
TypeVector sig(sig_types, sig_types + num_types);
CHECK_RESULT(typechecker.OnLoop(&sig));
PushLabel(GetIstreamOffset(), kInvalidIstreamOffset);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnIfExpr(Index num_types,
Type* sig_types) {
TypeVector sig(sig_types, sig_types + num_types);
CHECK_RESULT(typechecker.OnIf(&sig));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::BrUnless));
IstreamOffset fixup_offset = GetIstreamOffset();
CHECK_RESULT(EmitI32(kInvalidIstreamOffset));
PushLabel(kInvalidIstreamOffset, fixup_offset);
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnElseExpr() {
CHECK_RESULT(typechecker.OnElse());
Label* label = TopLabel();
IstreamOffset fixup_cond_offset = label->fixup_offset;
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Br));
label->fixup_offset = GetIstreamOffset();
CHECK_RESULT(EmitI32(kInvalidIstreamOffset));
CHECK_RESULT(EmitI32At(fixup_cond_offset, GetIstreamOffset()));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnEndExpr() {
TypeChecker::Label* label;
CHECK_RESULT(typechecker.GetLabel(0, &label));
LabelType label_type = label->label_type;
CHECK_RESULT(typechecker.OnEnd());
if (label_type == LabelType::If || label_type == LabelType::Else) {
CHECK_RESULT(EmitI32At(TopLabel()->fixup_offset, GetIstreamOffset()));
}
FixupTopLabel();
PopLabel();
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnBrExpr(Index depth) {
Index drop_count, keep_count;
CHECK_RESULT(GetBrDropKeepCount(depth, &drop_count, &keep_count));
CHECK_RESULT(typechecker.OnBr(depth));
CHECK_RESULT(EmitBr(depth, drop_count, keep_count));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnBrIfExpr(Index depth) {
Index drop_count, keep_count;
CHECK_RESULT(typechecker.OnBrIf(depth));
CHECK_RESULT(GetBrDropKeepCount(depth, &drop_count, &keep_count));
/* flip the br_if so if <cond> is true it can drop values from the stack */
CHECK_RESULT(EmitOpcode(interpreter::Opcode::BrUnless));
IstreamOffset fixup_br_offset = GetIstreamOffset();
CHECK_RESULT(EmitI32(kInvalidIstreamOffset));
CHECK_RESULT(EmitBr(depth, drop_count, keep_count));
CHECK_RESULT(EmitI32At(fixup_br_offset, GetIstreamOffset()));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnBrTableExpr(
Index num_targets,
Index* target_depths,
Index default_target_depth) {
CHECK_RESULT(typechecker.BeginBrTable());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::BrTable));
CHECK_RESULT(EmitI32(num_targets));
IstreamOffset fixup_table_offset = GetIstreamOffset();
CHECK_RESULT(EmitI32(kInvalidIstreamOffset));
/* not necessary for the interpreter, but it makes it easier to disassemble.
* This opcode specifies how many bytes of data follow. */
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Data));
CHECK_RESULT(EmitI32((num_targets + 1) * WABT_TABLE_ENTRY_SIZE));
CHECK_RESULT(EmitI32At(fixup_table_offset, GetIstreamOffset()));
for (Index i = 0; i <= num_targets; ++i) {
Index depth = i != num_targets ? target_depths[i] : default_target_depth;
CHECK_RESULT(typechecker.OnBrTableTarget(depth));
CHECK_RESULT(EmitBrTableOffset(depth));
}
CHECK_RESULT(typechecker.EndBrTable());
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnCallExpr(Index func_index) {
Func* func = GetFuncByModuleIndex(func_index);
FuncSignature* sig = env->GetFuncSignature(func->sig_index);
CHECK_RESULT(
typechecker.OnCall(&sig->param_types, &sig->result_types));
if (func->is_host) {
CHECK_RESULT(EmitOpcode(interpreter::Opcode::CallHost));
CHECK_RESULT(EmitI32(TranslateFuncIndexToEnv(func_index)));
} else {
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Call));
CHECK_RESULT(EmitFuncOffset(func->as_defined(), func_index));
}
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnCallIndirectExpr(Index sig_index) {
if (module->table_index == kInvalidIndex) {
PrintError("found call_indirect operator, but no table");
return wabt::Result::Error;
}
FuncSignature* sig = GetSignatureByModuleIndex(sig_index);
CHECK_RESULT(typechecker.OnCallIndirect(&sig->param_types,
&sig->result_types));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::CallIndirect));
CHECK_RESULT(EmitI32(module->table_index));
CHECK_RESULT(EmitI32(TranslateSigIndexToEnv(sig_index)));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnCompareExpr(wabt::Opcode opcode) {
return OnBinaryExpr(opcode);
}
wabt::Result BinaryReaderInterpreter::OnConvertExpr(wabt::Opcode opcode) {
return OnUnaryExpr(opcode);
}
wabt::Result BinaryReaderInterpreter::OnDropExpr() {
CHECK_RESULT(typechecker.OnDrop());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Drop));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnI32ConstExpr(uint32_t value) {
CHECK_RESULT(typechecker.OnConst(Type::I32));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::I32Const));
CHECK_RESULT(EmitI32(value));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnI64ConstExpr(uint64_t value) {
CHECK_RESULT(typechecker.OnConst(Type::I64));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::I64Const));
CHECK_RESULT(EmitI64(value));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnF32ConstExpr(uint32_t value_bits) {
CHECK_RESULT(typechecker.OnConst(Type::F32));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::F32Const));
CHECK_RESULT(EmitI32(value_bits));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnF64ConstExpr(uint64_t value_bits) {
CHECK_RESULT(typechecker.OnConst(Type::F64));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::F64Const));
CHECK_RESULT(EmitI64(value_bits));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnGetGlobalExpr(Index global_index) {
CHECK_RESULT(CheckGlobal(global_index));
Type type = GetGlobalTypeByModuleIndex(global_index);
CHECK_RESULT(typechecker.OnGetGlobal(type));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::GetGlobal));
CHECK_RESULT(EmitI32(TranslateGlobalIndexToEnv(global_index)));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnSetGlobalExpr(Index global_index) {
CHECK_RESULT(CheckGlobal(global_index));
Global* global = GetGlobalByModuleIndex(global_index);
if (!global->mutable_) {
PrintError("can't set_global on immutable global at index %" PRIindex ".",
global_index);
return wabt::Result::Error;
}
CHECK_RESULT(
typechecker.OnSetGlobal(global->typed_value.type));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::SetGlobal));
CHECK_RESULT(EmitI32(TranslateGlobalIndexToEnv(global_index)));
return wabt::Result::Ok;
}
Index BinaryReaderInterpreter::TranslateLocalIndex(Index local_index) {
return typechecker.type_stack_size() +
current_func->param_and_local_types.size() - local_index;
}
wabt::Result BinaryReaderInterpreter::OnGetLocalExpr(Index local_index) {
CHECK_RESULT(CheckLocal(local_index));
Type type = GetLocalTypeByIndex(current_func, local_index);
// Get the translated index before calling typechecker.OnGetLocal because it
// will update the type stack size. We need the index to be relative to the
// old stack size.
Index translated_local_index = TranslateLocalIndex(local_index);
CHECK_RESULT(typechecker.OnGetLocal(type));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::GetLocal));
CHECK_RESULT(EmitI32(translated_local_index));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnSetLocalExpr(Index local_index) {
CHECK_RESULT(CheckLocal(local_index));
Type type = GetLocalTypeByIndex(current_func, local_index);
CHECK_RESULT(typechecker.OnSetLocal(type));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::SetLocal));
CHECK_RESULT(EmitI32(TranslateLocalIndex(local_index)));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnTeeLocalExpr(Index local_index) {
CHECK_RESULT(CheckLocal(local_index));
Type type = GetLocalTypeByIndex(current_func, local_index);
CHECK_RESULT(typechecker.OnTeeLocal(type));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::TeeLocal));
CHECK_RESULT(EmitI32(TranslateLocalIndex(local_index)));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnGrowMemoryExpr() {
CHECK_RESULT(CheckHasMemory(wabt::Opcode::GrowMemory));
CHECK_RESULT(typechecker.OnGrowMemory());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::GrowMemory));
CHECK_RESULT(EmitI32(module->memory_index));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnLoadExpr(wabt::Opcode opcode,
uint32_t alignment_log2,
Address offset) {
CHECK_RESULT(CheckHasMemory(opcode));
CHECK_RESULT(CheckAlign(alignment_log2, get_opcode_memory_size(opcode)));
CHECK_RESULT(typechecker.OnLoad(opcode));
CHECK_RESULT(EmitOpcode(opcode));
CHECK_RESULT(EmitI32(module->memory_index));
CHECK_RESULT(EmitI32(offset));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnStoreExpr(wabt::Opcode opcode,
uint32_t alignment_log2,
Address offset) {
CHECK_RESULT(CheckHasMemory(opcode));
CHECK_RESULT(CheckAlign(alignment_log2, get_opcode_memory_size(opcode)));
CHECK_RESULT(typechecker.OnStore(opcode));
CHECK_RESULT(EmitOpcode(opcode));
CHECK_RESULT(EmitI32(module->memory_index));
CHECK_RESULT(EmitI32(offset));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnCurrentMemoryExpr() {
CHECK_RESULT(CheckHasMemory(wabt::Opcode::CurrentMemory));
CHECK_RESULT(typechecker.OnCurrentMemory());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::CurrentMemory));
CHECK_RESULT(EmitI32(module->memory_index));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnNopExpr() {
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnReturnExpr() {
Index drop_count, keep_count;
CHECK_RESULT(GetReturnDropKeepCount(&drop_count, &keep_count));
CHECK_RESULT(typechecker.OnReturn());
CHECK_RESULT(EmitDropKeep(drop_count, keep_count));
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Return));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnSelectExpr() {
CHECK_RESULT(typechecker.OnSelect());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Select));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::OnUnreachableExpr() {
CHECK_RESULT(typechecker.OnUnreachable());
CHECK_RESULT(EmitOpcode(interpreter::Opcode::Unreachable));
return wabt::Result::Ok;
}
wabt::Result BinaryReaderInterpreter::EndModule() {
for (ElemSegmentInfo& info : elem_segment_infos) {
*info.dst = info.func_index;
}
for (DataSegmentInfo& info : data_segment_infos) {
memcpy(info.dst_data, info.src_data, info.size);
}
return wabt::Result::Ok;
}
} // namespace
wabt::Result read_binary_interpreter(Environment* env,
const void* data,
size_t size,
const ReadBinaryOptions* options,
BinaryErrorHandler* error_handler,
DefinedModule** out_module) {
// Need to mark before taking ownership of env->istream.
Environment::MarkPoint mark = env->Mark();
std::unique_ptr<OutputBuffer> istream = env->ReleaseIstream();
IstreamOffset istream_offset = istream->size();
DefinedModule* module = new DefinedModule();
BinaryReaderInterpreter reader(env, module, std::move(istream),
error_handler);
env->EmplaceBackModule(module);
wabt::Result result = read_binary(data, size, &reader, options);
env->SetIstream(reader.ReleaseOutputBuffer());
if (WABT_SUCCEEDED(result)) {
module->istream_start = istream_offset;
module->istream_end = env->istream().size();
*out_module = module;
} else {
env->ResetToMarkPoint(mark);
*out_module = nullptr;
}
return result;
}
} // namespace wabt
| 36.785617 | 80 | 0.683154 | [
"vector"
] |
53eaec7b65847e0746666f466ca752573e7399a6 | 64,844 | cpp | C++ | hub/src/TrayControlWindow.cpp | akarasulu/SubutaiTray | 50e70715360ec6fa8fffab4992232cdde488e321 | [
"Apache-2.0"
] | 8 | 2018-03-16T02:19:51.000Z | 2019-09-07T07:22:01.000Z | hub/src/TrayControlWindow.cpp | akarasulu/SubutaiTray | 50e70715360ec6fa8fffab4992232cdde488e321 | [
"Apache-2.0"
] | 446 | 2018-02-26T09:31:59.000Z | 2020-09-14T18:45:09.000Z | hub/src/TrayControlWindow.cpp | akarasulu/SubutaiTray | 50e70715360ec6fa8fffab4992232cdde488e321 | [
"Apache-2.0"
] | 18 | 2018-03-02T09:19:08.000Z | 2021-11-04T08:17:43.000Z | #include <QDesktopWidget>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QWidget>
#include <QWidgetAction>
#include <QtConcurrent/QtConcurrent>
#include <QtGui>
#include <algorithm>
#include "DlgAbout.h"
#include "DlgCreatePeer.h"
#include "DlgEnvironment.h"
#include "DlgGenerateSshKey.h"
#include "DlgLogin.h"
#include "DlgNotification.h"
#include "DlgNotifications.h"
#include "DlgPeer.h"
#include "DlgSettings.h"
#include "HubController.h"
#include "OsBranchConsts.h"
#include "P2PController.h"
#include "PeerController.h"
#include "RestWorker.h"
#include "RhController.h"
#include "SettingsManager.h"
#include "SystemCallWrapper.h"
#include "TrayControlWindow.h"
#include "libssh2/include/LibsshController.h"
#include "ui_TrayControlWindow.h"
#include "updater/HubComponentsUpdater.h"
#include "SshKeyController.h"
#include "DlgTransferFile.h"
using namespace update_system;
template <class OS>
static inline void InitTrayIconTriggerHandler_internal(QSystemTrayIcon *icon,
TrayControlWindow *win);
template <>
inline void InitTrayIconTriggerHandler_internal<Os2Type<OS_WIN> >(
QSystemTrayIcon *icon, TrayControlWindow *win) {
QObject::connect(icon, &QSystemTrayIcon::activated, win,
&TrayControlWindow::tray_icon_is_activated_sl);
}
template <>
inline void InitTrayIconTriggerHandler_internal<Os2Type<OS_LINUX> >(
QSystemTrayIcon *icon, TrayControlWindow *win) {
QObject::connect(icon, &QSystemTrayIcon::activated, win,
&TrayControlWindow::tray_icon_is_activated_sl);
}
template <>
inline void InitTrayIconTriggerHandler_internal<Os2Type<OS_MAC> >(
QSystemTrayIcon *icon, TrayControlWindow *win) {
UNUSED_ARG(icon);
UNUSED_ARG(win);
}
void InitTrayIconTriggerHandler(QSystemTrayIcon *icon, TrayControlWindow *win) {
InitTrayIconTriggerHandler_internal<Os2Type<CURRENT_OS> >(icon, win);
}
TrayControlWindow::TrayControlWindow(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::TrayControlWindow),
m_tray_menu(nullptr),
m_act_ssh_keys_management(nullptr),
m_act_quit(nullptr),
m_act_settings(nullptr),
m_act_balance(nullptr),
m_act_hub(nullptr),
m_act_user_name(nullptr),
m_act_launch_Hub(nullptr),
m_act_about(nullptr),
m_act_help(nullptr),
m_act_logout(nullptr),
m_sys_tray_icon(nullptr),
m_act_create_peer(nullptr),
m_act_p2p_start(nullptr),
m_act_p2p_stop(nullptr),
in_peer_slot(false) {
ui->setupUi(this);
create_tray_actions();
create_tray_icon();
m_sys_tray_icon->show();
p2p_current_status = P2PStatus_checker::P2P_LOADING;
CPeerController::Instance()->init();
SshKeyController::Instance();
connect(CNotificationObserver::Instance(), &CNotificationObserver::notify,
this, &TrayControlWindow::notification_received);
connect(&CHubController::Instance(),
&CHubController::ssh_to_container_from_tray_finished, this,
&TrayControlWindow::ssh_to_container_finished);
connect(&CHubController::Instance(),
&CHubController::desktop_to_container_from_tray_finished, this,
&TrayControlWindow::desktop_to_container_finished);
connect(&CHubController::Instance(), &CHubController::user_name_updated, this,
&TrayControlWindow::user_name_updated_sl);
connect(&CHubController::Instance(), &CHubController::balance_updated, this,
&TrayControlWindow::balance_updated_sl);
connect(&CHubController::Instance(), &CHubController::environments_updated,
this, &TrayControlWindow::environments_updated_sl);
connect(&CHubController::Instance(), &CHubController::my_peers_updated, this,
&TrayControlWindow::my_peers_updated_sl);
connect(CRestWorker::Instance(), &CRestWorker::on_got_ss_console_readiness,
this, &TrayControlWindow::got_ss_console_readiness_sl);
connect(CHubComponentsUpdater::Instance(),
&CHubComponentsUpdater::update_available, this,
&TrayControlWindow::update_available);
connect(CRhController::Instance(), &CRhController::ssh_to_rh_finished, this,
&TrayControlWindow::ssh_to_rh_finished_sl);
connect(CPeerController::Instance(), &CPeerController::got_peer_info, this,
&TrayControlWindow::got_peer_info_sl);
/*p2p status updater*/
connect(&P2PStatus_checker::Instance(), &P2PStatus_checker::p2p_status, this,
&TrayControlWindow::update_p2p_status_sl);
InitTrayIconTriggerHandler(m_sys_tray_icon, this);
CHubController::Instance().force_refresh();
login_success();
check_components();
save_current_pid();
}
TrayControlWindow::~TrayControlWindow() {
QMenu *menus[] = {m_hub_menu, m_hub_peer_menu, m_local_peer_menu,
m_tray_menu, m_p2p_menu};
QAction *acts[] = {m_act_ssh_keys_management,
m_act_quit,
m_act_settings,
m_act_balance,
m_act_hub,
m_act_user_name,
m_act_launch_Hub,
m_act_about,
m_act_help,
m_act_logout,
m_act_notifications_history,
m_act_p2p_start,
m_act_p2p_stop,
m_act_create_peer,
m_act_p2p_install};
for (size_t i = 0; i < sizeof(menus) / sizeof(QMenu *); ++i) {
if (menus[i] == nullptr) continue;
try {
delete menus[i];
} catch (...) { /*do nothing*/
}
}
for (size_t i = 0; i < sizeof(acts) / sizeof(QAction *); ++i) {
if (acts[i] == nullptr) continue;
try {
delete acts[i];
} catch (...) { /*do nothing*/
}
}
try {
delete m_sys_tray_icon;
} catch (...) {
}
delete ui;
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::save_current_pid(){
qint64 current_pid = QCoreApplication::applicationPid();
QFile f_pid(QCoreApplication::applicationDirPath() + QDir::separator() + "last_pid");
if (f_pid.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) {
QTextStream in(&f_pid);
in << current_pid;
f_pid.close();
} else {
qDebug("Failed to write pid");
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::check_components() {
if (!is_e2e_avaibale()) {
CNotificationObserver::Error(tr("Subutai E2E Plugin is not installed. It's "
"recommended to install it"),
DlgNotification::N_ABOUT);
}
if (!is_p2p_avaibale()) {
CNotificationObserver::Error(tr("P2P is not installed. You cannot manage "
"your cloud environments without P2P."),
DlgNotification::N_ABOUT);
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief close all opened dialogs, terminate all started processes.
///
void TrayControlWindow::application_quit() {
qDebug() << "Quitting the tray";
CProcessHandler::Instance()->clear_proc();
QApplication::closeAllWindows();
m_sys_tray_icon->hide();
QApplication::quit();
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::create_tray_actions() {
m_act_settings =
new QAction(QIcon(":/hub/settings-new.png"), tr("Settings"), this);
connect(m_act_settings, &QAction::triggered, this,
&TrayControlWindow::show_settings_dialog);
m_act_settings->setToolTip(tr("CC settings"));
m_act_hub =
new QAction(QIcon(":/hub/environments-new.png"), tr("Environments"), this);
QString user_name = "";
CRestWorker::Instance()->get_user_info("name", user_name);
m_act_user_name =
new QAction(QIcon(":/hub/user-new.png"), user_name.toStdString().c_str(), this);
connect(m_act_user_name, &QAction::triggered,
[] { CHubController::Instance().launch_balance_page(); });
m_act_user_name->setToolTip(tr("Name"));
m_act_quit = new QAction(QIcon(":/hub/quit-new.png"), tr("Quit"), this);
connect(m_act_quit, &QAction::triggered, this,
&TrayControlWindow::application_quit);
m_act_quit->setToolTip(tr("Close Control Center"));
m_act_launch_Hub =
new QAction(QIcon(":/hub/hub-new.png"), tr("Go to Bazaar"), this);
connect(m_act_launch_Hub, &QAction::triggered, this,
&TrayControlWindow::launch_Hub);
m_act_launch_Hub->setToolTip(tr("Opens the main page of Bazaar"));
m_act_balance = new QAction(QIcon(":/hub/wallet-new.png"),
CHubController::Instance().balance(), this);
connect(m_act_balance, &QAction::triggered,
[] { CHubController::Instance().launch_balance_page(); });
m_act_balance->setToolTip(tr("GoodWill"));
m_act_about = new QAction(QIcon(":/hub/components-new.png"), tr("Components"), this);
connect(m_act_about, &QAction::triggered, this,
&TrayControlWindow::show_about);
m_act_about->setToolTip(tr("Information about Control Center Components"));
m_act_help = new QAction(QIcon(":/hub/help-new.png"), tr("Help"), this);
connect(m_act_help, &QAction::triggered,
[] { CHubController::Instance().launch_help_page(); });
m_act_help->setToolTip(tr("Control Center guidelines"));
m_act_ssh_keys_management =
new QAction(QIcon(":/hub/ssh-keys-new.png"), tr("SSH Key Manager"), this);
connect(m_act_ssh_keys_management, &QAction::triggered, this,
&TrayControlWindow::ssh_key_generate_triggered);
m_act_ssh_keys_management->setToolTip(tr("Generate and Deploy SSH keys"));
m_act_logout = new QAction(QIcon(":/hub/logout-new.png"), tr("Logout"), this);
connect(m_act_logout, &QAction::triggered, this, &TrayControlWindow::logout);
m_act_logout->setToolTip(tr("Sign out from your account"));
m_act_notifications_history =
new QAction(QIcon(":hub/notifications-new.png"),
tr("Notification History"), this);
connect(m_act_notifications_history, &QAction::triggered, this,
&TrayControlWindow::show_notifications_triggered);
m_act_notifications_history->setToolTip(tr("Show Notification History"));
m_act_create_peer =
new QAction(QIcon(":hub/create-peer-new.png"), tr("Create Peer"), this);
connect(m_act_create_peer, &QAction::triggered, this,
&TrayControlWindow::show_create_dialog);
m_empty_action = new QAction(tr("Empty"), this);
m_empty_action->setEnabled(false);
m_act_create_peer->setToolTip(tr("Will create a new peer"));
// p2p action start
m_act_p2p_start =
new QAction(QIcon(":/hub/launch.png"), tr("Start P2P"), this);
connect(m_act_p2p_start, &QAction::triggered, this,
&TrayControlWindow::launch_p2p);
// p2p action stop
m_act_p2p_stop =
new QAction(QIcon(":/hub/stop_p2p.png"), tr("Stop P2P"), this);
connect(m_act_p2p_stop, &QAction::triggered, this,
&TrayControlWindow::stop_p2p);
// p2p action install
m_act_p2p_install =
new QAction(QIcon(":/hub/install.png"), tr("Install P2P"), this);
connect(m_act_p2p_install, &QAction::triggered, this,
&TrayControlWindow::launch_p2p_installation);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::create_tray_icon() {
m_sys_tray_icon = new QSystemTrayIcon(this);
m_tray_menu = new QMenu(this);
m_sys_tray_icon->setContextMenu(m_tray_menu);
// p2p menu
m_p2p_menu = m_tray_menu->addMenu(QIcon(":hub/loading.png"),
tr("P2P is loading..."));
m_tray_menu->addSeparator();
m_tray_menu->addAction(m_act_launch_Hub);
m_tray_menu->addAction(m_act_user_name);
m_tray_menu->addAction(m_act_balance);
m_tray_menu->addSeparator();
m_hub_menu = m_tray_menu->addMenu(QIcon(":/hub/environments-new.png"),
tr("Environments"));
m_hub_menu->setStyleSheet(qApp->styleSheet());
m_hub_menu->addAction(m_empty_action);
m_hub_peer_menu =
m_tray_menu->addMenu(QIcon(":/hub/my-peers-new.png"), tr("My Peers"));
m_hub_peer_menu->addAction(m_empty_action);
m_local_peer_menu =
m_tray_menu->addMenu(QIcon(":/hub/lan-peers-new.png"), tr("LAN Peers"));
m_local_peer_menu->addAction(m_empty_action);
m_tray_menu->addAction(m_act_create_peer);
m_tray_menu->addSeparator();
m_tray_menu->addAction(m_act_settings);
m_tray_menu->addAction(m_act_ssh_keys_management);
m_tray_menu->addAction(m_act_notifications_history);
m_tray_menu->addAction(m_act_about);
m_tray_menu->addSeparator();
m_tray_menu->addAction(m_act_help);
m_tray_menu->addAction(m_act_logout);
m_tray_menu->addAction(m_act_quit);
m_sys_tray_icon->setIcon(QIcon(":/hub/cc_icon_last.png"));
}
void TrayControlWindow::get_sys_tray_icon_coordinates_for_dialog(
int &src_x, int &src_y, int &dst_x, int &dst_y, int dlg_w, int dlg_h,
bool use_cursor_position) {
int icon_x, icon_y;
dst_x = dst_y = 0;
src_x = src_y = 0;
icon_x = m_sys_tray_icon->geometry().x();
icon_y = m_sys_tray_icon->geometry().y();
int adw, adh;
adw = QApplication::desktop()->availableGeometry().width();
adh = QApplication::desktop()->availableGeometry().height();
if (icon_x == 0 && icon_y == 0) {
if (use_cursor_position) {
icon_x = QCursor::pos().x();
icon_y = QCursor::pos().y();
} else {
int coords[] = {adw, 0, adw, adh, 0, adh, 0, 0};
uint32_t pc =
CSettingsManager::Instance().preferred_notifications_place();
icon_x = coords[pc * 2];
icon_y = coords[pc * 2 + 1];
}
}
int dx, dy;
dy = QApplication::desktop()->availableGeometry().y();
dx = QApplication::desktop()->availableGeometry().x();
#ifdef RT_OS_WINDOWS
dy += dy ? 0 : 35; // don't know why -20 and 35
#endif
if (icon_x < adw / 2) {
src_x = -dlg_w + dx;
dst_x = src_x + dlg_w;
} else {
src_x = adw + dx;
dst_x = src_x - dlg_w;
}
src_y = icon_y < adh / 2 ? dy : adh - dy - dlg_h;
dst_y = src_y;
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::tray_icon_is_activated_sl(
QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
m_sys_tray_icon->contextMenu()->exec(
QPoint(QCursor::pos().x(), QCursor::pos().y()));
}
}
////////////////////////////////////////////////////////////////////////////
static QPoint lastNotificationPos(0, 0);
template <class OS>
static inline void shift_notification_dialog_positions_internal(
int &src_y, int &dst_y, int shift_value);
template <>
inline void shift_notification_dialog_positions_internal<Os2Type<OS_LINUX> >(
int &src_y, int &dst_y, int shift_value) {
const int &pref_place =
CSettingsManager::Instance().preferred_notifications_place();
if (pref_place == 1 ||
pref_place ==
2) { // if the notification dialogs on the top of the screen
src_y = lastNotificationPos.y() - shift_value;
dst_y = lastNotificationPos.y() - shift_value;
} else { // on the bottom
src_y = lastNotificationPos.y() + shift_value;
dst_y = lastNotificationPos.y() + shift_value;
}
}
template <>
inline void shift_notification_dialog_positions_internal<Os2Type<OS_WIN> >(
int &src_y, int &dst_y, int shift_value) {
src_y = lastNotificationPos.y() - shift_value;
dst_y = lastNotificationPos.y() - shift_value;
}
template <>
inline void shift_notification_dialog_positions_internal<Os2Type<OS_MAC> >(
int &src_y, int &dst_y, int shift_value) {
src_y = lastNotificationPos.y() + shift_value;
dst_y = lastNotificationPos.y() + shift_value;
}
void shift_notification_dialog_positions(int &src_y, int &dst_y,
int shift_value) {
shift_notification_dialog_positions_internal<Os2Type<CURRENT_OS> >(
src_y, dst_y, shift_value);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::notification_received(
CNotificationObserver::notification_level_t level, const QString &msg,
DlgNotification::NOTIFICATION_ACTION_TYPE action_type) {
qDebug() << "Message: " << msg << "Level: "
<< CNotificationObserver::notification_level_to_str(level)
<< "Action Type: " << (size_t)action_type
<< "Current notification level: "
<< CSettingsManager::Instance().notifications_level()
<< "Message is ignored: "
<< CSettingsManager::Instance().is_notification_ignored(msg);
if (CSettingsManager::Instance().is_notification_ignored(msg) ||
(uint32_t)level < CSettingsManager::Instance().notifications_level()) {
return;
}
QDialog *dlg = new DlgNotification(level, msg, this, action_type);
dlg->setWindowFlags(Qt::Window | Qt::CustomizeWindowHint |
Qt::WindowStaysOnTopHint);
dlg->setAttribute(Qt::WA_ShowWithoutActivating);
connect(dlg, &QDialog::finished, dlg, &DlgNotification::deleteLater);
int src_x, src_y, dst_x, dst_y;
get_sys_tray_icon_coordinates_for_dialog(src_x, src_y, dst_x, dst_y,
dlg->width(), dlg->height(), false);
if (DlgNotification::NOTIFICATIONS_COUNT > 1 &&
DlgNotification::NOTIFICATIONS_COUNT < 4) { // shift dialog if there is more than one dialogs
shift_notification_dialog_positions(src_y, dst_y, dlg->height() + 20);
}
if (CSettingsManager::Instance().use_animations()) {
QPropertyAnimation *pos_anim = new QPropertyAnimation(dlg, "pos");
QPropertyAnimation *opa_anim = new QPropertyAnimation(dlg, "windowOpacity");
pos_anim->setStartValue(QPoint(src_x, src_y));
pos_anim->setEndValue(QPoint(dst_x, dst_y));
pos_anim->setEasingCurve(QEasingCurve::OutBack);
pos_anim->setDuration(800);
opa_anim->setStartValue(0.0);
opa_anim->setEndValue(1.0);
opa_anim->setEasingCurve(QEasingCurve::Linear);
opa_anim->setDuration(800);
QParallelAnimationGroup *gr = new QParallelAnimationGroup;
gr->addAnimation(pos_anim);
gr->addAnimation(opa_anim);
dlg->move(src_x, src_y);
dlg->show();
gr->start();
connect(gr, &QParallelAnimationGroup::finished, gr,
&QParallelAnimationGroup::deleteLater);
} else {
dlg->move(dst_x, dst_y);
dlg->show();
}
lastNotificationPos = dlg->pos();
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::logout() {
std::vector<QDialog *> lstActiveDialogs(m_dct_active_dialogs.size());
int i = 0;
// this extra copy because on dialog finish we are removing it from
// m_dct_active_dialogs
for (auto j = m_dct_active_dialogs.begin(); j != m_dct_active_dialogs.end();
++j, ++i)
lstActiveDialogs[i] = j->second;
// close active dialogs
for (auto dialog : lstActiveDialogs) {
dialog->close();
}
CHubController::Instance().logout();
this->m_sys_tray_icon->hide();
CSettingsManager::Instance().set_remember_me(false);
DlgLogin dlg;
connect(&dlg, &DlgLogin::login_success, this,
&TrayControlWindow::login_success);
dlg.setModal(true);
if (dlg.exec() != QDialog::Accepted) {
qApp->exit(0);
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::login_success() {
CHubController::Instance().force_refresh();
emit user_name_updated_sl();
m_sys_tray_icon->show();
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::upload_to_container_triggered(
const CEnvironment &env, const CHubContainer &cont) {
QString ssh_key = CHubController::Instance().get_env_key(env.id());
QString username = CSettingsManager::Instance().ssh_user();
if (ssh_key.isEmpty()) {
CNotificationObserver::Error(
CHubController::ssh_desktop_launch_err_to_str(SDLE_NO_KEY_FILE_TANSFER_DEPLOYED),
DlgNotification::N_NO_ACTION);
return;
}
// generate_transferfile_dlg();
DlgTransferFile *dlg_transfer_file = new DlgTransferFile(this);
Qt::WindowFlags flags = 0;
flags = Qt::Window;
flags |= Qt::WindowMinimizeButtonHint;
flags |= Qt::WindowMaximizeButtonHint;
flags |= Qt::WindowCloseButtonHint;
dlg_transfer_file->setWindowFlags(flags);
if (P2PController::Instance().is_cont_in_machine(cont.peer_id())) {
dlg_transfer_file->addIPPort(cont.ip(), QString(""));
} else {
CSystemCallWrapper::container_ip_and_port cip =
CSystemCallWrapper::container_ip_from_ifconfig_analog(
cont.port(), cont.ip(), cont.rh_ip());
dlg_transfer_file->addIPPort(cip.ip, cip.port);
}
dlg_transfer_file->addSSHKey(ssh_key);
dlg_transfer_file->addUser(username);
m_last_generated_tranferfile_dlg = dlg_transfer_file;
show_dialog(last_generated_transferfile_dlg,
"Transfer File " + env.name() + "/" + cont.name());
}
void TrayControlWindow::ssh_to_container_triggered(const CEnvironment &env,
const CHubContainer &cont) {
qDebug()
<< QString("Environment [name: %1, id: %2]").arg(env.name(), env.id())
<< QString("Container [name: %1, id: %2]").arg(cont.name(), cont.id());
CHubController::Instance().ssh_to_container_from_tray(env, cont);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::ssh_to_rh_triggered(const QString &peer_fingerprint) {
qDebug() << QString("Peer [peer_fingerprint: %1]").arg(peer_fingerprint);
QtConcurrent::run(CRhController::Instance(), &CRhController::ssh_to_rh,
peer_fingerprint);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::ssh_to_rh_finished_sl(const QString &peer_fingerprint,
system_call_wrapper_error_t res,
int libbssh_exit_code) {
qDebug() << QString("Peer [peer_fingerprint: %1]").arg(peer_fingerprint);
if (res != SCWE_SUCCESS) {
if (libbssh_exit_code != 0)
CNotificationObserver::Info(
tr("This Peer is not accessible with provided credentials. Please "
"check and verify. Error SSH code: %1")
.arg(CLibsshController::run_libssh2_error_to_str(
(run_libssh2_error_t)libbssh_exit_code)),
DlgNotification::N_NO_ACTION);
else
CNotificationObserver::Info(
tr("Cannot run terminal to SSH into the peer. Error code: %1")
.arg(CSystemCallWrapper::scwe_error_to_str(res)),
DlgNotification::N_NO_ACTION);
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::desktop_to_container_triggered(
const CEnvironment &env, const CHubContainer &cont) {
qDebug()
<< QString("Environment [name: %1, id: %2]").arg(env.name(), env.id())
<< QString("Container [name: %1, id: %2]").arg(cont.name(), cont.id())
<< QString("X2go is Launchable: %1")
.arg(CSystemCallWrapper::x2goclient_check());
if (!CSystemCallWrapper::x2goclient_check()) {
CNotificationObserver::Error(
QObject::tr("X2Go-Client is not launchable. Make sure x2go-client is "
"installed from \"Components\".")
.arg(x2goclient_url()),
DlgNotification::N_ABOUT);
return;
}
QString key = CHubController::Instance().get_env_key(env.id());
if (key.isEmpty()) {
CNotificationObserver::Error(
tr("Can't SSH to container. Err : %1")
.arg(CHubController::ssh_desktop_launch_err_to_str(SDLE_NO_KEY_DEPLOYED)),
DlgNotification::N_NO_ACTION);
return;
}
if (OS_MAC == CURRENT_OS) {
QString xquartz_version;
CSystemCallWrapper::xquartz_version(xquartz_version);
if (xquartz_version == "undefined") {
CNotificationObserver::Error(
QObject::tr("XQuartz is not launchable. Make sure XQuartz is "
"installed from \"Components\"."),
DlgNotification::N_ABOUT);
return;
}
}
CHubController::Instance().desktop_to_container_from_tray(env, cont);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::update_available(QString file_id) {
qDebug() << "File ID: " << file_id;
CNotificationObserver::Info(
tr("Update for %1 is available. Check \"Components\" dialog").arg(file_id),
DlgNotification::N_ABOUT);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::update_finished(QString file_id, bool success) {
qDebug() << QString("File ID: %1, Success: %2").arg(file_id, success);
if (!success) {
CNotificationObserver::Error(
tr("Failed to update %1. See details in error logs").arg(file_id),
DlgNotification::N_NO_ACTION);
return;
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::launch_Hub() {
CHubController::Instance().launch_browser(hub_site());
}
////////////////////////////////////////////////////////////////////////////
/* p2p start */
void TrayControlWindow::launch_p2p() {
qDebug() << "P2P start is pressed";
int rse_err;
CSystemCallWrapper::restart_p2p_service(&rse_err, restart_p2p_type::STOPPED_P2P);
if (rse_err == 0)
CNotificationObserver::Instance()->Info(tr("Please wait while P2P Daemon is being launched."), DlgNotification::N_NO_ACTION);
else
CNotificationObserver::Error(QObject::tr("Cannot launch P2P Daemon. "
"Either change the path setting in Settings or install the Daemon if it is not installed. "
"You can get the %1 daemon from <a href=\"%2\">here</a>.").
arg(current_branch_name_with_changes()).arg(p2p_package_url()), DlgNotification::N_SETTINGS);
emit P2PStatus_checker::Instance().p2p_status(P2PStatus_checker::P2P_LOADING);
}
/* p2p stop */
void TrayControlWindow::stop_p2p() {
int rse_err;
CSystemCallWrapper::restart_p2p_service(&rse_err, restart_p2p_type::STARTED_P2P);
}
/*p2p installations */
void TrayControlWindow::launch_p2p_installation() {
update_system::CHubComponentsUpdater::Instance()->install_p2p();
}
//////////////////////////////////////
void TrayControlWindow::user_name_updated_sl() {
QString user_name = "";
CRestWorker::Instance()->get_user_info("name", user_name);
m_act_user_name->setText(user_name);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::balance_updated_sl() {
m_act_balance->setText(CHubController::Instance().balance());
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::environments_updated_sl(int rr) {
qDebug() << "Updating Environment List"
<< "Result: " << rr;
m_hub_menu->setEnabled(false); // MacOS Qt bug.
static QIcon unhealthy_icon(":/hub/BAD.png");
static QIcon healthy_icon(":/hub/GOOD.png");
static QIcon modification_icon(":/hub/OK.png");
static QString deteted_string("DELETED");
static std::vector<QString> lst_checked_unhealthy_env;
std::map<QString, std::vector<QString> > tbl_envs;
std::map<QString, std::vector<int> > tbl_env_ids;
std::map<QString, int> new_envs;
for (auto env = CHubController::Instance().lst_environments().cbegin();
env != CHubController::Instance().lst_environments().cend(); ++env) {
QString env_id = env->id();
environments_table[env_id] = *env;
QString env_name = env->name();
//mark that env still exist
new_envs[env_name] = 1;
//update action button, create if does not exist
QAction *env_start;
if(my_envs_button_table.find(env_id) == my_envs_button_table.end()){
env_start = new QAction;
m_hub_menu->addAction(env_start);
m_hub_menu->removeAction(m_empty_action);
connect(env_start, &QAction::triggered, [env_id, this]() {
if(environments_table.find(env_id) == environments_table.end()){
CNotificationObserver::Instance()->Error(tr("This environment credentials does not exist. "
"Please restart Control Center to refresh menu."),
DlgNotification::N_NO_ACTION);
return;
}
CEnvironment env = environments_table[env_id];
this->generate_env_dlg(&env);
TrayControlWindow::show_dialog(TrayControlWindow::last_generated_env_dlg,
QString("Environment \"%1\" (%2)")
.arg(env.name())
.arg(env.status()));
});
my_envs_button_table[env_id] = env_start;
}
else{
env_start = my_envs_button_table[env_id];
}
env_start->setEnabled(false); // MacOS Qt bug.
env_start->setEnabled(true);
env_start->setText(env_name);
env_start->setIcon(env->status() == "HEALTHY"
? healthy_icon
: env->status() == "UNHEALTHY" ? unhealthy_icon
: modification_icon);
//mark envs that changed their status
std::vector<QString>::iterator iter_found =
std::find(lst_checked_unhealthy_env.begin(),
lst_checked_unhealthy_env.end(), env->id());
if (!env->healthy()) {
if (iter_found == lst_checked_unhealthy_env.end()) {
lst_checked_unhealthy_env.push_back(env->id());
tbl_envs[env->status()].push_back(env_name);
tbl_env_ids[env->status()].push_back(env->hub_id());
qCritical("Environment %s, %s is unhealthy. Reason : %s",
env_name.toStdString().c_str(),
env->id().toStdString().c_str(),
env->status_description().toStdString().c_str());
}
} else {
if (iter_found != lst_checked_unhealthy_env.end()) {
QString env_url = hub_billing_url()
.arg(CHubController::Instance().current_user_id()) +
QString("/environments/%1").arg(env->hub_id());
CNotificationObserver::Info(
tr("Environment <a href=%1>%2</a> became healthy")
.arg(env_url, env->name()),
DlgNotification::N_NO_ACTION);
qInfo("Environment %s became healthy",
env->name().toStdString().c_str());
lst_checked_unhealthy_env.erase(iter_found);
}
qInfo("Environment %s is healthy", env->name().toStdString().c_str());
}
}
// show notification about environment changed their status
for (std::map<QString, std::vector<QString> >::iterator it = tbl_envs.begin();
it != tbl_envs.end(); it++) {
if (!it->second.empty()) {
QString str_env_names = "";
QString env_url = hub_billing_url()
.arg(CHubController::Instance().current_user_id()) +
QString("/environments/%1");
for (size_t i = 0; i < it->second.size() - 1; i++)
str_env_names += QString("<a href=%1>")
.arg(env_url.arg(tbl_env_ids[it->first][i])) + it->second[i] + "</a>, ";
str_env_names += QString("<a href=%1>").
arg(env_url.arg(tbl_env_ids[it->first][it->second.size() - 1])) +
it->second[it->second.size() - 1] + "</a>";
QString str_notifications = tr("Environment%1 %2 %3 %4")
.arg(it->second.size() > 1 ? "s" : "")
.arg(str_env_names)
.arg(it->second.size() > 1 ? "are" : "is")
.arg(it->first);
CNotificationObserver::Instance()->Info(str_notifications,
DlgNotification::N_NO_ACTION);
}
}
// mark deleted environments
for (std::map<QString, CEnvironment>::iterator it =
environments_table.begin();
it != environments_table.end(); it++) {
if (new_envs[it->second.name()] == 0){
it->second.set_status(deteted_string);
if(my_envs_button_table.find(it->second.id()) == my_envs_button_table.end()) continue;
m_hub_menu->removeAction(my_envs_button_table[it->second.id()]);
if(m_hub_menu->isEmpty())
m_hub_menu->addAction(m_empty_action);
my_envs_button_table.erase(my_envs_button_table.find(it->second.id()));
}
}
m_hub_menu->setEnabled(true);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::my_peers_updated_sl() {
in_peer_slot = true;
QString msgDisconnected = "", msgOnline = "", msgOffline = "";
// get peers list;
std::vector<CMyPeerInfo> hub_peers =
CHubController::Instance().lst_my_peers();
std::vector<std::pair<QString, QString> > network_peers;
for (std::pair<QString, QString> local_peer :
CRhController::Instance()->dct_resource_hosts()) {
network_peers.push_back(std::make_pair(
CCommons::GetFingerprintFromUid(local_peer.first), local_peer.second));
}
// update connected peers
for (auto peer_info : hub_peers) {
if (hub_peers_table.find(peer_info.fingerprint()) ==
hub_peers_table.end()) {
peer_info.status() == "ONLINE" ? msgOnline += ", " + peer_info.name()
: msgOffline += ", " + peer_info.name();
} else if (hub_peers_table[peer_info.fingerprint()].status() !=
peer_info.status()) {
peer_info.status() == "ONLINE" ? msgOnline += ", " + peer_info.name()
: msgOffline += ", " + peer_info.name();
}
peer_info.set_updated(true);
hub_peers_table[peer_info.fingerprint()] = peer_info;
update_peer_button(peer_info.fingerprint().toUpper(), peer_info);
}
for (auto peer_info : network_peers) {
network_peers_table[peer_info.first] =
std::make_pair(peer_info.second, true);
update_peer_button(peer_info.first.toUpper(), peer_info);
}
// delete disconnected peers
std::vector<QString> hub_disconnected_peers;
std::vector<QString> network_disconnected_peers;
for (auto peer_it = hub_peers_table.begin(); peer_it != hub_peers_table.end();
peer_it++) {
if (!peer_it->second.updated()) {
hub_disconnected_peers.push_back(peer_it->second.fingerprint());
msgDisconnected += ", " + peer_it->second.name();
} else {
peer_it->second.set_updated(false);
}
}
for (auto peer_it = network_peers_table.end();
peer_it != network_peers_table.end(); peer_it++) {
if (!peer_it->second.second) {
network_disconnected_peers.push_back(peer_it->first);
} else {
peer_it->second.second = false;
}
}
for (auto del_me : hub_disconnected_peers) {
hub_peers_table.erase(hub_peers_table.find(del_me));
delete_peer_button_info(del_me.toUpper(), 1);
}
for (auto del_me : network_disconnected_peers) {
network_peers_table.erase(network_peers_table.find(del_me));
delete_peer_button_info(del_me.toUpper(), 2);
}
// show notifications
if (!msgOnline.isEmpty()) {
msgOnline.remove(0, 2);
CNotificationObserver::Instance()->Info(
tr("%1 %2 online")
.arg(msgOnline, msgOnline.contains(", ") ? "are" : "is"),
DlgNotification::N_GO_TO_HUB_PEER);
}
if (!msgOffline.isEmpty()) {
msgOffline.remove(0, 2);
CNotificationObserver::Instance()->Info(
tr("%1 %2 offline")
.arg(msgOffline, msgOffline.contains(", ") ? "are" : "is"),
DlgNotification::N_GO_TO_HUB_PEER);
}
if (!msgDisconnected.isEmpty()) {
msgDisconnected.remove(0, 2);
CNotificationObserver::Instance()->Info(
tr("%1 %2 disconnected")
.arg(msgDisconnected,
msgDisconnected.contains(", ") ? "are" : "is"),
DlgNotification::N_GO_TO_HUB_PEER);
}
in_peer_slot = false;
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::got_peer_info_sl(CPeerController::peer_info_t type, QString name, QString dir,
QString output) {
qDebug() << "UPDATE PEER ICON";
in_peer_slot = true;
static QString new_updated = "new";
static int minus_one = -1;
if (type == CPeerController::P_STATUS &&
name == "update" && dir == "peer" && output == "menu") {
machine_peers_upd_finished();
in_peer_slot = false;
return;
}
if (CPeerController::Instance()->get_number_threads() <= 0) {
in_peer_slot = false;
return;
}
CPeerController::Instance()->dec_number_threads();
CLocalPeer updater_peer;
if (machine_peers_table.find(name) != machine_peers_table.end())
updater_peer = machine_peers_table[name];
updater_peer.set_dir(dir);
updater_peer.set_name(name);
updater_peer.set_update(new_updated);
switch (type) {
case CPeerController::P_STATUS:
updater_peer.set_status(output);
break;
case CPeerController::P_PORT:
updater_peer.set_ip(output);
break;
case CPeerController::P_FINGER:
if (output != "undefined" && !output.isEmpty() &&
CSettingsManager::Instance().peer_finger(name) != output) {
delete_peer_button_info(CSettingsManager::Instance().peer_finger(name),
0);
CSettingsManager::Instance().set_peer_finger(name, output);
}
updater_peer.set_fingerprint(output);
break;
case CPeerController::P_UPDATE:
updater_peer.set_update_available(output);
break;
case CPeerController::P_PROVISION_STEP:
output != "finished" ?
updater_peer.set_provision_step(output.toInt()) :
updater_peer.set_provision_step(minus_one);
break;
default:
break;
}
machine_peers_table[name] = updater_peer;
if (!CSettingsManager::Instance()
.peer_finger(updater_peer.name())
.isEmpty()) {
delete_peer_button_info(updater_peer.name(), 0);
update_peer_button(
CSettingsManager::Instance().peer_finger(updater_peer.name()),
updater_peer);
} else {
update_peer_button(updater_peer.name(), updater_peer);
}
if (CPeerController::Instance()->get_number_threads() == 0) {
machine_peers_upd_finished();
}
in_peer_slot = false;
}
void TrayControlWindow::machine_peers_upd_finished() {
qDebug() << "refresh of local machine peers finished"
<< "number of total peers in table" << machine_peers_table.size();
std::vector<QString> delete_me;
for (auto it = machine_peers_table.begin(); it != machine_peers_table.end();
it++) {
if (it->second.update() == "old") {
delete_peer_button_info(
CSettingsManager::Instance().peer_finger(it->second.name()), 0);
delete_peer_button_info(it->second.name(), 0);
delete_me.push_back(it->second.name());
} else
it->second.set_update("old");
}
for (auto del : delete_me) {
machine_peers_table.erase(machine_peers_table.find(del));
}
}
void TrayControlWindow::peer_deleted_sl(const QString &peer_name) {
machine_peers_table.erase(machine_peers_table.find(peer_name));
CPeerController::Instance()->finish_current_update();
}
void TrayControlWindow::peer_under_modification_sl(const QString &peer_name) {
static QString running_string = "running";
static QString undefined_string = "undefined";
if (machine_peers_table.find(peer_name) != machine_peers_table.end()) {
machine_peers_table[peer_name].set_status(running_string);
machine_peers_table[peer_name].set_ip(undefined_string);
}
CPeerController::Instance()->finish_current_update();
}
void TrayControlWindow::peer_poweroff_sl(const QString &peer_name) {
static QString poweroff_string = "poweroff";
static QString undefined_string = "undefined";
if (machine_peers_table.find(peer_name) != machine_peers_table.end()) {
machine_peers_table[peer_name].set_status(poweroff_string);
machine_peers_table[peer_name].set_ip(undefined_string);
}
CPeerController::Instance()->finish_current_update();
}
void TrayControlWindow::peer_update_peeros_sl(const QString peer_fingerprint) {
QString updating_str = "updating";
QString finished_str = "finished";
if (my_peers_button_table.find(peer_fingerprint) == my_peers_button_table.end()) {
qCritical() << "tried to update deleted peer: " << peer_fingerprint;
return;
}
my_peer_button *peer_instance = my_peers_button_table[peer_fingerprint];
QString peer_name, peer_port, local_peer_name;
if (peer_instance->m_local_peer != nullptr){
if (peer_instance->m_local_peer->update_available() == "updating") {
qCritical() << "tried to update updating peer: " << peer_fingerprint;
return;
}
local_peer_name = peer_name = peer_instance->m_local_peer->name();
peer_port = peer_instance->m_local_peer->ip();
} else {
qCritical() << "tried to update deleted peer: " << peer_fingerprint;
return;
}
if (peer_instance->m_hub_peer != nullptr){
peer_name = peer_instance->m_hub_peer->name();
}
UpdatePeerOS *peer_updater = new UpdatePeerOS(this);
peer_updater->init(peer_name, peer_port);
connect(peer_updater, &UpdatePeerOS::outputReceived,
[this, local_peer_name, finished_str](system_call_wrapper_error_t res){
if (res == SCWE_SUCCESS) {
qDebug() << "update peeros for the " << local_peer_name << "finished with success error";
} else {
qCritical() << "update peeros for the" << local_peer_name << "finished with failed error";
}
if (machine_peers_table.find(local_peer_name) != machine_peers_table.end()){
machine_peers_table[local_peer_name].set_update_available(finished_str);
}
});
connect(peer_updater, &UpdatePeerOS::outputReceived,
peer_updater, &UpdatePeerOS::deleteLater);
if (machine_peers_table.find(local_peer_name) != machine_peers_table.end()){
machine_peers_table[local_peer_name].set_update_available(updating_str);
}
peer_updater->startWork();
}
// local peer
void TrayControlWindow::update_peer_button(const QString &peer_id,
const CLocalPeer &peer_info) {
qDebug() << "update peer button information wih local peer"
<< peer_id
<< peer_info.fingerprint();
if (my_peers_button_table.find(peer_id) == my_peers_button_table.end()) {
my_peer_button *new_peer_button =
new my_peer_button(peer_id, peer_info.name());
my_peers_button_table[peer_id] = new_peer_button;
}
my_peer_button *peer_button = my_peers_button_table[peer_id];
if (peer_button->m_local_peer == nullptr) {
peer_button->m_local_peer = new CLocalPeer;
}
if (peer_info.status() == "running") {
if (peer_info.ip() == "undefined" || peer_info.ip() == "loading" ||
peer_info.ip().isEmpty()) {
peer_button->m_local_peer_state = 3;
} else if (peer_info.fingerprint() == "undefined" ||
peer_info.fingerprint() == "loading" ||
peer_info.fingerprint().isEmpty()) {
peer_button->m_local_peer_state = 3;
} else {
peer_button->m_local_peer_state = 1;
}
} else {
peer_button->m_local_peer_state = 2;
}
if (peer_button->m_hub_peer == nullptr) {
peer_button->peer_name = peer_info.name();
}
*(peer_button->m_local_peer) = peer_info;
update_peer_icon(peer_id);
}
// hub peer
void TrayControlWindow::update_peer_button(const QString &peer_id,
const CMyPeerInfo &peer_info) {
qDebug() << "update peer button information wih hub peer"
<< peer_id;
if (my_peers_button_table.find(peer_id) == my_peers_button_table.end()) {
my_peer_button *new_peer_button =
new my_peer_button(peer_id, peer_info.name());
my_peers_button_table[peer_id] = new_peer_button;
}
my_peer_button *peer_button = my_peers_button_table[peer_id];
if (peer_button->m_hub_peer == nullptr) {
peer_button->m_hub_peer = new CMyPeerInfo;
}
if (peer_info.status() == "ONLINE") {
peer_button->m_hub_peer_state = 1;
} else {
peer_button->m_hub_peer_state = 2;
}
peer_button->peer_name = peer_info.name();
*(peer_button->m_hub_peer) = peer_info;
update_peer_icon(peer_id);
}
// lan peer
void TrayControlWindow::update_peer_button(
const QString &peer_id, const std::pair<QString, QString> &peer_info) {
qDebug() << "update peer button information wih network peer(rh)"
<< peer_id;
if (my_peers_button_table.find(peer_id) == my_peers_button_table.end()) {
my_peer_button *new_peer_button =
new my_peer_button(peer_id, peer_info.second);
my_peers_button_table[peer_id] = new_peer_button;
}
my_peer_button *peer_button = my_peers_button_table[peer_id];
if ((peer_button->m_hub_peer_state || peer_button->m_local_peer_state) == 0) {
peer_button->peer_name = peer_info.second;
}
if (peer_button->m_network_peer == nullptr) {
peer_button->m_network_peer = new std::pair<QString, QString>;
}
*(peer_button->m_network_peer) = peer_info;
peer_button->m_network_peer_state = 1;
update_peer_icon(peer_id);
}
void TrayControlWindow::update_peer_icon(const QString &peer_id) {
qDebug() << "update peer icon: " << peer_id;
static QIcon online_icon(":/hub/GOOD.png");
static QIcon offline_icon(":/hub/BAD.png");
static QIcon unknown_icon(":/hub/OK.png");
static QIcon local_hub(":/hub/local_hub.png");
static QIcon local_network_icon(":/hub/local-network.png");
static QIcon local_machine_off_icon(":/hub/local_off.png");
static QIcon map_icons[2][3][4] = {
{
// no network peer(rh)
{ unknown_icon, local_network_icon, local_machine_off_icon, unknown_icon }, // no hub peer
{ online_icon, local_hub, local_machine_off_icon, unknown_icon }, // online hub peer
{ offline_icon, local_hub, local_machine_off_icon, unknown_icon }, // offline hub peer
},
{
// found network peer(rh)
{ local_network_icon, local_network_icon, local_machine_off_icon, unknown_icon },
{ local_hub, local_hub, local_machine_off_icon, unknown_icon },
{ local_hub, local_network_icon, local_machine_off_icon }
}
};
my_peer_button *peer_button = my_peers_button_table[peer_id];
if (peer_button == nullptr) {
return;
}
if (peer_button->m_my_peers_item == nullptr) {
peer_button->m_my_peers_item = new QAction;
connect(peer_button->m_my_peers_item, &QAction::triggered,
[this, peer_id]() {
this->my_peer_button_pressed_sl(peer_id);
});
}
peer_button->m_my_peers_item->setText(peer_button->peer_name);
peer_button->m_my_peers_item->setIcon(
map_icons[peer_button->m_network_peer_state]
[peer_button->m_hub_peer_state]
[peer_button->m_local_peer_state]);
if ((peer_button->m_local_peer_state || peer_button->m_hub_peer_state) ==
0) { // no information about hub and local peers
if (peer_button->m_my_peers_item != nullptr) {
m_hub_peer_menu->removeAction(peer_button->m_my_peers_item);
if (m_hub_peer_menu->actions().isEmpty()) {
m_hub_peer_menu->addAction(m_empty_action);
}
}
if (peer_button->m_network_peer_state == 0) {
my_peers_button_table.erase(my_peers_button_table.find(peer_id));
} else {
peer_button->peer_name = peer_button->m_network_peer->second;
peer_button->m_my_peers_item->setText(peer_button->peer_name);
if (m_local_peer_menu->actions().indexOf(peer_button->m_my_peers_item) ==
-1) {
m_local_peer_menu->addAction(peer_button->m_my_peers_item);
m_local_peer_menu->removeAction(m_empty_action);
}
}
return;
} else {
m_local_peer_menu->removeAction(peer_button->m_my_peers_item);
if (m_local_peer_menu->actions().empty()) {
m_local_peer_menu->addAction(m_empty_action);
}
if (m_hub_peer_menu->actions().indexOf(peer_button->m_my_peers_item) ==
-1) {
m_hub_peer_menu->addAction(peer_button->m_my_peers_item);
m_hub_peer_menu->removeAction(m_empty_action);
}
}
}
void TrayControlWindow::delete_peer_button_info(const QString &peer_id,
int type) {
if (my_peers_button_table.find(peer_id) == my_peers_button_table.end()) {
return;
}
my_peer_button *peer_button = my_peers_button_table[peer_id];
QString peer_backup_name,
peer_local_backup_name; // we need keep them to delete fingerprint from
// configs
switch (type) {
case 0:
if (peer_button->m_local_peer != nullptr) {
peer_backup_name = peer_button->peer_name;
peer_local_backup_name = peer_button->m_local_peer->name();
delete peer_button->m_local_peer;
peer_button->m_local_peer = nullptr;
}
peer_button->m_local_peer_state = 0;
break;
case 1:
if (peer_button->m_hub_peer != nullptr) {
delete peer_button->m_hub_peer;
peer_button->m_hub_peer = nullptr;
}
peer_button->m_hub_peer_state = 0;
break;
case 2:
if (peer_button->m_network_peer != nullptr) {
delete peer_button->m_network_peer;
peer_button->m_network_peer = nullptr;
}
peer_button->m_network_peer_state = 0;
break;
}
update_peer_icon(peer_id);
if (peer_backup_name != peer_id && type == 0) {
bool hub_peer_not_found = hub_peers_table.find(peer_id) == hub_peers_table.end();
if (hub_peer_not_found) {
qDebug() << "CLEAN PEER FINGERPRINT"
<< peer_backup_name
<< peer_local_backup_name
<< peer_id;
CSettingsManager::Instance().set_peer_finger(peer_local_backup_name, "");
}
}
}
void TrayControlWindow::my_peer_button_pressed_sl(
const QString &peer_id) {
QString peer_name = this->generate_peer_dlg(peer_id);
TrayControlWindow::show_dialog(
TrayControlWindow::last_generated_peer_dlg,
peer_name);
}
////////////////////////////////////////////////////////////////////////////
/* p2p status updater*/
void TrayControlWindow::update_p2p_status_sl(
P2PStatus_checker::P2P_STATUS status) {
p2p_current_status = status;
// need to put static icons
static QIcon p2p_running(":/hub/running.png");
static QIcon p2p_waiting(":/hub/waiting");
static QIcon p2p_fail(":/hub/stopped");
static QIcon p2p_loading(":/hub/loading");
qDebug() << "P2P updater got signal and try to update status";
if (P2PStatus_checker::Instance().get_status() ==
P2PStatus_checker::P2P_INSTALLING) {
m_p2p_menu->setTitle(tr("P2P is being installed"));
m_p2p_menu->setIcon(p2p_loading);
return;
} else if (P2PStatus_checker::Instance().get_status() ==
P2PStatus_checker::P2P_UNINSTALLING) {
m_p2p_menu->setTitle(tr("P2P is being uninstalled"));
m_p2p_menu->setIcon(p2p_loading);
return;
}
switch (status) {
case P2PStatus_checker::P2P_READY:
m_p2p_menu->setTitle(tr("P2P is not running"));
m_p2p_menu->setIcon(p2p_waiting);
m_p2p_menu->clear();
m_p2p_menu->addAction(m_act_p2p_start);
break;
case P2PStatus_checker::P2P_RUNNING:
m_p2p_menu->setTitle(tr("P2P is running"));
m_p2p_menu->setIcon(p2p_running);
m_p2p_menu->clear();
m_p2p_menu->addAction(m_act_p2p_stop);
break;
case P2PStatus_checker::P2P_FAIL:
if (p2p_current_status == P2PStatus_checker::P2P_LOADING)
CNotificationObserver::Error(
QObject::tr("P2P is not installed. You can't connect to the "
"environments without P2P."),
DlgNotification::N_INSTALL_P2P);
m_p2p_menu->setTitle(tr("Cannot launch P2P"));
m_p2p_menu->setIcon(p2p_fail);
m_p2p_menu->clear();
m_p2p_menu->addAction(m_act_p2p_install);
break;
case P2PStatus_checker::P2P_LOADING:
m_p2p_menu->setTitle(tr("P2P is loading..."));
m_p2p_menu->setIcon(p2p_loading);
break;
case P2PStatus_checker::P2P_INSTALLING:
m_p2p_menu->setTitle(tr("P2P is installing"));
m_p2p_menu->setIcon(p2p_loading);
break;
case P2PStatus_checker::P2P_UNINSTALLING:
m_p2p_menu->setTitle(tr("P2P is uninstalling"));
m_p2p_menu->setIcon(p2p_loading);
break;
default:
break;
}
}
//////////////////////////////////////
void TrayControlWindow::got_ss_console_readiness_sl(bool is_ready,
QString err) {
qDebug() << "Is console ready: " << is_ready << "Error: " << err;
if (!is_ready) {
CNotificationObserver::Info(tr(err.toStdString().c_str()),
DlgNotification::N_NO_ACTION);
return;
}
QString hub_url = "https://localhost:9999";
std::string rh_ip;
int ec = 0;
system_call_wrapper_error_t scwe = CSystemCallWrapper::get_rh_ip_via_libssh2(
CSettingsManager::Instance()
.rh_host(m_default_peer_id)
.toStdString()
.c_str(),
CSettingsManager::Instance().rh_port(m_default_peer_id),
CSettingsManager::Instance()
.rh_user(m_default_peer_id)
.toStdString()
.c_str(),
CSettingsManager::Instance()
.rh_pass(m_default_peer_id)
.toStdString()
.c_str(),
ec, rh_ip);
if (scwe == SCWE_SUCCESS && (ec == RLE_SUCCESS || ec == 0)) {
hub_url = QString("https://%1:8443").arg(rh_ip.c_str());
} else {
qCritical(
"Can't get RH IP address. Err : %s",
CLibsshController::run_libssh2_error_to_str((run_libssh2_error_t)ec));
CNotificationObserver::Info(
tr("Can't get RH IP address. Error : %1")
.arg(CLibsshController::run_libssh2_error_to_str(
(run_libssh2_error_t)ec)),
DlgNotification::N_NO_ACTION);
return;
}
CHubController::Instance().launch_browser(hub_url);
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::launch_ss() {
std::string rh_ip;
int ec = 0;
system_call_wrapper_error_t scwe = CSystemCallWrapper::get_rh_ip_via_libssh2(
CSettingsManager::Instance()
.rh_host(m_default_peer_id)
.toStdString()
.c_str(),
CSettingsManager::Instance().rh_port(m_default_peer_id),
CSettingsManager::Instance()
.rh_user(m_default_peer_id)
.toStdString()
.c_str(),
CSettingsManager::Instance()
.rh_pass(m_default_peer_id)
.toStdString()
.c_str(),
ec, rh_ip);
if (scwe == SCWE_SUCCESS && (ec == RLE_SUCCESS || ec == 0)) {
QString tmp =
QString("https://%1:8443/rest/v1/peer/ready").arg(rh_ip.c_str());
// after that got_ss_console_readiness_sl will be called
qInfo("launch_ss : %s", tmp.toStdString().c_str());
CRestWorker::Instance()->check_if_ss_console_is_ready(tmp);
} else {
qCritical(
"Cannot get RH IP address. Err : %s",
CLibsshController::run_libssh2_error_to_str((run_libssh2_error_t)ec));
CNotificationObserver::Info(
tr("Cannot get RH IP address. Error : %1")
.arg(CLibsshController::run_libssh2_error_to_str(
(run_libssh2_error_t)ec)),
DlgNotification::N_NO_ACTION);
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::show_dialog(QDialog *(*pf_dlg_create)(QWidget *),
const QString &title) {
std::map<QString, QDialog *>::iterator iter =
m_dct_active_dialogs.find(title);
qDebug() << "Popping up the dialog with title: " << title;
if (iter == m_dct_active_dialogs.end()) {
QDialog *dlg = pf_dlg_create(this);
dlg->setWindowTitle(title);
Qt::WindowFlags flags;
flags = Qt::Window;
flags |= Qt::WindowMinimizeButtonHint;
flags |= Qt::WindowMaximizeButtonHint;
flags |= Qt::WindowCloseButtonHint;
dlg->setWindowFlags(flags);
dlg->setWindowIcon(QIcon(":/hub/cc_icon_resized.png"));
m_dct_active_dialogs[dlg->windowTitle()] = dlg;
int src_x, src_y, dst_x, dst_y;
get_sys_tray_icon_coordinates_for_dialog(src_x, src_y, dst_x, dst_y,
dlg->width(), dlg->height(), true);
if (CSettingsManager::Instance().use_animations()) {
QPropertyAnimation *pos_anim = new QPropertyAnimation(dlg, "pos");
QPropertyAnimation *opa_anim =
new QPropertyAnimation(dlg, "windowOpacity");
pos_anim->setStartValue(QPoint(src_x, src_y));
pos_anim->setEndValue(QPoint(dst_x, dst_y));
pos_anim->setEasingCurve(QEasingCurve::OutBack);
pos_anim->setDuration(800);
opa_anim->setStartValue(0.0);
opa_anim->setEndValue(1.0);
opa_anim->setEasingCurve(QEasingCurve::Linear);
opa_anim->setDuration(800);
QParallelAnimationGroup *gr = new QParallelAnimationGroup;
gr->addAnimation(pos_anim);
gr->addAnimation(opa_anim);
dlg->move(src_x, src_y);
dlg->show();
gr->start();
connect(gr, &QParallelAnimationGroup::finished, [dlg]() {
dlg->activateWindow();
dlg->raise();
dlg->setFocus();
});
connect(gr, &QParallelAnimationGroup::finished, gr,
&QParallelAnimationGroup::deleteLater);
} else {
dlg->move(dst_x, dst_y);
dlg->show();
dlg->activateWindow();
dlg->raise();
dlg->setFocus();
}
connect(dlg, &QDialog::finished, this, &TrayControlWindow::dialog_closed);
} else {
if (iter->second != nullptr) {
iter->second->show();
iter->second->activateWindow();
iter->second->raise();
iter->second->setFocus();
}
}
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::dialog_closed(int unused) {
UNUSED_ARG(unused);
QDialog *dlg = qobject_cast<QDialog *>(sender());
if (dlg == nullptr) return;
QString title = dlg->windowTitle();
dlg->deleteLater();
auto iter = m_dct_active_dialogs.find(title);
if (iter == m_dct_active_dialogs.end()) return;
m_dct_active_dialogs.erase(iter);
}
////////////////////////////////////////////////////////////////////////////
QDialog *create_settings_dialog(QWidget *p) {
UNUSED_ARG(p);
return new DlgSettings();
}
void TrayControlWindow::show_settings_dialog() {
show_dialog(create_settings_dialog, tr("Settings"));
}
////////////////////////////////////////////////////////////////////////////
QDialog *create_create_peer_dialog(QWidget *p) {
UNUSED_ARG(p);
return new DlgCreatePeer();
}
void TrayControlWindow::show_create_dialog() {
QString vg_version;
//CSystemCallWrapper::oracle_virtualbox_version(vb_version);
CSystemCallWrapper::vagrant_version(vg_version);
QStringList bridged_ifs = CPeerController::Instance()->get_bridgedifs();
if (vg_version == "undefined") {
CNotificationObserver::Instance()->Error(
tr("Cannot create a peer without Vagrant installed in your system. To install, go to the menu > Components."), DlgNotification::N_ABOUT);
return;
}
if (bridged_ifs.size() == 0) {
VagrantProvider::PROVIDERS provider = VagrantProvider::Instance()->CurrentProvider();
switch (provider) {
case VagrantProvider::VIRTUALBOX:
CNotificationObserver::Error(tr("The Peer Manager is not yet ready. Please try again later."), DlgNotification::N_NO_ACTION);
return;
//case VagrantProvider::PARALLELS:
// CNotificationObserver::Error(tr("The Peer Manager is not yet ready for use. Please try again later."), DlgNotification::N_NO_ACTION);
// return;
default:
break;
}
}
show_dialog(create_create_peer_dialog, tr("Create Peer"));
}
////////////////////////////////////////////////////////////////////////////
QDialog *create_about_dialog(QWidget *p) {
UNUSED_ARG(p);
return new DlgAbout();
}
void TrayControlWindow::show_about() {
show_dialog(create_about_dialog, tr("Components"));
}
////////////////////////////////////////////////////////////////////////////
QDialog *create_ssh_key_generate_dialog(QWidget *p) {
UNUSED_ARG(p);
return new DlgGenerateSshKey();
}
void TrayControlWindow::ssh_key_generate_triggered() {
show_dialog(create_ssh_key_generate_dialog, tr("SSH Key Manager"));
}
QDialog *create_notifications_dialog(QWidget *p) {
UNUSED_ARG(p);
QDialog *dlg = new DlgNotifications();
dlg->setFixedWidth(dlg->width());
return dlg;
}
void TrayControlWindow::show_notifications_triggered() {
show_dialog(create_notifications_dialog, tr("Notification History"));
}
////////////////////////////////////////////////////////////////////////////
QDialog *TrayControlWindow::m_last_generated_env_dlg = nullptr;
QDialog *TrayControlWindow::last_generated_env_dlg(QWidget *p) {
UNUSED_ARG(p);
return m_last_generated_env_dlg;
}
void TrayControlWindow::generate_env_dlg(const CEnvironment *env) {
qDebug() << "Generating environment dialog... \n"
<< "Environment name: " << env->name();
DlgEnvironment *dlg_env = new DlgEnvironment();
dlg_env->addEnvironment(env);
connect(dlg_env, &DlgEnvironment::upload_to_container_sig, this,
&TrayControlWindow::upload_to_container_triggered);
connect(dlg_env, &DlgEnvironment::ssh_to_container_sig, this,
&TrayControlWindow::ssh_to_container_triggered);
connect(dlg_env, &DlgEnvironment::desktop_to_container_sig, this,
&TrayControlWindow::desktop_to_container_triggered);
m_last_generated_env_dlg = dlg_env;
}
////////////////////////////////////////////////////////////////////////////
QDialog *TrayControlWindow::m_last_generated_tranferfile_dlg = nullptr;
QDialog *TrayControlWindow::last_generated_transferfile_dlg(QWidget *p) {
UNUSED_ARG(p);
return m_last_generated_tranferfile_dlg;
}
#include "DlgTransferFile.h"
void TrayControlWindow::generate_transferfile_dlg() {
qDebug() << "Generating new transferfile dialog";
DlgTransferFile *dlg_transfer_file = new DlgTransferFile();
m_last_generated_tranferfile_dlg = dlg_transfer_file;
}
////////////////////////////////////////////////////////////////////////////
QDialog *TrayControlWindow::m_last_generated_peer_dlg = nullptr;
QDialog *TrayControlWindow::last_generated_peer_dlg(QWidget *p) {
UNUSED_ARG(p);
return m_last_generated_peer_dlg;
}
QString TrayControlWindow::generate_peer_dlg(const QString& peer_id) { // local_peer -> pair of fingerprint and local ip
DlgPeer *dlg_peer = new DlgPeer(nullptr, peer_id);
connect(dlg_peer, &DlgPeer::ssh_to_rh_sig, this,
&TrayControlWindow::ssh_to_rh_triggered);
connect(dlg_peer, &DlgPeer::peer_update_peeros, this,
&TrayControlWindow::peer_update_peeros_sl);
m_last_generated_peer_dlg = dlg_peer;
return dlg_peer->get_peer_name();
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::ssh_to_container_finished(const CEnvironment &env,
const CHubContainer &cont,
int result) {
UNUSED_ARG(env);
UNUSED_ARG(cont);
if (result != SDLE_SUCCESS) {
CNotificationObserver::Error(
tr("Cannot SSH to container. Err : %1")
.arg(CHubController::ssh_desktop_launch_err_to_str(result)),
DlgNotification::N_NO_ACTION);
}
}
////////////////////////////////////////////////////////////////////////////
bool TrayControlWindow::is_e2e_avaibale() {
QString version_e2e;
return CSystemCallWrapper::subutai_e2e_version(version_e2e) == SCWE_SUCCESS;
}
bool TrayControlWindow::is_p2p_avaibale() {
QString version_p2p;
return CSystemCallWrapper::p2p_version(version_p2p) == SCWE_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////
void TrayControlWindow::desktop_to_container_finished(const CEnvironment &env,
const CHubContainer &cont,
int result) {
UNUSED_ARG(env);
UNUSED_ARG(cont);
qDebug() << "Result " << result;
if (result != SDLE_SUCCESS) {
CNotificationObserver::Error(
tr("Cannot desktop to container. Err : %1")
.arg(CHubController::ssh_desktop_launch_err_to_str(result)),
DlgNotification::N_NO_ACTION);
}
}
////////////////////////////////////////////////////////////////////////////
| 37.964871 | 145 | 0.636697 | [
"geometry",
"vector"
] |
d882e63d25aaa9bb6a166f2129d9d0ee35386e7e | 2,308 | cpp | C++ | GUI/StudentManagementSystem/searchstudentbyhashmap.cpp | AppDevIn/StudentManagement | 38f88cd00473437fbffacd5d797f0a927c439544 | [
"MIT"
] | null | null | null | GUI/StudentManagementSystem/searchstudentbyhashmap.cpp | AppDevIn/StudentManagement | 38f88cd00473437fbffacd5d797f0a927c439544 | [
"MIT"
] | null | null | null | GUI/StudentManagementSystem/searchstudentbyhashmap.cpp | AppDevIn/StudentManagement | 38f88cd00473437fbffacd5d797f0a927c439544 | [
"MIT"
] | null | null | null | #include "searchstudentbyhashmap.h"
#include "ui_searchstudentbyhashmap.h"
#include "globals.h"
List dictWords;
SearchStudentByHashmap::SearchStudentByHashmap(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SearchStudentByHashmap)
{
ui->setupUi(this);
}
SearchStudentByHashmap::~SearchStudentByHashmap()
{
delete ui;
}
void SearchStudentByHashmap::on_lineEdit_textChanged(const QString &arg1)
{
dictWords = Constant::dictionary.getByPrefix(arg1.toUtf8().constData());
ui->tableWidget->clear();
ui->tableWidget->setRowCount(dictWords.getLength());
ui->tableWidget->model()->setHeaderData(0,Qt::Horizontal,QStringLiteral("Name"));
dictWords.begin();
for (int i = 0; i < dictWords.getLength(); i++){
Student s = dictWords.next();
if(s.id != ""){
QTableWidgetItem *name = new QTableWidgetItem;
name->setText(QString::fromStdString(s.name));
name->setFlags(name->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,0, name);
QTableWidgetItem *id = new QTableWidgetItem;
id->setText(QString::fromStdString(s.id));
id->setFlags(id->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,1, id);
QTableWidgetItem *email = new QTableWidgetItem;
email->setText(QString::fromStdString(s.email));
email->setFlags(email->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,2, email);
QTableWidgetItem *address = new QTableWidgetItem;
address->setText(QString::fromStdString(s.address));
address->setFlags(address->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,3, address);
ui->tableWidget->setColumnWidth(3,300);
QTableWidgetItem *gpa = new QTableWidgetItem;
gpa->setText(QString::number(s.gpa, 'f', 3));
gpa->setFlags(gpa->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,4, gpa);
QTableWidgetItem *tGroup = new QTableWidgetItem;
tGroup->setText(QString::fromStdString(s.tGroup));
tGroup->setFlags(tGroup->flags() ^ Qt::ItemIsEditable);
ui->tableWidget->setItem(i,5, tGroup);
}
}
}
| 27.807229 | 85 | 0.625217 | [
"model"
] |
d88663f8152c93186313d35a28dfe0820fb61f9a | 34,858 | cpp | C++ | MediaSession.cpp | Sukanya673/OCDM-Playready-Nexus-SVP | 2fc887a6f384cfeb240630a88ffedddf7d5053cf | [
"Apache-2.0"
] | null | null | null | MediaSession.cpp | Sukanya673/OCDM-Playready-Nexus-SVP | 2fc887a6f384cfeb240630a88ffedddf7d5053cf | [
"Apache-2.0"
] | null | null | null | MediaSession.cpp | Sukanya673/OCDM-Playready-Nexus-SVP | 2fc887a6f384cfeb240630a88ffedddf7d5053cf | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017-2018 Metrological
*
* 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 "MediaSession.h"
#include <assert.h>
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
#include <vector>
#include <sys/utsname.h>
#include <nexus_random_number.h>
#include <drmbuild_oem.h>
#include <drmnamespace.h>
#include <drmbytemanip.h>
#include <drmmanager.h>
#include <drmbase64.h>
#include <drmsoapxmlutility.h>
#include <oemcommon.h>
#include <drmconstants.h>
#include <drmsecuretime.h>
#include <drmsecuretimeconstants.h>
#include <drmrevocation.h>
#include <drmxmlparser.h>
#include <drmmathsafe.h>
#include <prdy_http.h>
#include <drm_data.h>
using SafeCriticalSection = WPEFramework::Core::SafeSyncType<WPEFramework::Core::CriticalSection>;
extern WPEFramework::Core::CriticalSection drmAppContextMutex_;
#define NYI_KEYSYSTEM "keysystem-placeholder"
// ~100 KB to start * 64 (2^6) ~= 6.4 MB, don't allocate more than ~6.4 MB
#define DRM_MAXIMUM_APPCONTEXT_OPAQUE_BUFFER_SIZE ( 64 * MINIMUM_APPCONTEXT_OPAQUE_BUFFER_SIZE )
OutputProtection::OutputProtection()
: compressedDigitalVideoLevel(0)
, uncompressedDigitalVideoLevel(0)
, analogVideoLevel(0)
, compressedDigitalAudioLevel(0)
, uncompressedDigitalAudioLevel(0)
, maxResDecodeWidth(0)
, maxResDecodeHeight(0)
{}
void OutputProtection::setOutputLevels(const DRM_MINIMUM_OUTPUT_PROTECTION_LEVELS& opLevels)
{
compressedDigitalVideoLevel = opLevels.wCompressedDigitalVideo;
uncompressedDigitalVideoLevel = opLevels.wUncompressedDigitalVideo;
analogVideoLevel = opLevels.wAnalogVideo;
compressedDigitalAudioLevel = opLevels.wCompressedDigitalAudio;
uncompressedDigitalAudioLevel = opLevels.wUncompressedDigitalAudio;
}
void OutputProtection::setMaxResDecode(uint32_t width, uint32_t height)
{
maxResDecodeWidth = width;
maxResDecodeHeight = height;
}
namespace CDMi {
MediaKeySession::DecryptContext::DecryptContext(IMediaKeySessionCallback* mcallback)
: callback(mcallback)
{
ZEROMEM(&drmDecryptContext, sizeof(DRM_DECRYPT_CONTEXT));
}
const DRM_CONST_STRING *g_rgpdstrRights[1] = {&g_dstrWMDRM_RIGHT_PLAYBACK};
// Parse out the first PlayReady initialization header found in the concatenated
// block of headers in _initData_.
// If a PlayReady header is found, this function returns true and the header
// contents are stored in _output_.
// Otherwise, returns false and _output_ is not touched.
bool parsePlayreadyInitializationData(const std::string& initData, std::string* output)
{
BufferReader input(reinterpret_cast<const uint8_t*>(initData.data()), initData.length());
static const uint8_t playreadySystemId[] = {
0x9A, 0x04, 0xF0, 0x79, 0x98, 0x40, 0x42, 0x86,
0xAB, 0x92, 0xE6, 0x5B, 0xE0, 0x88, 0x5F, 0x95,
};
// one PSSH box consists of:
// 4 byte size of the atom, inclusive. (0 means the rest of the buffer.)
// 4 byte atom type, "pssh".
// (optional, if size == 1) 8 byte size of the atom, inclusive.
// 1 byte version, value 0 or 1. (skip if larger.)
// 3 byte flags, value 0. (ignored.)
// 16 byte system id.
// (optional, if version == 1) 4 byte key ID count. (K)
// (optional, if version == 1) K * 16 byte key ID.
// 4 byte size of PSSH data, exclusive. (N)
// N byte PSSH data.
while (!input.IsEOF()) {
size_t startPosition = input.pos();
// The atom size, used for skipping.
uint64_t atomSize;
if (!input.Read4Into8(&atomSize)) {
return false;
}
std::vector<uint8_t> atomType;
if (!input.ReadVec(&atomType, 4)) {
return false;
}
if (atomSize == 1) {
if (!input.Read8(&atomSize)) {
return false;
}
} else if (atomSize == 0) {
atomSize = input.size() - startPosition;
}
if (memcmp(&atomType[0], "pssh", 4)) {
if (!input.SkipBytes(atomSize - (input.pos() - startPosition))) {
return false;
}
continue;
}
uint8_t version;
if (!input.Read1(&version)) {
return false;
}
if (version > 1) {
// unrecognized version - skip.
if (!input.SkipBytes(atomSize - (input.pos() - startPosition))) {
return false;
}
continue;
}
// flags
if (!input.SkipBytes(3)) {
return false;
}
// system id
std::vector<uint8_t> systemId;
if (!input.ReadVec(&systemId, sizeof(playreadySystemId))) {
return false;
}
if (memcmp(&systemId[0], playreadySystemId, sizeof(playreadySystemId))) {
// skip non-Playready PSSH boxes.
if (!input.SkipBytes(atomSize - (input.pos() - startPosition))) {
return false;
}
continue;
}
if (version == 1) {
// v1 has additional fields for key IDs. We can skip them.
uint32_t numKeyIds;
if (!input.Read4(&numKeyIds)) {
return false;
}
if (!input.SkipBytes(numKeyIds * 16)) {
return false;
}
}
// size of PSSH data
uint32_t dataLength;
if (!input.Read4(&dataLength)) {
return false;
}
output->clear();
if (!input.ReadString(output, dataLength)) {
return false;
}
return true;
}
// we did not find a matching record
return false;
}
bool MediaKeySession::LoadRevocationList(const char *revListFile)
{
DRM_RESULT dr = DRM_SUCCESS;
FILE * fRev;
uint8_t * revBuf = nullptr;
size_t fileSize = 0;
uint32_t currSize = 0;
assert(revListFile != nullptr);
fRev = fopen(revListFile, "rb");
if( fRev == nullptr)
{
return true;
}
/* get the size of the file */
fseek(fRev, 0, SEEK_END);
fileSize = ftell(fRev);
fseek(fRev, 0, SEEK_SET);
revBuf = (uint8_t *)BKNI_Malloc(fileSize);
if( revBuf == nullptr)
{
goto ErrorExit;
}
BKNI_Memset(revBuf, 0x00, fileSize);
for(;;) {
uint8_t buf[512];
int rc = fread(buf, 1, sizeof(buf), fRev);
if(rc<=0) {
break;
}
BKNI_Memcpy(revBuf+currSize, buf, rc);
currSize += rc;
}
ChkDR( Drm_Revocation_StorePackage(
m_poAppContext,
( DRM_CHAR * )revBuf,
fileSize ) );
if( revBuf != nullptr)
BKNI_Free(revBuf);
return true;
ErrorExit:
if( revBuf != nullptr)
BKNI_Free(revBuf);
return false;
}
// PlayReady license policy callback which should be
// customized for platform/environment that hosts the CDM.
// It is currently implemented as a place holder that
// does nothing.
DRM_RESULT MediaKeySession::PolicyCallback(
const DRM_VOID *f_pvPolicyCallbackData,
DRM_POLICY_CALLBACK_TYPE f_dwCallbackType,
const DRM_KID *f_pKID,
const DRM_LID *f_pLID,
const DRM_VOID *f_pv)
{
/*!+!hla fix this, implement for something. */
DRM_RESULT dr = DRM_SUCCESS;
const DRM_PLAY_OPL_EX2 *oplPlay = NULL;
BSTD_UNUSED(f_pKID);
BSTD_UNUSED(f_pLID);
BSTD_UNUSED(f_pv);
switch( f_dwCallbackType )
{
case DRM_PLAY_OPL_CALLBACK:
printf(" Got DRM_PLAY_OPL_CALLBACK from Bind:\r\n");
ChkArg( f_pvPolicyCallbackData != NULL );
oplPlay = (const DRM_PLAY_OPL_EX2*)f_pvPolicyCallbackData;
printf(" minOPL:\r\n");
printf(" wCompressedDigitalVideo = %d\r\n", oplPlay->minOPL.wCompressedDigitalVideo);
printf(" wUncompressedDigitalVideo = %d\r\n", oplPlay->minOPL.wUncompressedDigitalVideo);
printf(" wAnalogVideo = %d\r\n", oplPlay->minOPL.wAnalogVideo);
printf(" wCompressedDigitalAudio = %d\r\n", oplPlay->minOPL.wCompressedDigitalAudio);
printf(" wUncompressedDigitalAudio = %d\r\n", oplPlay->minOPL.wUncompressedDigitalAudio);
printf("\r\n");
printf(" oplIdReserved:\r\n");
// ChkDR( DRMTOOLS_PrintOPLOutputIDs( &oplPlay->oplIdReserved ) );
printf(" vopi:\r\n");
//ChkDR( DRMTOOLS_PrintVideoOutputProtectionIDs( &oplPlay->vopi ) );
printf(" dvopi:\r\n");
//ChkDR( handleDigitalVideoOutputProtectionIDs( &oplPlay->dvopi ) );
break;
case DRM_EXTENDED_RESTRICTION_QUERY_CALLBACK:
{
const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT *pExtCallback = (const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT*)f_pvPolicyCallbackData;
DRM_DWORD i = 0;
printf(" Got DRM_EXTENDED_RESTRICTION_QUERY_CALLBACK from Bind:\r\n");
printf(" wRightID = %d\r\n", pExtCallback->wRightID);
printf(" wType = %d\r\n", pExtCallback->pRestriction->wType);
printf(" wFlags = %x\r\n", pExtCallback->pRestriction->wFlags);
printf(" Data = ");
for( i = pExtCallback->pRestriction->ibData; (i - pExtCallback->pRestriction->ibData) < pExtCallback->pRestriction->cbData; i++ )
{
printf("0x%.2X ", pExtCallback->pRestriction->pbBuffer[ i ] );
}
printf("\r\n\r\n");
/* Report that restriction was not understood */
dr = DRM_E_EXTENDED_RESTRICTION_NOT_UNDERSTOOD;
}
break;
case DRM_EXTENDED_RESTRICTION_CONDITION_CALLBACK:
{
const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT *pExtCallback = (const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT*)f_pvPolicyCallbackData;
DRM_DWORD i = 0;
printf(" Got DRM_EXTENDED_RESTRICTION_CONDITION_CALLBACK from Bind:\r\n");
printf(" wRightID = %d\r\n", pExtCallback->wRightID);
printf(" wType = %d\r\n", pExtCallback->pRestriction->wType);
printf(" wFlags = %x\r\n", pExtCallback->pRestriction->wFlags);
printf(" Data = ");
for( i = pExtCallback->pRestriction->ibData; (i - pExtCallback->pRestriction->ibData) < pExtCallback->pRestriction->cbData; i++ )
{
printf("0x%.2X ", pExtCallback->pRestriction->pbBuffer[ i ] );
}
printf("\r\n\r\n");
}
break;
case DRM_EXTENDED_RESTRICTION_ACTION_CALLBACK:
{
const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT *pExtCallback = (const DRM_EXTENDED_RESTRICTION_CALLBACK_STRUCT*)f_pvPolicyCallbackData;
DRM_DWORD i = 0;
printf(" Got DRM_EXTENDED_RESTRICTION_ACTION_CALLBACK from Bind:\r\n");
printf(" wRightID = %d\r\n", pExtCallback->wRightID);
printf(" wType = %d\r\n", pExtCallback->pRestriction->wType);
printf(" wFlags = %x\r\n", pExtCallback->pRestriction->wFlags);
printf(" Data = ");
for( i = pExtCallback->pRestriction->ibData; (i - pExtCallback->pRestriction->ibData) < pExtCallback->pRestriction->cbData; i++ )
{
printf("0x%.2X ", pExtCallback->pRestriction->pbBuffer[ i ] );
}
printf("\r\n\r\n");
}
break;
default:
printf(" Callback from Bind with unknown callback type of %d.\r\n", f_dwCallbackType);
/* Report that this callback type is not implemented */
ChkDR( DRM_E_NOTIMPL );
}
ErrorExit:
return dr;
}
MediaKeySession::MediaKeySession(
const uint8_t *f_pbInitData, uint32_t f_cbInitData,
const uint8_t *f_pbCDMData, uint32_t f_cbCDMData,
DRM_VOID *f_pOEMContext, DRM_APP_CONTEXT * appContext)
: m_poAppContext(appContext)
, m_oDecryptContext(nullptr)
, m_pbOpaqueBuffer(nullptr)
, m_cbOpaqueBuffer(0)
, m_pbRevocationBuffer(nullptr)
, m_customData(reinterpret_cast<const char*>(f_pbCDMData), f_cbCDMData)
, m_piCallback(nullptr)
, m_eKeyState(KEY_CLOSED)
, m_fCommit(false)
, m_pOEMContext(f_pOEMContext)
, mDrmHeader()
, m_SessionId()
, mBatchId()
, m_decryptInited(false)
, pNexusMemory(nullptr)
, mNexusMemorySize(512 * 1024) {
LOGGER(LINFO_, "Contruction MediaKeySession, Build: %s", __TIMESTAMP__ );
m_oDecryptContext = new DRM_DECRYPT_CONTEXT;
memset(m_oDecryptContext, 0, sizeof(DRM_DECRYPT_CONTEXT));
DRM_RESULT dr = DRM_SUCCESS;
DRM_ID oSessionID;
DRM_DWORD cchEncodedSessionID = sizeof(m_rgchSessionID);
std::string playreadyInitData;
// The current state MUST be KEY_CLOSED otherwise error out.
ChkBOOL(m_eKeyState == KEY_CLOSED, DRM_E_INVALIDARG);
ChkArg((f_pbInitData == nullptr) == (f_cbInitData == 0));
if( NEXUS_Memory_Allocate(mNexusMemorySize, nullptr, &pNexusMemory) != 0 ) {
LOGGER(LERROR_, "NexusMemory, could not allocate memory %d", mNexusMemorySize);
goto ErrorExit;
}
if (f_pbInitData != nullptr) {
std::string initData(reinterpret_cast<const char *>(f_pbInitData), f_cbInitData);
if (!parsePlayreadyInitializationData(initData, &playreadyInitData)) {
playreadyInitData = initData;
}
// TODO: can we do this nicer?
mDrmHeader.resize(f_cbInitData);
memcpy(&mDrmHeader[0], f_pbInitData, f_cbInitData);
ChkDR(Drm_Content_SetProperty(m_poAppContext,
DRM_CSP_AUTODETECT_HEADER,
reinterpret_cast<const uint8_t *>(playreadyInitData.data()),
playreadyInitData.size()));
// Generate a random media session ID.
ChkDR(Oem_Random_GetBytes(m_poAppContext, (DRM_BYTE *)&oSessionID, sizeof(oSessionID)));
ZEROMEM(m_rgchSessionID, sizeof(m_rgchSessionID));
// Store the generated media session ID in base64 encoded form.
ChkDR(DRM_B64_EncodeA((DRM_BYTE *)&oSessionID,
sizeof(oSessionID),
m_rgchSessionID,
&cchEncodedSessionID,
0));
LOGGER(LINFO_, "Session ID generated: %s", m_rgchSessionID);
m_eKeyState = KEY_INIT;
}
LOGGER(LINFO_, "Session Initialized");
ErrorExit:
if (DRM_FAILED(dr))
{
m_eKeyState = KEY_ERROR;
LOGGER(LERROR_, "Drm_Content_SetProperty() failed, exiting");
}
}
MediaKeySession::~MediaKeySession(void)
{
Close();
LOGGER(LINFO_, "PlayReady Session Destructed");
}
const char *MediaKeySession::GetSessionId(void) const
{
return m_rgchSessionID;
}
const char *MediaKeySession::GetKeySystem(void) const
{
return NYI_KEYSYSTEM; // FIXME : replace with keysystem and test.
}
void MediaKeySession::Run(const IMediaKeySessionCallback *f_piMediaKeySessionCallback)
{
LOGGER(LINFO_, "Set session callback to %p", f_piMediaKeySessionCallback);
if (f_piMediaKeySessionCallback) {
m_piCallback = const_cast<IMediaKeySessionCallback *>(f_piMediaKeySessionCallback);
if (mDrmHeader.size() != 0) {
playreadyGenerateKeyRequest();
}
} else {
m_piCallback = nullptr;
}
}
bool MediaKeySession::playreadyGenerateKeyRequest() {
DRM_RESULT dr = DRM_SUCCESS;
DRM_BYTE *pbChallenge = nullptr;
DRM_DWORD cbChallenge = 0;
DRM_CHAR *pchSilentURL = nullptr;
DRM_DWORD cchSilentURL = 0;
if(m_eKeyState == KEY_INIT){
// Try to figure out the size of the license acquisition
// challenge to be returned.
dr = Drm_LicenseAcq_GenerateChallenge(m_poAppContext,
g_rgpdstrRights,
DRM_NO_OF(g_rgpdstrRights),
nullptr,
!m_customData.empty() ? m_customData.c_str() : nullptr,
m_customData.size(),
nullptr,
&cchSilentURL,
nullptr,
nullptr,
nullptr,
&cbChallenge,
nullptr);
if (dr == DRM_E_BUFFERTOOSMALL)
{
if (cchSilentURL > 0)
{
ChkMem(pchSilentURL = (DRM_CHAR *)Oem_MemAlloc(cchSilentURL + 1));
ZEROMEM(pchSilentURL, cchSilentURL + 1);
}
// Allocate buffer that is sufficient to store the license acquisition
// challenge.
if (cbChallenge > 0)
{
ChkMem(pbChallenge = (DRM_BYTE *)Oem_MemAlloc(cbChallenge + 1));
ZEROMEM(pbChallenge, cbChallenge + 1);
}
dr = DRM_SUCCESS;
}
else
{
ChkDR(dr);
}
// Supply a buffer to receive the license acquisition challenge.
ChkDR(Drm_LicenseAcq_GenerateChallenge(m_poAppContext,
g_rgpdstrRights,
DRM_NO_OF(g_rgpdstrRights),
nullptr,
!m_customData.empty() ? m_customData.c_str() : nullptr,
m_customData.size(),
pchSilentURL,
&cchSilentURL,
nullptr,
nullptr,
pbChallenge,
&cbChallenge,
nullptr));
pbChallenge[cbChallenge] = 0;
m_eKeyState = KEY_PENDING;
LOGGER(LINFO_, "Generated license acquisition challenge.");
// Everything is OK and trigger a callback to let the caller
// handle the key message.
m_piCallback->OnKeyMessage((const uint8_t *) pbChallenge, cbChallenge, (char *) pchSilentURL);
}
ErrorExit:
if (DRM_FAILED(dr))
{
if (m_piCallback != nullptr)
{
m_piCallback->OnError(0, CDMi_S_FALSE, "KeyError");
}
m_eKeyState = KEY_ERROR;
LOGGER(LERROR_, "Failure during license acquisition challenge. (error: 0x%08X)",(unsigned int)dr);
}
SAFE_OEM_FREE(pbChallenge);
SAFE_OEM_FREE(pchSilentURL);
return (dr == DRM_SUCCESS);
}
CDMi_RESULT MediaKeySession::Load(void)
{
return CDMi_S_FALSE;
}
void MediaKeySession::Update(const uint8_t *f_pbKeyMessageResponse, uint32_t f_cbKeyMessageResponse)
{
DRM_RESULT dr = DRM_SUCCESS;
DRM_LICENSE_RESPONSE oLicenseResponse;
ChkArg(f_pbKeyMessageResponse != nullptr && f_cbKeyMessageResponse > 0);
BKNI_Memset(&oLicenseResponse, 0, sizeof(oLicenseResponse));
LOGGER(LINFO_, "Processing license acquisition response...");
ChkDR(Drm_LicenseAcq_ProcessResponse(m_poAppContext,
DRM_PROCESS_LIC_RESPONSE_SIGNATURE_NOT_REQUIRED,
const_cast<DRM_BYTE *>(f_pbKeyMessageResponse),
f_cbKeyMessageResponse,
&oLicenseResponse));
LOGGER(LINFO_, "Binding License...");
while ((dr = Drm_Reader_Bind(m_poAppContext,
g_rgpdstrRights,
DRM_NO_OF(g_rgpdstrRights),
PolicyCallback,
nullptr,
m_oDecryptContext)) == DRM_E_BUFFERTOOSMALL) {
uint8_t *pbNewOpaqueBuffer = nullptr;
m_cbOpaqueBuffer *= 2;
ChkMem( pbNewOpaqueBuffer = ( uint8_t* )Oem_MemAlloc(m_cbOpaqueBuffer) );
if( m_cbOpaqueBuffer > DRM_MAXIMUM_APPCONTEXT_OPAQUE_BUFFER_SIZE ) {
ChkDR( DRM_E_OUTOFMEMORY );
}
ChkDR( Drm_ResizeOpaqueBuffer(
m_poAppContext,
pbNewOpaqueBuffer,
m_cbOpaqueBuffer ) );
/*
Free the old buffer and then transfer the new buffer ownership
Free must happen after Drm_ResizeOpaqueBuffer because that
function assumes the existing buffer is still valid
*/
SAFE_OEM_FREE(m_pbOpaqueBuffer);
m_pbOpaqueBuffer = pbNewOpaqueBuffer;
}
ChkDR(dr);
ChkDR( Drm_Reader_Commit( m_poAppContext, nullptr, nullptr ) );
m_eKeyState = KEY_READY;
LOGGER(LINFO_, "Key processed, now ready for content decryption");
if((m_piCallback != nullptr) && (m_eKeyState == KEY_READY) && (DRM_SUCCEEDED(dr))){
for (uint8_t i = 0; i < oLicenseResponse.m_cAcks; ++i) {
if (DRM_SUCCEEDED(oLicenseResponse.m_rgoAcks[i].m_dwResult)) {
// Make MS endianness to Cenc endianness.
ToggleKeyIdFormat(DRM_ID_SIZE, oLicenseResponse.m_rgoAcks[i].m_oKID.rgb);
m_piCallback->OnKeyStatusUpdate("KeyUsable", oLicenseResponse.m_rgoAcks[i].m_oKID.rgb, DRM_ID_SIZE);
}
}
m_piCallback->OnKeyStatusesUpdated();
}
ErrorExit:
if (DRM_FAILED(dr))
{
if (dr == DRM_E_LICENSE_NOT_FOUND) {
/* could not find a license for the KID */
LOGGER(LERROR_, "No licenses found in the license store. Please request one from the license server.");
}
else if(dr == DRM_E_LICENSE_EXPIRED) {
/* License is expired */
LOGGER(LERROR_, "License expired. Please request one from the license server.");
}
else if( dr == DRM_E_RIV_TOO_SMALL ||
dr == DRM_E_LICEVAL_REQUIRED_REVOCATION_LIST_NOT_AVAILABLE )
{
/* Revocation Package must be update */
LOGGER(LERROR_, "Revocation Package must be update. (error: 0x%08X)",(unsigned int)dr);
}
else {
LOGGER(LERROR_, "Unexpected failure during bind. (error: 0x%08X)",(unsigned int)dr);
}
m_eKeyState = KEY_ERROR;
if (m_piCallback) {
m_piCallback->OnError(0, CDMi_S_FALSE, "KeyError");
m_piCallback->OnKeyStatusesUpdated();
}
}
return;
}
CDMi_RESULT MediaKeySession::Remove(void)
{
return CDMi_S_FALSE;
}
CDMi_RESULT MediaKeySession::Close(void)
{
m_eKeyState = KEY_CLOSED;
CleanLicenseStore(m_poAppContext);
CleanDecryptContexts();
if (pNexusMemory) {
NEXUS_Memory_Free(pNexusMemory);
pNexusMemory = nullptr;
mNexusMemorySize = 0;
}
m_piCallback = nullptr;
m_fCommit = FALSE;
m_decryptInited = false;
return CDMi_SUCCESS;
}
CDMi_RESULT MediaKeySession::Decrypt(
const uint8_t *f_pbSessionKey,
uint32_t f_cbSessionKey,
const uint32_t *f_pdwSubSampleMapping,
uint32_t f_cdwSubSampleMapping,
const uint8_t *f_pbIV,
uint32_t f_cbIV,
const uint8_t *payloadData,
uint32_t payloadDataSize,
uint32_t *f_pcbOpaqueClearContent,
uint8_t **f_ppbOpaqueClearContent,
const uint8_t /* keyIdLength */,
const uint8_t* /* keyId */,
bool initWithLast15)
{
SafeCriticalSection systemLock(drmAppContextMutex_);
if (!m_oDecryptContext) {
LOGGER(LERROR_, "Error: no decrypt context (yet?)\n");
return CDMi_S_FALSE;
}
DRM_RESULT dr = DRM_SUCCESS;
CDMi_RESULT cr = CDMi_S_FALSE;
DRM_AES_COUNTER_MODE_CONTEXT oAESContext = {0, 0, 0};
void *pOpaqueData = nullptr;
NEXUS_MemoryBlockHandle pNexusMemoryBlock = nullptr;
NEXUS_MemoryBlockTokenHandle token = nullptr;
static NEXUS_HeapHandle secureHeap = NEXUS_Heap_Lookup(NEXUS_HeapLookupType_eCompressedRegion);
{
ChkArg(payloadData != nullptr && payloadDataSize > 0);
}
if (!initWithLast15) {
if( f_pcbOpaqueClearContent == nullptr || f_ppbOpaqueClearContent == nullptr )
{
dr = DRM_E_INVALIDARG;
goto ErrorExit;
}
{
// The current state MUST be KEY_READY otherwise error out.
ChkBOOL(m_eKeyState == KEY_READY, DRM_E_INVALIDARG);
ChkArg(f_pbIV != nullptr && f_cbIV == sizeof(DRM_UINT64));
}
}
// TODO: can be done in another way (now abusing "initWithLast15" variable)
if (initWithLast15) {
// Netflix case
memcpy(&oAESContext, f_pbIV, sizeof(oAESContext));
} else {
// Regular case
// FIXME: IV bytes need to be swapped ???
// TODO: is this for-loop the same as "NETWORKBYTES_TO_QWORD"?
unsigned char * ivDataNonConst = const_cast<unsigned char *>(f_pbIV); // TODO: this is ugly
for (uint32_t i = 0; i < f_cbIV / 2; i++) {
unsigned char temp = ivDataNonConst[i];
ivDataNonConst[i] = ivDataNonConst[f_cbIV - i - 1];
ivDataNonConst[f_cbIV - i - 1] = temp;
}
memcpy(&oAESContext.qwInitializationVector, f_pbIV, f_cbIV);
}
// Reallocate input memory if needed.
if (payloadDataSize > mNexusMemorySize) {
void *newBuffer = nullptr;
int rc = NEXUS_Memory_Allocate(payloadDataSize, nullptr, &newBuffer);
if( rc != 0 ) {
LOGGER(LERROR_, "NexusMemory to small, use larger buffer. could not allocate memory %d", payloadDataSize);
goto ErrorExit;
}
NEXUS_Memory_Free(pNexusMemory);
pNexusMemory = newBuffer;
mNexusMemorySize = payloadDataSize;
LOGGER(LINFO_, "NexusMemory to small, use larger buffer. %d", payloadDataSize);
}
pNexusMemoryBlock = NEXUS_MemoryBlock_Allocate(secureHeap, payloadDataSize, 0, nullptr);
if (!pNexusMemoryBlock) {
LOGGER(LERROR_, "NexusBlockMemory could not allocate %d", payloadDataSize);
goto ErrorExit;
}
NEXUS_Error rc;
rc = NEXUS_MemoryBlock_Lock(pNexusMemoryBlock, &pOpaqueData);
if (rc) {
LOGGER(LERROR_, "NexusBlockMemory is not usable");
NEXUS_MemoryBlock_Free(pNexusMemoryBlock);
pOpaqueData = nullptr;
goto ErrorExit;
}
token = NEXUS_MemoryBlock_CreateToken(pNexusMemoryBlock);
if (!token) {
LOGGER(LERROR_, "Could not create a token for another process");
goto ErrorExit;
}
// Copy provided payload to Input of Decryption.
::memcpy(pNexusMemory, payloadData, payloadDataSize);
uint32_t subsamples[2];
subsamples[0] = 0;
subsamples[1] = payloadDataSize;
ChkDR(Drm_Reader_DecryptOpaque(
m_oDecryptContext,
2,
subsamples,
oAESContext.qwInitializationVector,
payloadDataSize,
(DRM_BYTE*)pNexusMemory,
(DRM_DWORD*)&payloadDataSize,
(DRM_BYTE**)&pOpaqueData));
cr = CDMi_SUCCESS;
// Return clear content.
*f_pcbOpaqueClearContent = sizeof(token);
*f_ppbOpaqueClearContent = reinterpret_cast<uint8_t*>(&token);
NEXUS_MemoryBlock_Unlock(pNexusMemoryBlock);
NEXUS_MemoryBlock_Free(pNexusMemoryBlock);
ErrorExit:
if (DRM_FAILED(dr))
{
if (pOpaqueData) {
if (pNexusMemoryBlock) {
NEXUS_MemoryBlock_Unlock(pNexusMemoryBlock);
NEXUS_MemoryBlock_Free(pNexusMemoryBlock);
}
pOpaqueData = nullptr;
}
LOGGER(LERROR_, "Decryption failed (error: 0x%08X)", static_cast<uint32_t>(dr));
}
return cr;
}
CDMi_RESULT MediaKeySession::ReleaseClearContent(
const uint8_t *f_pbSessionKey,
uint32_t f_cbSessionKey,
const uint32_t f_cbClearContentOpaque,
uint8_t *f_pbClearContentOpaque )
{
return CDMi_SUCCESS;
}
#define MAX_TIME_CHALLENGE_RESPONSE_LENGTH (1024*64)
#define MAX_URL_LENGTH (512)
int MediaKeySession::InitSecureClock(DRM_APP_CONTEXT *pDrmAppCtx)
{
int rc = 0;
DRM_DWORD cbChallenge = 0;
DRM_BYTE *pbChallenge = nullptr;
DRM_BYTE *pbResponse = nullptr;
char *pTimeChallengeURL = nullptr;
char secureTimeUrlStr[MAX_URL_LENGTH];
bool redirect = true;
int32_t petRC=0;
uint32_t petRespCode = 0;
uint32_t startOffset;
uint32_t length;
uint32_t post_ret;
NEXUS_MemoryAllocationSettings allocSettings;
DRM_RESULT drResponse = DRM_SUCCESS;
DRM_RESULT dr = DRM_SUCCESS;
dr = Drm_SecureTime_GenerateChallenge( pDrmAppCtx,
&cbChallenge,
&pbChallenge );
ChkDR(dr);
NEXUS_Memory_GetDefaultAllocationSettings(&allocSettings);
rc = NEXUS_Memory_Allocate(MAX_URL_LENGTH, &allocSettings, (void **)(&pTimeChallengeURL ));
if(rc != NEXUS_SUCCESS)
{
LOGGER(LERROR_, " NEXUS_Memory_Allocate failed for time challenge response buffer, rc = %d", rc);
goto ErrorExit;
}
/* send the petition request to Microsoft with HTTP GET */
petRC = PRDY_HTTP_Client_GetForwardLinkUrl((char*)g_dstrHttpSecureTimeServerUrl.pszString,
&petRespCode,
(char**)&pTimeChallengeURL);
if( petRC != 0)
{
LOGGER(LERROR_, " Secure Time forward link petition request failed, rc = %d", petRC);
rc = petRC;
goto ErrorExit;
}
do
{
redirect = false;
/* we need to check if the Pettion responded with redirection */
if( petRespCode == 200)
{
redirect = false;
}
else if( petRespCode == 302 || petRespCode == 301)
{
redirect = true;
memset(secureTimeUrlStr, 0, MAX_URL_LENGTH);
strcpy(secureTimeUrlStr, pTimeChallengeURL);
memset(pTimeChallengeURL, 0, MAX_URL_LENGTH);
petRC = PRDY_HTTP_Client_GetSecureTimeUrl(secureTimeUrlStr,
&petRespCode,
(char**)&pTimeChallengeURL);
if( petRC != 0)
{
LOGGER(LERROR_, " Secure Time URL petition request failed, rc = %d", petRC);
rc = petRC;
goto ErrorExit;
}
}
else
{
LOGGER(LERROR_, "Secure Clock Petition responded with unsupported result, rc = %d, can't get the time challenge URL", petRespCode);
rc = -1;
goto ErrorExit;
}
} while (redirect);
NEXUS_Memory_GetDefaultAllocationSettings(&allocSettings);
rc = NEXUS_Memory_Allocate(MAX_TIME_CHALLENGE_RESPONSE_LENGTH, &allocSettings, (void **)(&pbResponse ));
if(rc != NEXUS_SUCCESS)
{
LOGGER(LERROR_, "NEXUS_Memory_Allocate failed for time challenge response buffer, rc = %d", rc);
goto ErrorExit;
}
BKNI_Memset(pbResponse, 0, MAX_TIME_CHALLENGE_RESPONSE_LENGTH);
post_ret = PRDY_HTTP_Client_SecureTimeChallengePost(pTimeChallengeURL,
(char *)pbChallenge,
1,
150,
(unsigned char**)&(pbResponse),
&startOffset,
&length);
if( post_ret != 0)
{
LOGGER(LERROR_, "Secure Time Challenge request failed, rc = %d", post_ret);
rc = post_ret;
goto ErrorExit;
}
drResponse = Drm_SecureTime_ProcessResponse(
pDrmAppCtx,
length,
(uint8_t *) pbResponse);
if ( drResponse != DRM_SUCCESS )
{
LOGGER(LERROR_, "Drm_SecureTime_ProcessResponse failed, drResponse = %x", (unsigned int)drResponse);
dr = drResponse;
ChkDR( drResponse);
}
LOGGER(LINFO_, "Initialized Playready Secure Clock success.");
/* NOW testing the system time */
ErrorExit:
SAFE_OEM_FREE(pbChallenge);
SAFE_OEM_FREE(pTimeChallengeURL);
SAFE_OEM_FREE(pbResponse);
return rc;
}
void MediaKeySession::CleanLicenseStore(DRM_APP_CONTEXT *pDrmAppCtx){
if (m_poAppContext != nullptr) {
LOGGER(LINFO_, "Licenses cleanup");
// Delete all the licenses added by this session
DRM_RESULT dr = Drm_StoreMgmt_DeleteInMemoryLicenses(pDrmAppCtx, &mBatchId);
// Since there are multiple licenses in a batch, we might have already cleared
// them all. Ignore DRM_E_NOMORE returned from Drm_StoreMgmt_DeleteInMemoryLicenses.
if (DRM_FAILED(dr) && (dr != DRM_E_NOMORE)) {
LOGGER(LERROR_, "Error in Drm_StoreMgmt_DeleteInMemoryLicenses 0x%08lX", dr);
}
}
}
void MediaKeySession::CleanDecryptContexts()
{
if (mDecryptContextMap.size() > 0){
m_oDecryptContext = nullptr;
// Close all decryptors that were created on this session
for (DecryptContextMap::iterator it = mDecryptContextMap.begin(); it != mDecryptContextMap.end(); ++it)
{
PrintBase64(DRM_ID_SIZE, &it->first[0], "Drm_Reader_Close for keyId");
if(it->second){
Drm_Reader_Close(&(it->second->drmDecryptContext));
}
}
mDecryptContextMap.clear();
}
if (m_oDecryptContext != nullptr) {
LOGGER(LINFO_, "Closing active decrypt context");
Drm_Reader_Close(m_oDecryptContext);
delete m_oDecryptContext;
m_oDecryptContext = nullptr;
}
}
} // namespace CDMi
| 34.074291 | 147 | 0.593895 | [
"vector"
] |
d88ae88f7c388fc75726f965b101c3bc70262112 | 15,725 | cpp | C++ | src/Line3D.cpp | devel0/iot-sci | 69deb99454101f56958f5648a3223cfd2d9afffb | [
"MIT"
] | null | null | null | src/Line3D.cpp | devel0/iot-sci | 69deb99454101f56958f5648a3223cfd2d9afffb | [
"MIT"
] | null | null | null | src/Line3D.cpp | devel0/iot-sci | 69deb99454101f56958f5648a3223cfd2d9afffb | [
"MIT"
] | null | null | null | #include "Line3D.h"
#include <number-utils.h>
#include "Matrix3D.h"
#include "CoordinateSystem3D.h"
Line3D *Line3D::_XAxisLine = NULL;
Line3D *Line3D::_YAxisLine = NULL;
Line3D *Line3D::_ZAxisLine = NULL;
const Line3D &Line3D::XAxisLine()
{
if (_XAxisLine == NULL)
{
_XAxisLine = new Line3D(Vector3D::Zero(), Vector3D::XAxis());
}
return *_XAxisLine;
}
const Line3D &Line3D::YAxisLine()
{
if (_YAxisLine == NULL)
{
_YAxisLine = new Line3D(Vector3D::Zero(), Vector3D::YAxis());
}
return *_YAxisLine;
}
const Line3D &Line3D::ZAxisLine()
{
if (_ZAxisLine == NULL)
{
_ZAxisLine = new Line3D(Vector3D::Zero(), Vector3D::ZAxis());
}
return *_ZAxisLine;
}
Vector3D Line3D::To() const
{
return From + V;
}
Vector3D Line3D::Dir() const
{
return V.Normalized();
}
Line3D::Line3D()
{
}
Line3D::Line3D(const Vector3D &from, const Vector3D &to)
{
From = from;
V = to - from;
}
Line3D::Line3D(V3DNR x1, V3DNR y1, V3DNR x2, V3DNR y2)
{
From = Vector3D(x1, y1);
V = Vector3D(x2, y2) - From;
}
Line3D::Line3D(V3DNR x1, V3DNR y1, V3DNR z1, V3DNR x2, V3DNR y2, V3DNR z2)
{
From = Vector3D(x1, y1, z1);
V = Vector3D(x2, y2, z2) - From;
}
Line3D::Line3D(const Vector3D &from, const Vector3D &v, Line3DConstructMode mode)
{
From = from;
V = v;
}
V3DNR Line3D::Length() const
{
return V.Length();
}
bool Line3D::EqualsTol(V3DNR tol, const Line3D &other) const
{
return (From.EqualsTol(tol, other.From) && To().EqualsTol(tol, other.To())) ||
(From.EqualsTol(tol, other.To()) && To().EqualsTol(tol, other.From));
}
nullable<Vector3D> Line3D::CommonPoint(V3DNR tol, const Line3D &other) const
{
if (From.EqualsTol(tol, other.From) || From.EqualsTol(tol, other.To()))
return From;
if (To().EqualsTol(tol, other.From) || To().EqualsTol(tol, other.To()))
return To();
return nullable<Vector3D>();
}
Line3D Line3D::Reverse() const
{
return Line3D(To(), From);
}
Vector3D Line3D::MidPoint() const
{
return (From + To()) / 2.0;
}
Line3D Line3D::Scale(const Vector3D &refpt, V3DNR factor) const
{
return Line3D(From.ScaleAbout(refpt, factor), To().ScaleAbout(refpt, factor));
}
Line3D Line3D::Scale(V3DNR factor) const
{
return Scale(MidPoint(), factor);
}
bool Line3D::LineContainsPoint(V3DNR tol, V3DNR x, V3DNR y, V3DNR z, bool segmentMode) const
{
return LineContainsPoint(tol, Vector3D(x, y, z), segmentMode);
}
bool Line3D::LineContainsPoint(V3DNR tol, const Vector3D &p, bool segmentMode, bool excludeExtreme) const
{
if (::EqualsTol(tol, Length(), 0))
return false;
auto prj = p.Project(*this);
auto dprj = p.Distance(prj);
// check if line contains point
if (dprj > tol)
return false;
if (segmentMode)
{
// line contains given point if there is a scalar s
// for which p = From + s * V
auto s = 0.0;
// to find out the scalar we need to test the first non null component
if (!(::EqualsTol(tol, V.X, 0)))
s = (p.X - From.X) / V.X;
else if (!(::EqualsTol(tol, V.Y, 0)))
s = (p.Y - From.Y) / V.Y;
else if (!(::EqualsTol(tol, V.Z, 0)))
s = (p.Z - From.Z) / V.Z;
if (excludeExtreme)
{
if (p.EqualsTol(tol, From))
return false;
if (p.EqualsTol(tol, To()))
return false;
return (s > 0 && s < 1);
}
else
{
// s is the scalar of V vector that runs From->To
if (s >= 0.0 && s <= 1.0)
return true;
// point on the line but outside exact segment
// check with tolerance
if (s < 0)
return p.EqualsTol(tol, From);
else
return p.EqualsTol(tol, To());
}
}
return true;
}
bool Line3D::SegmentContainsPoint(V3DNR tol, const Vector3D &p, bool excludeExtreme) const
{
return LineContainsPoint(tol, p, true, excludeExtreme);
}
bool Line3D::SegmentContainsPoint(V3DNR tol, V3DNR x, V3DNR y, V3DNR z) const
{
return LineContainsPoint(tol, x, y, z, true);
}
bool Line3D::SemiLineContainsPoint(V3DNR tol, const Vector3D &p) const
{
return LineContainsPoint(tol, p) && (p - From).Concordant(tol, To() - From);
}
nullable<Vector3D> Line3D::Intersect(V3DNR tol, const Line3D &other, LineIntersectBehavior behavior) const
{
auto perpSeg = ApparentIntersect(other);
if (perpSeg.HasValue() && perpSeg.Value().From.EqualsTol(tol, perpSeg.Value().To()))
{
switch (behavior)
{
case LineIntersectBehavior::IntMidPoint:
return perpSeg.Value().MidPoint();
case LineIntersectBehavior::IntPointOnThis:
return perpSeg.Value().From;
case LineIntersectBehavior::IntPointOnOther:
return perpSeg.Value().To();
}
}
// not intersection
return nullable<Vector3D>();
}
nullable<Line3D> Line3D::ApparentIntersect(const Line3D &other) const
{
// this : t = tf + tu * tv
// other : o = of + ou * ov
// res : r = rf + ru * rv
//
// giving res starting from this and toward other
// rf = tf + tu * tv
// rv = of + ou * ov - tf - tu * tv
//
// result:
// r = Line3D(tf + tu * tv, of + ou * ov)
// <=>
// r perpendicular to t and o :
// (1) rv.DotProduct(tv) = 0
// (2) rv.DotProduct(ov) = 0
//
// (1)
// rvx * tvx + rvy * tvy + rvz * tvz = 0 <=>
// (ofx + ou * ovx - tfx - tu * tvx) * tvx +
// (ofy + ou * ovy - tfy - tu * tvy) * tvy +
// (ofz + ou * ovz - tfz - tu * tvz) * tvz = 0
//
// (2)
// rvx * ovx + rvy * ovy + rvz * ovz = 0 <=>
// (ofx + ou * ovx - tfx - tu * tvx) * ovx +
// (ofy + ou * ovy - tfy - tu * tvy) * ovy +
// (ofz + ou * ovz - tfz - tu * tvz) * ovz = 0
//
// unknowns ( tu, ou )
//
// solution through python sympy
//
/*
from sympy import *
ou, tu = symbols('ou tu')
ofx, ovx, tfx, tvx = symbols('ofx ovx tfx tvx')
ofy, ovy, tfy, tvy = symbols('ofy ovy tfy tvy')
ofz, ovz, tfz, tvz = symbols('ofz ovz tfz tvz')
eq1 = Eq((ofx + ou * ovx - tfx - tu * tvx) * tvx +
(ofy + ou * ovy - tfy - tu * tvy) * tvy +
(ofz + ou * ovz - tfz - tu * tvz) * tvz, 0)
eq2 = Eq((ofx + ou * ovx - tfx - tu * tvx) * ovx +
(ofy + ou * ovy - tfy - tu * tvy) * ovy +
(ofz + ou * ovz - tfz - tu * tvz) * ovz, 0)
print(solve([eq1, eq2], [ou, tu]))
*/
// live.sympy.org url :
// http://live.sympy.org/?evaluate=from%20sympy%20import%20*%0A%23--%0Aou%2C%20tu%20%3D%20symbols('ou%20tu')%0A%23--%0Aofx%2C%20ovx%2C%20tfx%2C%20tvx%20%3D%20symbols('ofx%20ovx%20tfx%20tvx')%0A%23--%0Aofy%2C%20ovy%2C%20tfy%2C%20tvy%20%3D%20symbols('ofy%20ovy%20tfy%20tvy')%0A%23--%0Aofz%2C%20ovz%2C%20tfz%2C%20tvz%20%3D%20symbols('ofz%20ovz%20tfz%20tvz')%0A%23--%0Aeq1%20%3D%20Eq((ofx%20%2B%20ou%20*%20ovx%20-%20tfx%20-%20tu%20*%20tvx)%20*%20tvx%20%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(ofy%20%2B%20ou%20*%20ovy%20-%20tfy%20-%20tu%20*%20tvy)%20*%20tvy%20%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(ofz%20%2B%20ou%20*%20ovz%20-%20tfz%20-%20tu%20*%20tvz)%20*%20tvz%2C%200)%0A%23--%0Aeq2%20%3D%20Eq((ofx%20%2B%20ou%20*%20ovx%20-%20tfx%20-%20tu%20*%20tvx)%20*%20ovx%20%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(ofy%20%2B%20ou%20*%20ovy%20-%20tfy%20-%20tu%20*%20tvy)%20*%20ovy%20%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(ofz%20%2B%20ou%20*%20ovz%20-%20tfz%20-%20tu%20*%20tvz)%20*%20ovz%2C%200)%20%20%20%20%20%20%0A%23--%0Asolve(%5Beq1%2C%20eq2%5D%2C%20%5Bou%2C%20tu%5D)%0A%23--%0A
// ou:
// (
// -(tvx**2 + tvy**2 + tvz**2)*(ofx*ovx + ofy*ovy + ofz*ovz - ovx*tfx - ovy*tfy - ovz*tfz) +
// (ovx*tvx + ovy*tvy + ovz*tvz)*(ofx*tvx + ofy*tvy + ofz*tvz - tfx*tvx - tfy*tvy - tfz*tvz)
// )
// /
// ((ovx**2 + ovy**2 + ovz**2)*(tvx**2 + tvy**2 + tvz**2) - (ovx*tvx + ovy*tvy + ovz*tvz)**2)
//
// tu:
// (
// (ovx**2 + ovy**2 + ovz**2)*(ofx*tvx + ofy*tvy + ofz*tvz - tfx*tvx - tfy*tvy - tfz*tvz) -
// (ovx*tvx + ovy*tvy + ovz*tvz)*(ofx*ovx + ofy*ovy + ofz*ovz - ovx*tfx - ovy*tfy - ovz*tfz)
// )
// /
// ((ovx**2 + ovy**2 + ovz**2)*(tvx**2 + tvy**2 + tvz**2) - (ovx*tvx + ovy*tvy + ovz*tvz)**2)
auto tfx = From.X;
auto tvx = V.X;
auto tfy = From.Y;
auto tvy = V.Y;
auto tfz = From.Z;
auto tvz = V.Z;
auto ofx = other.From.X;
auto ovx = other.V.X;
auto ofy = other.From.Y;
auto ovy = other.V.Y;
auto ofz = other.From.Z;
auto ovz = other.V.Z;
auto d = ((ovx * ovx + ovy * ovy + ovz * ovz) * (tvx * tvx + tvy * tvy + tvz * tvz) -
V3DPOW(ovx * tvx + ovy * tvy + ovz * tvz, 2));
// no solution
if (d < std::numeric_limits<V3DNR>::epsilon())
return nullable<Line3D>();
auto ou = (-(tvx * tvx + tvy * tvy + tvz * tvz) * (ofx * ovx + ofy * ovy + ofz * ovz - ovx * tfx - ovy * tfy - ovz * tfz) +
(ovx * tvx + ovy * tvy + ovz * tvz) * (ofx * tvx + ofy * tvy + ofz * tvz - tfx * tvx - tfy * tvy - tfz * tvz)) /
d;
auto tu = ((ovx * ovx + ovy * ovy + ovz * ovz) * (ofx * tvx + ofy * tvy + ofz * tvz - tfx * tvx - tfy * tvy - tfz * tvz) -
(ovx * tvx + ovy * tvy + ovz * tvz) * (ofx * ovx + ofy * ovy + ofz * ovz - ovx * tfx - ovy * tfy - ovz * tfz)) /
d;
// res
auto rf = From + tu * V;
auto rt = other.From + ou * other.V;
return Line3D(rf, rt);
}
nullable<Vector3D> Line3D::Intersect(V3DNR tol, const Line3D &other, bool thisSegment, bool otherSegment) const
{
auto i = Intersect(tol, other);
if (!i.HasValue())
return nullable<Vector3D>();
if (thisSegment && !SegmentContainsPoint(tol, i.Value()))
return nullable<Vector3D>();
if (otherSegment && !other.SegmentContainsPoint(tol, i.Value()))
return nullable<Vector3D>();
return i;
}
nullable<Line3D> Line3D::Perpendicular(V3DNR tol, const Vector3D &p) const
{
if (LineContainsPoint(tol, p))
return nullable<Line3D>();
auto pRelVProj = (p - From).Project(V);
return Line3D(p, From + pRelVProj);
}
bool Line3D::Colinear(V3DNR tol, const Line3D &other) const
{
return (LineContainsPoint(tol, other.From) && LineContainsPoint(tol, other.To())) ||
(other.LineContainsPoint(tol, From) && other.LineContainsPoint(tol, To()));
}
bool Line3D::IsParallelTo(V3DNR tol, const CoordinateSystem3D &cs) const
{
auto from_ = From.ToUCS(cs);
auto to_ = To().ToUCS(cs);
return ::EqualsTol(tol, from_.Z, to_.Z);
}
nullable<Vector3D> Line3D::Intersect(V3DNR tol, const CoordinateSystem3D &cs) const
{
if (IsParallelTo(tol, cs))
return nullable<Vector3D>();
// O = plane.Origin Vx = plane.CS.BaseX Vy = plane.CS.BaseY
//
// plane : O + alpha * Vx + beta * Vy
// line : From + gamma * V
//
// => m:{ alpha * Vx + beta * Vy - gamma * V } * s = n:{ From - O }
auto m = Matrix3D::FromVectorsAsColumns(cs.BaseX(), cs.BaseY(), -V);
auto n = From - cs.Origin();
auto s = m.Solve(n);
return From + s.Z * V;
}
Line3D Line3D::RotateAboutAxis(const Line3D &axisSegment, V3DNR angleRad) const
{
return Line3D(From.RotateAboutAxis(axisSegment, angleRad), To().RotateAboutAxis(axisSegment, angleRad));
}
Line3D Line3D::SetLength(V3DNR len) const
{
return Line3D(From, V.Normalized() * len, Line3DConstructMode::PointAndVector);
}
Line3D Line3D::Move(const Vector3D &delta) const
{
return Line3D(From + delta, To() + delta);
}
Line3D Line3D::MoveMidpoint(const Vector3D &newMidpoint) const
{
auto mid = MidPoint();
return Move(newMidpoint - mid);
}
vector<Line3D> Line3D::Split(V3DNR tolLen, const vector<Vector3D> &splitPts) const
{
auto res = vector<Line3D>();
res.push_back(*this);
if (splitPts.size() == 0)
return res;
auto splitPtIdx = 0;
while (splitPtIdx < splitPts.size())
{
vector<Line3D> repl;
for (int i = 0; i < res.size(); ++i)
{
auto spnt = splitPts[splitPtIdx];
if (res[i].SegmentContainsPoint(tolLen, spnt, true))
{
repl = vector<Line3D>();
for (int h = 0; h < res.size(); ++h)
{
if (h == i)
{
auto l = res[h];
repl.push_back(Line3D(l.From, spnt));
repl.push_back(Line3D(spnt, l.To()));
}
else
repl.push_back(res[h]);
}
break; // break cause need to reeval
}
}
if (repl.size() != 0)
{
res = repl;
continue;
}
else
splitPtIdx++;
}
return res;
}
Line3D Line3D::EnsureFrom(V3DNR tolLen, const Vector3D &pt) const
{
if (From.EqualsTol(tolLen, pt))
return *this;
if (To().EqualsTol(tolLen, pt))
return Reverse();
error("ensurefrom: pt not found");
}
Line3D Line3D::Offset(V3DNR tol, const Vector3D &refPt, V3DNR offset) const
{
auto perp = Perpendicular(tol, refPt);
auto voff = (-perp.Value().V).Normalized() * offset;
auto res = Line3D(From + voff, To() + voff);
return res;
}
Line3D Line3D::Normalized() const
{
return Line3D(From, V.Normalized(), Line3DConstructMode::PointAndVector);
}
Line3D Line3D::Swapped() const
{
return Line3D(To(), From);
}
Line3D Line3D::Inverted() const
{
return Line3D(From, -V, Line3DConstructMode::PointAndVector);
}
nullable<Line3D> Line3D::Bisect(V3DNR tol_len, const Line3D &other, const nullable<Vector3D> ¶llelRotationAxis) const
{
if (V.IsParallelTo(tol_len, other.V))
{
if (!parallelRotationAxis.HasValue())
return nullable<Line3D>();
auto p = From;
if (To().EqualsTol(tol_len, other.From) || To().EqualsTol(tol_len, other.To()))
p = To();
return Line3D(p, V.RotateAboutAxis(parallelRotationAxis.Value(), PI / 2), Line3DConstructMode::PointAndVector);
}
auto ip = Intersect(tol_len, other);
if (!ip.HasValue())
return nullable<Line3D>();
auto k = From.EqualsTol(tol_len, ip.Value()) ? To() : From;
auto k2 = other.From.EqualsTol(tol_len, ip.Value()) ? other.To() : other.From;
auto c = (k - ip.Value()).RotateAs(tol_len, (k - ip.Value()), (k2 - ip.Value()), .5);
return Line3D(ip.Value(), c, Line3DConstructMode::PointAndVector);
}
//
Line3D operator*(V3DNR s, const Line3D &l)
{
return Line3D(l.From, l.V * s, Line3D::Line3DConstructMode::PointAndVector);
}
Line3D operator*(const Line3D &l, V3DNR s)
{
return Line3D(l.From, l.V * s, Line3D::Line3DConstructMode::PointAndVector);
}
Line3D operator+(const Line3D &l, const Vector3D &delta)
{
return Line3D(l.From + delta, l.V, Line3D::Line3DConstructMode::PointAndVector);
}
Line3D operator-(const Line3D &l, const Vector3D &delta)
{
return Line3D(l.From - delta, l.V, Line3D::Line3DConstructMode::PointAndVector);
} | 29.558271 | 1,287 | 0.56337 | [
"vector",
"3d"
] |
d88b28883fcb99b7e4645dfddf1f837bff5bb8a4 | 1,999 | cpp | C++ | 0x0002_var_const_array_vector/main.cpp | mytechnotalent/Fundamental-C- | f0113147bc858df8aefc399faa9fe51e08d51a42 | [
"MIT"
] | 24 | 2021-06-06T14:23:29.000Z | 2022-01-05T00:00:41.000Z | 0x0002_var_const_array_vector/main.cpp | mytechnotalent/Fundamental-C- | f0113147bc858df8aefc399faa9fe51e08d51a42 | [
"MIT"
] | null | null | null | 0x0002_var_const_array_vector/main.cpp | mytechnotalent/Fundamental-C- | f0113147bc858df8aefc399faa9fe51e08d51a42 | [
"MIT"
] | 5 | 2021-07-09T09:27:12.000Z | 2021-12-06T01:43:53.000Z | #include <iostream>
#include <vector>
#include <string>
int main()
{
// char
char x = 'x';
std::cout << x << std::endl;
// bool
bool isHappy = true;
std::cout << isHappy << std::endl;
// int
int y = 42;
std::cout << y << std::endl;
// floating-point
std::cout.precision(17);
double zz = 42.111111111111111;
std::cout << zz << std::endl;
// constants
const int MAGIC_NUMBER = 42;
std::cout << MAGIC_NUMBER << std::endl;
// arrays
int favorite_numbers[2] = {42, 7};
std::cout << &favorite_numbers << std::endl;
std::cout << favorite_numbers[0] << std::endl;
std::cout << favorite_numbers[1] << std::endl;
// vectors
std::vector<int> favourite_numbers; // always init to 0, no need to init
favourite_numbers.push_back(42);
favourite_numbers.push_back(7);
std::cout << &favourite_numbers << std::endl;
std::cout << favourite_numbers.at(0) << std::endl;
std::cout << favourite_numbers.at(1) << std::endl;
std::cout << favourite_numbers.size() << std::endl;
int da_fav_num = 42;
std::vector<int>::iterator it;
it = std::find(favourite_numbers.begin(), favourite_numbers.end(), da_fav_num);
if (it != favourite_numbers.end())
{
std::cout << da_fav_num << " found at position: ";
std::cout << it - favourite_numbers.begin() << std::endl;
}
else
std::cout << da_fav_num << " not found...";
// operators
int result = 0;
result++;
std::cout << result << std::endl;
// strings
std::string secret_number = "forty-two";
std::cout << secret_number << std::endl;
secret_number.at(4) = 'e';
std::cout << secret_number << std::endl;
std::cout << secret_number.length() << std::endl;
std::cout << (secret_number == "forte-two") << std::endl;
std::cout << secret_number.substr(3, 8) << std::endl;
std::cout << secret_number.find("te-two") << std::endl;
std::cout << secret_number.erase(0, 3) << std::endl;
secret_number.clear();
std::cout << secret_number << std::endl;
return 0;
}
| 27.383562 | 81 | 0.618309 | [
"vector"
] |
d890191da775398976dd538a0443de075c77338e | 16,191 | hpp | C++ | src/qdeferred.hpp | CETONI-Software/3rdparty-QDeferred | 662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9 | [
"MIT"
] | 51 | 2019-02-11T15:06:22.000Z | 2022-03-29T06:52:19.000Z | src/qdeferred.hpp | CETONI-Software/3rdparty-QDeferred | 662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9 | [
"MIT"
] | 4 | 2020-10-28T10:20:53.000Z | 2022-01-24T08:23:15.000Z | src/qdeferred.hpp | CETONI-Software/3rdparty-QDeferred | 662bdc6bc8debf025859ddc59e5dfb8f96b1e5b9 | [
"MIT"
] | 12 | 2019-11-19T19:14:53.000Z | 2022-03-29T06:52:20.000Z | #ifndef QDEFERRED_H
#define QDEFERRED_H
#include <QExplicitlySharedDataPointer>
#include <QList>
#include <QTimer>
#include <functional>
#include <QDebug>
#include "qdeferreddata.hpp"
template<class ...Types>
class QDeferred
{
public:
// constructors
QDeferred();
QDeferred(const QDeferred<Types...> &other);
QDeferred &operator=(const QDeferred<Types...> &rhs);
~QDeferred();
// wrapper consumer API (with chaning)
// get state method
QDeferredState state() const;
// done method
QDeferred<Types...> done(
const std::function<void(Types(...args))> &callback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// fail method
QDeferred<Types...> fail(
const std::function<void(Types(...args))> &callback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method
template<class ...RetTypes, typename T>
QDeferred<RetTypes...> then(
const T &doneCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method specialization
template<class ...RetTypes>
QDeferred<RetTypes...> then(
const std::function<QDeferred<RetTypes...>(Types(...args))> &doneCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method
template<class ...RetTypes, typename T>
QDeferred<RetTypes...> then(
const T &doneCallback,
const std::function<void()> &failCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method specialization
template<class ...RetTypes>
QDeferred<RetTypes...> then(
const std::function<QDeferred<RetTypes...>(Types(...args))> &doneCallback,
const std::function<void()> &failCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// progress method
QDeferred<Types...> progress(
const std::function<void(Types(...args))> &callback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// extra consume API (static)
// NOTE : there is no case in setting a Qt::ConnectionType in when method because
// we never know which deferred in which thread will be the last one to be resolved/rejected
template <class ...OtherTypes, typename... Rest>
static QDeferred<> when(QDeferred<OtherTypes...> t, Rest... rest);
// can pass a container (implementing begin/end iterator and ::size())
// instead of passing variadic arguments one by one
template<template<class> class Container, class ...OtherTypes>
static QDeferred<> when(const Container<QDeferred<OtherTypes...>>& deferList);
// block current thread until deferred object gets resolved/rejected
// NOTE : since current thread is blocked, the deferred object must be
// resolved/rejected in a different thread
template <class ...OtherTypes, typename... Rest>
static bool await(QDeferred<OtherTypes...> t, Rest... rest);
// syntactic sugar for container of deferred objects
template<template<class> class Container, class ...OtherTypes>
static bool await(const Container<QDeferred<OtherTypes...>>& deferList);
// wrapper provider API
// resolve method
void resolve(Types(...args));
// reject method
void reject(Types(...args));
// notify method
void notify(Types(...args));
// reject method with zero arguments (only to be used internally for the 'then' propagation mechanism)
void rejectZero();
protected:
QExplicitlySharedDataPointer<QDeferredData<Types...>> m_data;
private:
// friend classes
friend class QDeferredDataBase;
// internal methods
// get when count method
int getWhenCount();
// set when count method
void setWhenCount(int whenCount);
// done method with zero arguments
void doneZero(const std::function<void()> &callback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// fail method with zero arguments
void failZero(const std::function<void()> &callback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method specialization internal
template<class ...RetTypes>
QDeferred<RetTypes...> thenAlias(
const std::function<QDeferred<RetTypes...>(Types(...args))> &doneCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// then method specialization internal
template<class ...RetTypes>
QDeferred<RetTypes...> thenAlias(
const std::function<QDeferred<RetTypes...>(Types(...args))> &doneCallback,
const std::function<void()> &failCallback,
const Qt::ConnectionType &connection = Qt::AutoConnection);
// internal await requires simple QDefer
static bool awaitInternal(const QDeferred<>& defer);
};
// alias for no argument types
using QDefer = QDeferred<>;
template<class ...Types>
QDeferred<Types...>::QDeferred() : m_data(nullptr)
{
m_data = QExplicitlySharedDataPointer<QDeferredData<Types...>>(new QDeferredData<Types...>());
}
template<class ...Types>
QDeferred<Types...>::QDeferred(const QDeferred<Types...> &other) : m_data(other.m_data)
{
m_data.reset();
m_data = other.m_data;
}
template<class ...Types>
QDeferred<Types...> &QDeferred<Types...>::operator=(const QDeferred<Types...> &rhs)
{
if (this != &rhs) {
m_data.reset();
m_data.operator=(rhs.m_data);
}
return *this;
}
template<class ...Types>
QDeferred<Types...>::~QDeferred()
{
m_data.reset();
}
template<class ...Types>
QDeferredState QDeferred<Types...>::state() const
{
return m_data->state();
}
template<class ...Types>
QDeferred<Types...> QDeferred<Types...>::done(
const std::function<void(Types(...args))> & callback,
const Qt::ConnectionType & connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(callback, "Deferred done method.", "Invalid done callback argument");
m_data->done(callback, connection);
return *this;
}
template<class ...Types>
QDeferred<Types...> QDeferred<Types...>::fail(const std::function<void(Types(...args))> &callback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(callback, "Deferred fail method.", "Invalid fail callback argument");
m_data->fail(callback, connection);
return *this;
}
template<class ...Types>
template<class ...RetTypes, typename T>
QDeferred<RetTypes...> QDeferred<Types...>::then(
const T &doneCallback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
return this->thenAlias<RetTypes...>((std::function<QDeferred<RetTypes...>(Types(...args))>)doneCallback, connection);
}
template<class ...Types>
template<class ...RetTypes>
QDeferred<RetTypes...> QDeferred<Types...>::then(
const std::function<QDeferred<RetTypes...>(Types(...args))> & doneCallback,
const Qt::ConnectionType & connection/* = Qt::AutoConnection*/)
{
return this->thenAlias<RetTypes...>(doneCallback, connection);
}
template<class ...Types>
template<class ...RetTypes>
QDeferred<RetTypes...> QDeferred<Types...>::thenAlias(
const std::function<QDeferred<RetTypes...>(Types(...args))> & doneCallback,
const Qt::ConnectionType & connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(doneCallback, "Deferred then method.", "Invalid done callback as first argument");
// create deferred to return
QDeferred<RetTypes...> retPromise;
// add intermediate done nameless callback
m_data->done([doneCallback, retPromise](Types(...args1)) mutable {
// when done execute user callback, then when user deferred and when done...
doneCallback(args1...)
.done([retPromise](RetTypes(...args2)) mutable {
// resolve returned deferred
retPromise.resolve(args2...);
})
.fail([retPromise](RetTypes(...args2)) mutable {
// reject returned deferred
retPromise.reject(args2...);
})
.progress([retPromise](RetTypes(...args2)) mutable {
// notify returned deferred
retPromise.notify(args2...);
});
}, connection);
// allow propagation
m_data->failZero([retPromise]() mutable {
// reject zero
retPromise.rejectZero();
}, connection);
// return new deferred
return retPromise;
}
template<class ...Types>
template<class ...RetTypes, typename T>
QDeferred<RetTypes...> QDeferred<Types...>::then(
const T &doneCallback,
const std::function<void()> &failCallback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
return this->thenAlias<RetTypes...>((std::function<QDeferred<RetTypes...>(Types(...args))>)doneCallback, failCallback, connection);
}
template<class ...Types>
template<class ...RetTypes>
QDeferred<RetTypes...> QDeferred<Types...>::then(
const std::function<QDeferred<RetTypes...>(Types(...args))> & doneCallback,
const std::function<void()> & failCallback,
const Qt::ConnectionType & connection/* = Qt::AutoConnection*/)
{
return this->thenAlias<RetTypes...>(doneCallback, failCallback, connection);
}
template<class ...Types>
template<class ...RetTypes>
QDeferred<RetTypes...> QDeferred<Types...>::thenAlias(
const std::function<QDeferred<RetTypes...>(Types(...args))> & doneCallback,
const std::function<void()> & failCallback,
const Qt::ConnectionType & connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(doneCallback, "Deferred then method.", "Invalid done callback as first argument");
Q_ASSERT_X(failCallback, "Deferred then method.", "Invalid fail callback as second argument");
// add fail zero (internal) callback
m_data->failZero([failCallback]() mutable {
// when fail zero execute user callback
failCallback();
}, connection);
// call other
return this->then<RetTypes...>(doneCallback, connection);
}
template<class ...Types>
QDeferred<Types...> QDeferred<Types...>::progress(const std::function<void(Types(...args))> &callback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(callback, "Deferred progress method.", "Invalid progress callback argument");
m_data->progress(callback, connection);
return *this;
}
template<class ...Types>
void QDeferred<Types...>::resolve(Types(...args))
{
// pass reference to this to at least have 1 reference until callbacks get executed
m_data->resolve(*this, args...);
}
template<class ...Types>
void QDeferred<Types...>::reject(Types(...args))
{
// pass reference to this to at least have 1 reference until callbacks get executed
m_data->reject(*this, args...);
}
template<class ...Types>
void QDeferred<Types...>::rejectZero()
{
// pass reference to this to at least have 1 reference until callbacks get executed
m_data->rejectZero(*this);
}
template<class ...Types>
void QDeferred<Types...>::notify(Types(...args))
{
// pass reference to this to at least have 1 reference until callbacks get executed
m_data->notify(*this, args...);
}
template<class ...Types>
void QDeferred<Types...>::doneZero(const std::function<void()> &callback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(callback, "Deferred doneZero method.", "Invalid doneZero callback argument");
m_data->doneZero(callback, connection);
}
template<class ...Types>
void QDeferred<Types...>::failZero(const std::function<void()> &callback,
const Qt::ConnectionType &connection/* = Qt::AutoConnection*/)
{
// check if valid
Q_ASSERT_X(callback, "Deferred failZero method.", "Invalid failZero callback argument");
m_data->failZero(callback, connection);
}
/*
https://api.jquery.com/jQuery.when/
In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a
new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master
Deferred as soon as one of the Deferreds is rejected.
*/
template<class ...Types>
template<class ...OtherTypes, class... Rest>
QDefer QDeferred<Types...>::when(QDeferred<OtherTypes...> t, Rest... rest)
{
QDefer retDeferred;
// setup necessary variables for expansion
int countArgs = sizeof...(Rest) + 1;
// done callback, resolve if ALL done
auto doneCallback = [retDeferred, countArgs]() mutable {
// whenCount++
retDeferred.setWhenCount(retDeferred.getWhenCount() + 1);
int whenCount = retDeferred.getWhenCount();
if (whenCount == countArgs)
{
retDeferred.resolve();
}
};
// fail callback, reject if ONE fails
auto failCallback = [retDeferred]() mutable {
// can only reject once
if (retDeferred.state() != QDeferredState::PENDING)
{
return;
}
retDeferred.reject();
};
// expand
QDeferredDataBase::whenInternal(doneCallback, failCallback, t, rest...);
// return deferred
return retDeferred;
}
template<class ...Types>
template<template<class> class Container, class ...OtherTypes>
QDefer QDeferred<Types...>::when(const Container<QDeferred<OtherTypes...>>& deferList)
{
QDefer retDeferred;
// setup necessary variables for expansion
int count = deferList.size();
// done callback, resolve if ALL done
auto doneCallback = [retDeferred, count]() mutable {
// whenCount++
retDeferred.setWhenCount(retDeferred.getWhenCount() + 1);
int whenCount = retDeferred.getWhenCount();
if (whenCount == count)
{
retDeferred.resolve();
}
};
// fail callback, reject if ONE fails
auto failCallback = [retDeferred]() mutable {
// can only reject once
if (retDeferred.state() != QDeferredState::PENDING)
{
return;
}
retDeferred.reject();
};
// call in friend class to access private methods
QDeferredDataBase::whenInternal(doneCallback, failCallback, deferList);
// return deferred
return retDeferred;
}
template<class ...Types>
template<class ...OtherTypes, typename ...Rest>
bool QDeferred<Types...>::await(QDeferred<OtherTypes...> t, Rest ...rest)
{
return QDefer::awaitInternal(QDefer::when(t, rest...));
}
template<class ...Types>
template<template<class> class Container, class ...OtherTypes>
bool QDeferred<Types...>::await(const Container<QDeferred<OtherTypes...>>& deferList)
{
return QDefer::awaitInternal(QDefer::when(deferList));
}
template<class ...Types>
bool QDeferred<Types...>::awaitInternal(const QDeferred<>& defer)
{
QEventLoop blockingEventLoop;
// pass loop reference so it can be un-blocked in resolving/rejecting thread
defer.m_data->m_blockingEventLoop = &blockingEventLoop;
// handle case where thread gets stopped or deleted
QThread* currThread = QThread::currentThread();
QObject::connect(currThread, &QThread::finished, &blockingEventLoop,
[&blockingEventLoop]() {
if (blockingEventLoop.isRunning())
{
blockingEventLoop.quit();
}
});
QObject::connect(currThread, &QThread::destroyed, &blockingEventLoop,
[&blockingEventLoop]() {
if (blockingEventLoop.isRunning())
{
blockingEventLoop.quit();
}
});
// sometimes it is already resolved by the time we reach here
if (defer.state() != QDeferredState::PENDING)
{
QTimer::singleShot(0, &blockingEventLoop, [&blockingEventLoop]() {
if (blockingEventLoop.isRunning())
{
blockingEventLoop.quit();
}
});
}
// block until resolved/rejected
blockingEventLoop.exec();
// return whether resolved or rejected
return defer.state() == QDeferredState::RESOLVED;
}
template<class ...Types>
void QDeferred<Types...>::setWhenCount(int whenCount)
{
m_data->m_whenCount = whenCount;
}
template<class ...Types>
int QDeferred<Types...>::getWhenCount()
{
return m_data->m_whenCount;
}
#endif // QDEFERRED_H
| 33.042857 | 133 | 0.672411 | [
"object"
] |
d89a899e4957cf79279b9776f17e6ac8874946b7 | 11,090 | cc | C++ | Sources/OpenGL sb6/Chapter12/_1231_deferred.cc | liliilli/SH-GraphicsStudy | 314af5ad6ec04b91ec86978c60cc2f96db6a1d7c | [
"Unlicense"
] | 3 | 2019-11-23T16:37:22.000Z | 2021-05-02T20:43:27.000Z | Sources/OpenGL sb6/Chapter12/_1231_deferred.cc | liliilli/SH-GraphicsStudy | 314af5ad6ec04b91ec86978c60cc2f96db6a1d7c | [
"Unlicense"
] | 3 | 2018-05-01T04:52:39.000Z | 2018-05-10T02:14:46.000Z | Sources/OpenGL sb6/Chapter12/_1231_deferred.cc | liliilli/GraphicsStudy | 314af5ad6ec04b91ec86978c60cc2f96db6a1d7c | [
"Unlicense"
] | 2 | 2019-11-23T16:37:38.000Z | 2022-03-29T10:33:32.000Z | #include <sb6.h>
#include <vmath.h>
#include <object.h>
#include <shader.h>
#include <sb6ktx.h>
#ifndef _WIN32
#define _WIN32 0
#endif
enum {
MAX_DISPLAY_WIDTH = 2048,
MAX_DISPLAY_HEIGHT = 2048,
NUM_LIGHTS = 64,
NUM_INSTANCES = (15 * 15)
};
class DeferredShading final : public sb6::application {
public:
DeferredShading() : render_program_nm(0), render_program(0), light_program(0), use_nm(true), paused(false) {}
protected:
void init() override final {
application::init();
constexpr const char title[] = "OpenGL SuperBible - Deferred Shading";
memcpy(info.title, title, sizeof(title));
}
void startup() override final {
LoadShaders();
object.load("media/objects/ladybug.sbm");
using sb6::ktx::file::load;
tex_nm = load("media/textures/ladybug_nm.ktx");
tex_diffuse = load("media/textures/ladybug_co.ktx");
GenerateGBuffer();
glGenVertexArrays(1, &fs_quad_empty_vao);
glBindVertexArray(fs_quad_empty_vao);
glGenBuffers(1, &light_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, light_ubo);
glBufferData(GL_UNIFORM_BUFFER, NUM_LIGHTS * sizeof(DLight), NULL, GL_DYNAMIC_DRAW);
glGenBuffers(1, &render_transform_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, render_transform_ubo);
glBufferData(GL_UNIFORM_BUFFER, (2 + NUM_INSTANCES) * sizeof(vmath::mat4), NULL, GL_DYNAMIC_DRAW);
}
void RenderGBuffer(float t) {
static const GLuint uint_zeros[] = { 0, 0, 0, 0 };
static const GLfloat float_zeros[] = { 0.0f, 0.0f, 0.0f, 0.0f };
static const GLfloat float_ones[] = { 1.0f, 1.0f, 1.0f, 1.0f };
static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glBindFramebuffer(GL_FRAMEBUFFER, gbuffer);
glViewport(0, 0, info.windowWidth, info.windowHeight);
glDrawBuffers(2, draw_buffers);
glClearBufferuiv(GL_COLOR, 0, uint_zeros);
glClearBufferuiv(GL_COLOR, 1, uint_zeros);
glClearBufferfv(GL_DEPTH, 0, float_ones);
UpdateMatrixesRenderTransformUbo(t);
glUseProgram(use_nm ? render_program_nm : render_program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_diffuse);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex_nm);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
object.render(NUM_INSTANCES);
}
void UpdateMatrixesRenderTransformUbo(float t) {
glBindBufferBase(GL_UNIFORM_BUFFER, 0, render_transform_ubo);
vmath::mat4* matrices = reinterpret_cast<vmath::mat4*>(glMapBufferRange(GL_UNIFORM_BUFFER, 0,
(2 + NUM_INSTANCES) * sizeof(vmath::mat4), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
matrices[0] = vmath::perspective(50.0f, (float)info.windowWidth / (float)info.windowHeight, 0.1f, 1000.0f);
const float d = (sinf(t * 0.131f) + 2.0f) * 0.15f;
vmath::vec3 eye_pos = vmath::vec3(d * 120.0f * sinf(t * 0.11f), 5.5f, d * 120.0f * cosf(t * 0.01f));
matrices[1] = vmath::lookat(eye_pos, vmath::vec3(0.0f, -20.0f, 0.0f), vmath::vec3(0.0f, 1.0f, 0.0f));
for (auto j = 0; j < 15; j++) {
for (auto i = 0; i < 15; i++) {
matrices[j * 15 + i + 2] = vmath::translate((i - 7.5f) * 7.0f, 0.0f, (j - 7.5f) * 11.0f);
}
}
glUnmapBuffer(GL_UNIFORM_BUFFER);
}
void UpdateMatrixesLightUbo(float t) {
glBindBufferBase(GL_UNIFORM_BUFFER, 0, light_ubo);
DLight* lights = reinterpret_cast<DLight *>(glMapBufferRange(GL_UNIFORM_BUFFER, 0,
NUM_LIGHTS * sizeof(DLight), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
for (auto i = 0; i < NUM_LIGHTS; i++) {
float i_f = ((float)i - 7.5f) * 0.1f + 0.3f;
lights[i].position = vmath::vec3(100.0f * sinf(t * 1.1f + (5.0f * i_f)) * cosf(t * 2.3f + (9.0f * i_f)),
15.0f,
100.0f * sinf(t * 1.5f + (6.0f * i_f)) * cosf(t * 1.9f + (11.0f * i_f))); // 300.0f * sinf(t * i_f * 0.7f) * cosf(t * i_f * 0.9f) - 600.0f);
lights[i].color = vmath::vec3(cosf(i_f * 14.0f) * 0.5f + 0.8f,
sinf(i_f * 17.0f) * 0.5f + 0.8f,
sinf(i_f * 13.0f) * cosf(i_f * 19.0f) * 0.5f + 0.8f);
}
glUnmapBuffer(GL_UNIFORM_BUFFER);
}
void render(double currentTime) override final {
static double last_time = 0.0;
static double total_time = 0.0;
if (!paused) total_time += (currentTime - last_time);
else {
if constexpr (_WIN32) Sleep(10);
}
last_time = currentTime;
RenderGBuffer(static_cast<float>(total_time));
// Final Render
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, info.windowWidth, info.windowHeight);
glDrawBuffer(GL_BACK);
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]);
if (vis_mode == EVisibilityMode::VIS_OFF)
glUseProgram(light_program);
else {
glUseProgram(vis_program);
glUniform1i(loc_vis_mode, static_cast<int>(vis_mode));
}
UpdateMatrixesLightUbo(static_cast<float>(total_time));
glBindVertexArray(fs_quad_empty_vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Release bind status.
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void shutdown() override final {
glDeleteTextures(3, &gbuffer_tex[0]);
glDeleteFramebuffers(1, &gbuffer);
glDeleteProgram(render_program);
glDeleteProgram(light_program);
}
void onKey(int key, int action) override final {
if (action) {
switch (key) {
case 'R': LoadShaders(); break;
case 'P': paused = !paused; break;
case 'N': use_nm = !use_nm; break;
case '1': vis_mode = EVisibilityMode::VIS_OFF; break;
case '2': vis_mode = EVisibilityMode::VIS_NORMALS; break;
case '3': vis_mode = EVisibilityMode::VIS_WS_COORDS; break;
case '4': vis_mode = EVisibilityMode::VIS_DIFFUSE; break;
case '5': vis_mode = EVisibilityMode::VIS_META; break;
default: break;
}
}
}
private:
void LoadShaders() {
GLuint vs, fs;
vs = sb6::shader::load("media/shaders/deferredshading/render.vs.glsl", GL_VERTEX_SHADER);
fs = sb6::shader::load("media/shaders/deferredshading/render.fs.glsl", GL_FRAGMENT_SHADER);
if (render_program) glDeleteProgram(render_program);
render_program = glCreateProgram();
glAttachShader(render_program, vs);
glAttachShader(render_program, fs);
glLinkProgram(render_program);
glDeleteShader(vs);
glDeleteShader(fs);
vs = sb6::shader::load("media/shaders/deferredshading/render-nm.vs.glsl", GL_VERTEX_SHADER);
fs = sb6::shader::load("media/shaders/deferredshading/render-nm.fs.glsl", GL_FRAGMENT_SHADER);
render_program_nm = glCreateProgram();
glAttachShader(render_program_nm, vs);
glAttachShader(render_program_nm, fs);
glLinkProgram(render_program_nm);
glDeleteShader(vs);
glDeleteShader(fs);
vs = sb6::shader::load("media/shaders/deferredshading/light.vs.glsl", GL_VERTEX_SHADER);
fs = sb6::shader::load("media/shaders/deferredshading/light.fs.glsl", GL_FRAGMENT_SHADER);
if (light_program) glDeleteProgram(light_program);
light_program = glCreateProgram();
glAttachShader(light_program, vs);
glAttachShader(light_program, fs);
glLinkProgram(light_program);
glDeleteShader(fs);
fs = sb6::shader::load("media/shaders/deferredshading/render-vis.fs.glsl", GL_FRAGMENT_SHADER);
vis_program = glCreateProgram();
glAttachShader(vis_program, vs);
glAttachShader(vis_program, fs);
glLinkProgram(vis_program);
loc_vis_mode = glGetUniformLocation(vis_program, "vis_mode");
glDeleteShader(vs);
glDeleteShader(fs);
}
void GenerateGBuffer() {
glGenFramebuffers(1, &gbuffer);
glBindFramebuffer(GL_FRAMEBUFFER, gbuffer);
glGenTextures(3, gbuffer_tex);
// gbuffer_tex[0] saves three 16bits normal into R 32bit and G 16bit,
// 16bits albedo colors into G latter 16bit and B
// and 32bit material index as final item.
glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32UI, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// gbuffer_tex[1] saves three 32bits floating point world coordinate and 32bit specular power value.
glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Just depth buffer. :)
glBindTexture(GL_TEXTURE_2D, gbuffer_tex[2]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, MAX_DISPLAY_WIDTH, MAX_DISPLAY_HEIGHT);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gbuffer_tex[0], 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, gbuffer_tex[1], 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gbuffer_tex[2], 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
private:
GLuint gbuffer;
GLuint gbuffer_tex[3];
GLuint fs_quad_empty_vao;
sb6::object object;
GLuint render_program;
GLuint render_program_nm;
GLuint render_transform_ubo;
GLuint light_program;
GLuint light_ubo;
GLuint vis_program;
GLint loc_vis_mode;
GLuint tex_diffuse;
GLuint tex_nm;
bool use_nm;
bool paused;
enum class EVisibilityMode : int {
VIS_OFF = 0,
VIS_NORMALS,
VIS_WS_COORDS,
VIS_DIFFUSE,
VIS_META
};
EVisibilityMode vis_mode = EVisibilityMode::VIS_OFF;
#pragma pack (push, 1)
struct DLight {
vmath::vec3 position;
unsigned int : 32; // pad0
vmath::vec3 color;
unsigned int : 32; // pad1
};
#pragma pack (pop)
};
DECLARE_MAIN(DeferredShading) | 36.123779 | 185 | 0.623805 | [
"render",
"object"
] |
d89c141ed9a18bb728193d9d9174645c40823fe4 | 4,300 | cpp | C++ | test/Config.cpp | LiamPattinson/luaconfig | 8f09b3176fcc08f5d212ca49f72a4da429716479 | [
"MIT"
] | null | null | null | test/Config.cpp | LiamPattinson/luaconfig | 8f09b3176fcc08f5d212ca49f72a4da429716479 | [
"MIT"
] | null | null | null | test/Config.cpp | LiamPattinson/luaconfig | 8f09b3176fcc08f5d212ca49f72a4da429716479 | [
"MIT"
] | null | null | null | // Config.cpp
//
// Unit test for Config.hpp
#include <luaconfig/luaconfig.hpp>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
#include <array>
int main(void)
{
// Open file
luaconfig::Config cfg("test.lua");
// Test simple reading
{
auto x = cfg.get<double>("x");
auto y = cfg.get<double>("y");
auto z = cfg.get<double>("z");
std::cout << x << std::endl;
std::cout << y << std::endl;
std::cout << z << std::endl;
}
// Test exceptions
try{
luaconfig::Config cfg("not_a_file.lua");
} catch( const luaconfig::FileException& e){
std::cout << e.what() << std::endl;
}
try{
auto a = cfg.get<int>("a");
} catch( const luaconfig::TypeMismatchException& e){
std::cout << e.what() << std::endl;
}
// Test default get
{
auto x = cfg.get<double>("not_a_variable",17);
std::cout << x << std::endl;
}
// Now, put SFINAE bits through their paces
// (compile time tests only)
// floats
{auto x = cfg.get<float>("x"); std::cout<<x<<std::endl;}
// ints
{char i = cfg.get<char>("i"); std::cout << i << std::endl;}
{auto i = cfg.get<short>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<unsigned short>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<int>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<unsigned>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<long>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<unsigned long>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<long long>("i"); std::cout<<i<<std::endl;}
{auto i = cfg.get<unsigned long long>("i"); std::cout<<i<<std::endl;}
// bool
{auto b = cfg.get<bool>("b"); std::cout<<std::boolalpha<<b<<std::endl;}
// string
{auto s = cfg.get<std::string>("s"); std::cout<<s<<std::endl;}
// string test
{auto x = cfg.get<double>(std::string{"x"}); std::cout << x << std::endl;}
// set globals
{ cfg.set("m",36); auto m = cfg.get<int>("m"); std::cout << m << std::endl;}
{ cfg.set("m",36.2); auto m = cfg.get<float>("m"); std::cout << m << std::endl;}
{ cfg.set("m",true); auto m = cfg.get<bool>("m"); std::cout << m << std::endl;}
{ cfg.set("m","cstr"); auto m = cfg.get<std::string>("m"); std::cout << m << std::endl;}
{ cfg.set("m",std::string{"stdstr"}); auto m = cfg.get<std::string>("m"); std::cout << m << std::endl;}
// Make Setting (no tests of whether Settings actually work)
{luaconfig::Setting col = cfg.get<luaconfig::Setting>("color");}
// Refocus setting
{
auto set = cfg.get<luaconfig::Setting>("color");
auto r = set.get<double>("r");
std::cout << "Before refocus:" << r << std::endl;
cfg.refocus( set, "array");
auto x = set.get<double>(1);
std::cout << "After refocus:" << x << std::endl;
}
// Dot notation
{
auto x = cfg.get<double>("color.r");
auto y = cfg.get<std::string>("table.string");
auto z = cfg.get<std::string>("table.table.string");
std::cout << x << std::endl;
std::cout << y << std::endl;
std::cout << z << std::endl;
}
// Integer indexed dot notation
{
auto x = cfg.get<double>("array.1");
auto y = cfg.get<double>("array.2");
auto z = cfg.get<double>("array.3");
std::cout << x << std::endl;
std::cout << y << std::endl;
std::cout << z << std::endl;
auto m = cfg.get<double>("matrix.2.2");
std::cout << m << std::endl;
}
// exists
{
bool x = cfg.exists("array");
bool y = cfg.exists("array.1");
bool z = cfg.exists("qwerty");
std::cout << std::boolalpha << x << std::endl;
std::cout << std::boolalpha << y << std::endl;
std::cout << std::boolalpha << z << std::endl;
}
// iterables
{
std::array<double,2> arr;
cfg.get( "array", arr.begin(), arr.end());
for( auto&& x : arr) std::cout << x << std::endl;
std::vector<double> vec(cfg.len("array"));
cfg.get( "array", vec.begin(), vec.end());
for( auto&& x : vec) std::cout << x << std::endl;
}
return EXIT_SUCCESS;
}
| 31.851852 | 107 | 0.514419 | [
"vector"
] |
d8a4ca71166e6910652b64b00f1488052a94c90f | 4,228 | cpp | C++ | ixbots/ixbots/IXCobraToSentryBot.cpp | fcojavmc/IXWebSocket | 493b23d4da88f0a49bd7561dd0de692cd5773f19 | [
"BSD-3-Clause"
] | null | null | null | ixbots/ixbots/IXCobraToSentryBot.cpp | fcojavmc/IXWebSocket | 493b23d4da88f0a49bd7561dd0de692cd5773f19 | [
"BSD-3-Clause"
] | null | null | null | ixbots/ixbots/IXCobraToSentryBot.cpp | fcojavmc/IXWebSocket | 493b23d4da88f0a49bd7561dd0de692cd5773f19 | [
"BSD-3-Clause"
] | null | null | null | /*
* IXCobraToSentryBot.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#include "IXCobraToSentryBot.h"
#include "IXCobraBot.h"
#include "IXQueueManager.h"
#include <ixcobra/IXCobraConnection.h>
#include <ixcore/utils/IXCoreLogger.h>
#include <chrono>
#include <sstream>
#include <vector>
namespace ix
{
int64_t cobra_to_sentry_bot(const CobraConfig& config,
const std::string& channel,
const std::string& filter,
const std::string& position,
SentryClient& sentryClient,
bool verbose,
size_t maxQueueSize,
bool enableHeartbeat,
int runtime)
{
CobraBot bot;
bot.setOnBotMessageCallback([&sentryClient](const Json::Value& msg,
const std::string& /*position*/,
const bool verbose,
std::atomic<bool>& throttled,
std::atomic<bool> &
/*fatalCobraError*/) -> bool {
auto ret = sentryClient.send(msg, verbose);
HttpResponsePtr response = ret.first;
if (!response)
{
CoreLogger::warn("Null HTTP Response");
return false;
}
if (verbose)
{
for (auto it : response->headers)
{
CoreLogger::info(it.first + ": " + it.second);
}
CoreLogger::info("Upload size: " + std::to_string(response->uploadSize));
CoreLogger::info("Download size: " + std::to_string(response->downloadSize));
CoreLogger::info("Status: " + std::to_string(response->statusCode));
if (response->errorCode != HttpErrorCode::Ok)
{
CoreLogger::info("error message: " + response->errorMsg);
}
if (response->headers["Content-Type"] != "application/octet-stream")
{
CoreLogger::info("payload: " + response->payload);
}
}
bool success = response->statusCode == 200;
if (!success)
{
CoreLogger::error("Error sending data to sentry: " + std::to_string(response->statusCode));
CoreLogger::error("Body: " + ret.second);
CoreLogger::error("Response: " + response->payload);
// Error 429 Too Many Requests
if (response->statusCode == 429)
{
auto retryAfter = response->headers["Retry-After"];
std::stringstream ss;
ss << retryAfter;
int seconds;
ss >> seconds;
if (!ss.eof() || ss.fail())
{
seconds = 30;
CoreLogger::warn("Error parsing Retry-After header. "
"Using " + retryAfter + " for the sleep duration");
}
CoreLogger::warn("Error 429 - Too Many Requests. ws will sleep "
"and retry after " + retryAfter + " seconds");
throttled = true;
auto duration = std::chrono::seconds(seconds);
std::this_thread::sleep_for(duration);
throttled = false;
}
}
return success;
});
bool useQueue = true;
return bot.run(config,
channel,
filter,
position,
verbose,
maxQueueSize,
useQueue,
enableHeartbeat,
runtime);
}
} // namespace ix
| 35.830508 | 107 | 0.431883 | [
"vector"
] |
d8a7c4eba092fbb89b3790dde4fd0402bec2f17f | 578 | hpp | C++ | src/org/apache/poi/ss/usermodel/ConditionFilterData.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/ConditionFilterData.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/ConditionFilterData.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/usermodel/ConditionFilterData.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct poi::ss::usermodel::ConditionFilterData
: public virtual ::java::lang::Object
{
virtual bool getAboveAverage() = 0;
virtual bool getBottom() = 0;
virtual bool getEqualAverage() = 0;
virtual bool getPercent() = 0;
virtual int64_t getRank() = 0;
virtual int32_t getStdDev() = 0;
// Generated
static ::java::lang::Class *class_();
};
| 26.272727 | 80 | 0.688581 | [
"object"
] |
d8ab0b5b8a13936586421195551b325866be5a6c | 7,869 | cpp | C++ | source/app/cmdparser/cmdparser.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | 5 | 2019-09-14T10:10:18.000Z | 2022-02-18T03:50:23.000Z | source/app/cmdparser/cmdparser.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | null | null | null | source/app/cmdparser/cmdparser.cpp | MatthijsReyers/HexMe | 945acbe8ed0fa48c01bda2f5083b0bba6293007d | [
"MIT"
] | 1 | 2019-10-10T16:23:05.000Z | 2019-10-10T16:23:05.000Z | #include "cmdparser.h"
cmdparser::cmdparser(utils::file& f, app* h): file(f), hexme(h)
{
this->commands["exit"] = &cmdparser::onExit;
this->commands["open"] = &cmdparser::onOpen;
this->commands["goto"] = &cmdparser::onGoto;
this->commands["find"] = &cmdparser::onFind;
this->commands["insert"] = &cmdparser::onInsert;
this->commands["replace"] = &cmdparser::onReplace;
}
std::vector<std::string> cmdparser::lexer(std::string cmd)
{
// Vector to output.
auto res = std::vector<std::string>();
// Remove trailing spaces behind cmd string.
while (cmd.back() == ' ')
cmd.pop_back();
// Parse keywords.
std::stringstream ss(cmd);
std::string segment;
while (std::getline(ss, segment, ' '))
{
// If the segment is a string. (<= Surrounded by "".)
if (segment.length() > 0 && segment[0] == '"') {
// String must also have closing bracket/quote.
if (cmd[cmd.size()-1] != '"')
/* Throw syntax error */
throw std::exception();
// Get full string.
segment = cmd.substr(cmd.find(segment)+1, cmd.size()-1);
segment.pop_back();
// Take care of escaped characters in string.
segment = utils::stringtools::escape(segment);
// Push to output and break while loop.
res.push_back(segment);
break;
}
// Output vector may not include empty items.
if (segment != "")
res.push_back(segment);
}
return res;
}
void cmdparser::onExit(std::vector<std::string>& tokens)
{
hexme->close();
exit(0);
}
void cmdparser::onOpen(std::vector<std::string>& tokens)
{
if (tokens.size() == 1)
throw CmdSyntaxErrorException("Please give a location to go to.");
if (tokens.size() > 2)
throw CmdSyntaxErrorException("Please use the correct syntax: open \"path/to/file.txt\"");
auto newPath = tokens[1];
auto oldPath = file.getPath();
try {
file.close();
file.open(newPath);
}
catch (utils::FailedToOpenFileException &error) {
file.close();
file.open(oldPath);
throw CmdSyntaxErrorException("Could not open file.");
}
}
void cmdparser::onGoto(std::vector<std::string>& tokens)
{
std::string index, format;
int base;
// Something must be given after 'goto'.
if (tokens.size() == 1)
throw CmdSyntaxErrorException("Please give a location to go to.");
else if (tokens.size() == 2)
{
// Get first argument of command.
index = tokens[1];
base = 16;
// File start and end shortcuts.
if (index == "start") {file.moveCursor(0);return;}
else if (index == "end") {file.moveCursor(file.getFileEnd());return;}
else if (index == "hex" || index == "dec")
throw CmdSyntaxErrorException("Please give a number after hex/dec.");
}
else if (tokens.size() == 3)
{
format = tokens[1];
index = tokens[2];
// Hexadecimal and decimal formating.
if (format == "hex")
base = 16;
else if (format == "dec")
base = 10;
// Second arugment must be 'hex' or 'dec'.
else throw CmdSyntaxErrorException("Please use the correct syntax: goto [hex/dec] [number].");
}
// Goto command never has more than 2 arguments.
else throw CmdSyntaxErrorException("Please use the correct syntax: goto [hex/dec] [number].");
try {
// Convert string to unsigned long long.
auto location = std::stoull(index, nullptr, base);
// Location must be inside file.
if (location > file.getFileEnd())
throw CmdSyntaxErrorException("Provided index is located outside of file.");
// Move cursor.
else file.moveCursor(location);
}
catch (std::invalid_argument const &e) {
throw CmdSyntaxErrorException("Number is not in the correct format.");}
catch (std::out_of_range const &e) {
throw CmdSyntaxErrorException("Provided number is too large.");}
}
void cmdparser::onFind(std::vector<std::string>& tokens)
{
if (tokens.size() == 1)
throw CmdSyntaxErrorException("Please give a string to find.");
if (tokens.size() > 3)
throw CmdSyntaxErrorException("Please use the correct syntax: find [first/last/next] \"query\"");
std::string query;
unsigned long long start, stop;
auto cursor = file.getCursorLocation();
// Find first occurence of string.
if (tokens[1] == "first" || tokens.size() == 2)
{
if (tokens.size() == 2) query = tokens[1];
else query = tokens[2];
start = 0;
stop = file.getFileEnd();
}
// Find last occurence of string.
else if (tokens[1] == "last")
{
query = tokens[2];
start = file.getFileEnd();
stop = 0;
}
// Find previous occurence of string.
else if (tokens[1] == "previous")
{
query = tokens[2];
start = file.getCursorLocation();
stop = 0;
}
// Find next occurence of string.
else if (tokens[1] == "next")
{
query = tokens[2];
start = file.getCursorLocation() + 1;
stop = file.getFileEnd() + 1;
}
// Wrong syntax.
else throw CmdSyntaxErrorException("Please use the correct syntax: find [first/last/next] \"query\"");
// Search for string.
for (unsigned long long i = start; i != stop; (start < stop) ? i++ : i--)
{
file.moveCursor(i);
byte current = file.getCurrentByte();
if (current == query[0] && file.getBytesAfterCursor() >= query.size())
{
bool found = true;
for (unsigned long long a = 0; a < query.size() && found; a++)
{
file.moveCursor(i + a);
if (query[a] != file.getCurrentByte())
found = false;
}
// Move cursor to query location and find.
if (found) {
file.moveCursor(i);
return;
}
}
}
// Could not find query.
file.moveCursor(cursor);
throw CmdSyntaxErrorException("Could not find provided query.");
}
void cmdparser::onInsert(std::vector<std::string>& tokens)
{
if (tokens.size() == 1)
throw CmdSyntaxErrorException("Please give a string to insert.");
if (tokens.size() > 2)
throw CmdSyntaxErrorException("Please use the correct syntax: insert \"string\".");
const char* toInsert = tokens[1].c_str();
const int length = tokens[1].length();
// Replace bytes at cursor.
file.insertBytes(toInsert, length);
}
void cmdparser::onReplace(std::vector<std::string>& tokens)
{
if (tokens.size() == 1)
throw CmdSyntaxErrorException("Please give bytes to replace the bytes at cursor with.");
if (tokens.size() > 2)
throw CmdSyntaxErrorException("Please use the correct syntax: replace \"string\".");
const char* newBytes = tokens[1].c_str();
const int length = tokens[1].length();
// Replace bytes at cursor.
file.replaceBytes(newBytes, length);
}
void cmdparser::executeCmd(std::string& cmd)
{
// Spit command up into tokens.
auto tokens = lexer(cmd);
// A command is at least one token long.
if (tokens.size() == 0)
return;
// throw CmdSyntaxErrorException("Please enter a command to execute.");
// Check if given command exists.
else if (commands.find(tokens[0]) != commands.end())
{
std::string name = tokens[0];
method command = commands[name];
(this->*command)(tokens);
}
// Comand does not exist.
else {
throw CmdSyntaxErrorException("That command does not exist.");
}
}
| 29.36194 | 106 | 0.576566 | [
"vector"
] |
d8ace6aa6974426f762ac66a0cbfc68cec3bc923 | 3,956 | cpp | C++ | ScrollBarStyle.cpp | KevinThierauf/SFML_TextBox | 7f2594bea04edb5be17715ccdddd9c9a0cb4d7b3 | [
"MIT"
] | null | null | null | ScrollBarStyle.cpp | KevinThierauf/SFML_TextBox | 7f2594bea04edb5be17715ccdddd9c9a0cb4d7b3 | [
"MIT"
] | null | null | null | ScrollBarStyle.cpp | KevinThierauf/SFML_TextBox | 7f2594bea04edb5be17715ccdddd9c9a0cb4d7b3 | [
"MIT"
] | null | null | null | #include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <algorithm>
#include "ScrollBarStyle.hpp"
#include "ScrollBar.hpp"
namespace sftb {
float ScrollBarStyle::getPrimary(const ScrollBar &scrollBar, const sf::Vector2f &vector) {
return getComponent(scrollBar.isVertical(), vector);
}
float ScrollBarStyle::getContentSize(const ScrollBar &scrollBar) {
return std::max(1.0f, getPrimary(scrollBar, scrollBar.getScrollBarManager().getContentSize()));
}
float ScrollBarStyle::getAssociatedDrawSpace(const ScrollBar &scrollBar) {
return std::max(1.0f, getComponent(!scrollBar.isVertical(), scrollBar.getScrollBarManager().getDrawSpace()));
}
float ScrollBarStyle::getDrawSpace(const ScrollBar &scrollBar) {
return getPrimary(scrollBar, scrollBar.getScrollBarManager().getDrawSpace());
}
void StandardScrollBarStyleBase::draw(sf::RenderTarget &target, sf::RenderStates states, const ScrollBar &scrollBar) const {
// only draw scroll bar if needed
if (getDrawSpace(scrollBar) >= getContentSize(scrollBar)) return;
sf::RectangleShape rectangle;
sf::FloatRect dimensions = getScrollBarDimensions(scrollBar);
rectangle.setPosition(dimensions.getPosition());
rectangle.setSize(dimensions.getSize());
style(rectangle);
target.draw(rectangle);
}
bool StandardScrollBarStyleBase::handleClick(const sf::Vector2f &position, ScrollBar &scrollBar, sf::Mouse::Button button, bool pressed) {
if (button == sf::Mouse::Button::Left) {
if (pressed) {
if (inside(scrollBar, position)) {
scrollBar.setSelected(true);
return true;
}
} else {
scrollBar.setSelected(false);
return true;
}
}
return false;
}
void StandardScrollBarStyleBase::handleMouseMove(const sf::Vector2f ¤t, ScrollBar &scrollBar) {
if (scrollBar.isSelected()) {
scrollBar.setScrollPercent(scrollBar.getScrollPercent() - (getComponent(scrollBar.isVertical(), previous) - getComponent(scrollBar.isVertical(), current)) /
(getMaxScrollBarLength(scrollBar) - getScrollBarLength(scrollBar)));
}
previous = current;
}
sf::FloatRect StandardScrollBarStyleBase::getScrollBarDimensions(const ScrollBar &scrollBar) const {
if (scrollBar.isVertical())
return sf::FloatRect(getAssociatedDrawSpace(scrollBar) - thickness, getScrollBarPosition(scrollBar), thickness, getScrollBarLength(scrollBar));
else return sf::FloatRect(getScrollBarPosition(scrollBar), getAssociatedDrawSpace(scrollBar) - thickness, getScrollBarLength(scrollBar), thickness);
}
float StandardScrollBarStyleBase::getMaxScrollBarLength(const ScrollBar &scrollBar) {
// subtract thickness of other scrollbar so they don't overlap
return getDrawSpace(scrollBar) - scrollBar.getOpposite().getScrollBarStyle().getReservedWidth();
}
float StandardScrollBarStyleBase::getScrollBarLength(const ScrollBar &scrollBar) {
float size = getContentSize(scrollBar);
float available = getMaxScrollBarLength(scrollBar);
if (size <= 0 || available <= 0) return 0;
return std::max(MIN_SCROLL_BAR_LENGTH, (available / size * available));
}
float StandardScrollBarStyleBase::getScrollBarPosition(const ScrollBar &scrollBar) {
return scrollBar.getScrollPercent() * (getMaxScrollBarLength(scrollBar) - getScrollBarLength(scrollBar));
}
const sf::Color StandardScrollBarStyle::DEFAULT_SCROLL_BAR_COLOR = sf::Color(0, 0, 0); // NOLINT(cert-err58-cpp)
void StandardScrollBarStyle::style(sf::RectangleShape &shape) const {
shape.setFillColor(scrollBarColor);
}
} | 43.955556 | 168 | 0.684024 | [
"shape",
"vector"
] |
d8add73aec5e6eb4689cc2d0f6976710627f6d0d | 18,186 | cpp | C++ | ufora/FORA/CompilerCache/OnDiskCompilerStore.cpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/FORA/CompilerCache/OnDiskCompilerStore.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/FORA/CompilerCache/OnDiskCompilerStore.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015-2016 Ufora 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 "CompilerCacheSerializer.hpp"
#include "MemoizableObject.hppml"
#include "OnDiskCompilerStore.hpp"
#include "../Core/ClassMediator.hppml"
#include "../Core/MemoryPool.hpp"
#include "../../core/Clock.hpp"
#include "../../core/Memory.hpp"
#include "../../core/serialization/IFileDescriptorProtocol.hpp"
#include "../../core/serialization/INoncontiguousByteBlockProtocol.hpp"
#include "../../core/serialization/OFileDescriptorProtocol.hpp"
#include "../../core/serialization/ONoncontiguousByteBlockProtocol.hpp"
#include <fstream>
#include <fcntl.h>
const string OnDiskCompilerStore::INDEX_FILE_EXTENSION = ".idx";
const string OnDiskCompilerStore::DATA_FILE_EXTENSION = ".dat";
const string OnDiskCompilerStore::STORE_FILE_PREFIX = "CompilerStore";
const string OnDiskCompilerStore::MAP_FILE_PREFIX = "ClassMediatorToCFG";
const string OnDiskCompilerStore::MAP_FILE_EXTENSION = ".map";
void removeIfExists(const fs::path& file)
{
if (fs::exists(file))
fs::remove(file);
}
inline
Nullable<fs::path> getFileWithNewExtension(
const fs::path& file,
const string& currentExtension,
const string& newExtension)
{
const string& fileStr = file.string();
const string suffix = fileStr.substr(
fileStr.size()- currentExtension.size(),
currentExtension.size());
if (suffix.compare(currentExtension))
return null();
string newFileStr =
fileStr.substr(
0,
fileStr.size() - currentExtension.size()
)
+ newExtension;
return null() << fs::path(newFileStr);
}
Nullable<fs::path> OnDiskCompilerStore::getDataFileFromIndexFile(const fs::path& indexFile)
{
return getFileWithNewExtension(indexFile, INDEX_FILE_EXTENSION, DATA_FILE_EXTENSION);
}
Nullable<fs::path> OnDiskCompilerStore::getIndexFileFromDataFile(const fs::path& dataFile)
{
return getFileWithNewExtension(dataFile, DATA_FILE_EXTENSION, INDEX_FILE_EXTENSION);
}
template<class T>
void logDebugMap(T& map) {
LOG_DEBUG << "Printing Index:";
for(auto term: map)
{
LOG_DEBUG << prettyPrintString(term.first)
<< " -> " << prettyPrintString(term.second);
}
}
shared_ptr<vector<char> > OnDiskCompilerStore::loadAndValidateFile(const fs::path& file)
{
if (!fs::exists(file) || !fs::is_regular_file(file))
return shared_ptr<vector<char> >();
if (mStoreFilesRead.find(file) != mStoreFilesRead.end())
{
LOG_ERROR << "File already loaded: " << file.string();
return shared_ptr<vector<char> >();
}
ifstream fin(file.string(), ios::in | ios::binary);
if (!fin.is_open())
return shared_ptr<vector<char> >();
hash_type storedChecksum;
constexpr auto checksumSize = sizeof(hash_type);
vector<char> checksumBuffer(checksumSize);
char* checksumPtr = &checksumBuffer[0];
fin.read(checksumPtr, checksumSize);
if (!fin)
{
fin.close();
return shared_ptr<vector<char> >();
}
IMemProtocol protocol(checksumPtr, checksumBuffer.size());
{
IBinaryStream stream(protocol);
CompilerCacheDuplicatingDeserializer deserializer(
stream,
MemoryPool::getFreeStorePool(),
PolymorphicSharedPtr<VectorDataMemoryManager>()
);
deserializer.deserialize(storedChecksum);
}
const uword_t bufferSize = fs::file_size(file) - checksumSize;
shared_ptr<vector<char> > result(new vector<char>(bufferSize));
char* bufPtr = &(*result)[0];
// 2. read rest
double t0 = curClock();
fin.read(bufPtr, bufferSize);
mPerformanceCounters.addDiskLookupTime(curClock()-t0);
if (!fin)
{
fin.close();
return shared_ptr<vector<char> >();
}
// else
fin.close();
hash_type computedChecksum = hashValue(*result);
if (computedChecksum != storedChecksum)
{
return shared_ptr<vector<char> >();
}
mStoreFilesRead.insert(file);
return result;
}
void getFilesWithExtension(const fs::path& rootDir, const string& ext, vector<fs::path>& outFiles)
{
if(!fs::exists(rootDir) || !fs::is_directory(rootDir)) return;
fs::recursive_directory_iterator it(rootDir);
fs::recursive_directory_iterator endit;
while(it != endit)
{
if(fs::is_regular_file(*it) && it->path().extension() == ext)
outFiles.push_back(it->path().filename());
++it;
}
}
bool OnDiskCompilerStore::tryRebuildIndexFromData(
const fs::path& rootDir,
const fs::path& indexFile,
const fs::path& dataFile)
{
// TODO: implement
return false;
}
bool OnDiskCompilerStore::initializeStoreIndex(const fs::path& rootDir, const fs::path& indexFile)
{
if (!fs::exists(rootDir / indexFile))
return false;
auto dataFile = getDataFileFromIndexFile(indexFile);
if (!dataFile)
{
// Do *not* remove indexFile. It could be a useful non-index file.
return false;
}
if (!fs::exists(rootDir / *dataFile))
{
LOG_WARN << "Removing index file '" << indexFile.string()
<< "' because the corresponding data file could not be found.";
removeIfExists(rootDir / indexFile);
return false;
}
shared_ptr<vector<char> > dataBuffer = loadAndValidateFile(rootDir/indexFile);
if (!dataBuffer)
{
bool res = tryRebuildIndexFromData(rootDir, indexFile, *dataFile);
if (!res)
{
LOG_WARN << "Failed to load compiler cache index file: " << indexFile.string();
removeIfExists(rootDir / indexFile);
removeIfExists(rootDir / *dataFile);
mStoreFilesRead.erase(*dataFile);
}
return res;
}
char* dataPtr = &(*dataBuffer)[0];
IMemProtocol protocol(dataPtr, dataBuffer->size());
{
IBinaryStream stream(protocol);
CompilerCacheDuplicatingDeserializer deserializer(
stream,
MemoryPool::getFreeStorePool(),
PolymorphicSharedPtr<VectorDataMemoryManager>()
);
uword_t entryCount = 0;
deserializer.deserialize(entryCount);
for(int i = 0; i < entryCount; ++i)
{
ObjectIdentifier objId;
deserializer.deserialize(objId);
mLocationIndex.tryInsert(objId, *dataFile);
}
}
return true;
}
void OnDiskCompilerStore::initializeStoreIndex()
{
vector<fs::path> indexFiles;
getFilesWithExtension(mBasePath, INDEX_FILE_EXTENSION, indexFiles);
for (auto& indexFile: indexFiles)
{
initializeStoreIndex(mBasePath, indexFile);
}
}
bool OnDiskCompilerStore::initializeMap(const fs::path& rootDir, const fs::path& mapFile)
{
if (!fs::exists(rootDir / mapFile))
return false;
shared_ptr<vector<char> > dataBuffer = loadAndValidateFile(rootDir/mapFile);
if (!dataBuffer)
{
LOG_WARN << "Failed to load compiler cache map file: " << mapFile.string();
removeIfExists(rootDir / mapFile);
return false;
}
char* dataPtr = &(*dataBuffer)[0];
IMemProtocol protocol(dataPtr, dataBuffer->size());
{
IBinaryStream stream(protocol);
CompilerCacheDuplicatingDeserializer deserializer(
stream,
MemoryPool::getFreeStorePool(),
PolymorphicSharedPtr<VectorDataMemoryManager>()
);
uword_t entryCount = 0;
deserializer.deserialize(entryCount);
for(int i = 0; i < entryCount; ++i)
{
CompilerMapKey key;
deserializer.deserialize(key);
ObjectIdentifier objId;
deserializer.deserialize(objId);
mMap[key] = objId;
}
}
return true;
}
bool OnDiskCompilerStore::initializeMap()
{
vector<fs::path> files;
getFilesWithExtension(mBasePath, MAP_FILE_EXTENSION, files);
bool atLeastOneSucceded = false;
for (auto& file: files)
atLeastOneSucceded |= initializeMap(mBasePath, file);
return atLeastOneSucceded;
}
fs::path OnDiskCompilerStore::getFreshMapFile()
{
static uint64_t index = 0;
for (; true; ++index)
{
stringstream mapSS;
mapSS << MAP_FILE_PREFIX << index << MAP_FILE_EXTENSION;
string mapFileStr;
mapSS >> mapFileStr;
fs::path mapFile(mapFileStr);
if (fs::exists(mBasePath / mapFile))
continue;
return mapFile;
}
}
pair<fs::path, fs::path> OnDiskCompilerStore::getFreshStoreFilePair()
{
static uint64_t index = 0;
for(; true; ++index)
{
stringstream dataSS;
dataSS << STORE_FILE_PREFIX << index << DATA_FILE_EXTENSION;
string dataFileStr;
dataSS >> dataFileStr;
fs::path dataFile(dataFileStr);
if (fs::exists(mBasePath / dataFile))
continue;
stringstream indexSS;
indexSS << STORE_FILE_PREFIX << index << INDEX_FILE_EXTENSION;
string indexFileStr;
indexSS >> indexFileStr;
fs::path indexFile(indexFileStr);
if (fs::exists(mBasePath / indexFile))
continue;
return make_pair(dataFile, indexFile);
}
}
void OnDiskCompilerStore::cleanUpLocationIndex(const fs::path& problematicDataFile)
{
LOG_DEBUG << "Cleaning up Index from problematic data file: "
<< problematicDataFile.string();
mLocationIndex.dropValue(problematicDataFile);
removeIfExists(mBasePath / problematicDataFile);
mStoreFilesRead.erase(mBasePath / problematicDataFile);
auto indexFile = getIndexFileFromDataFile(problematicDataFile);
if (indexFile)
removeIfExists(mBasePath / *indexFile);
}
bool OnDiskCompilerStore::loadDataFromDisk(const fs::path& relativePathToFile)
{
fs::path absolutePathToFile = mBasePath / relativePathToFile;
if (!fs::exists(absolutePathToFile) || !fs::is_regular_file(absolutePathToFile))
{
cleanUpLocationIndex(relativePathToFile);
return false;
}
shared_ptr<vector<char> > dataBuffer = loadAndValidateFile(absolutePathToFile);
if (!dataBuffer)
{
cleanUpLocationIndex(relativePathToFile);
return false;
}
lassert(dataBuffer);
char* dataPtr = &(*dataBuffer)[0];
IMemProtocol protocol(dataPtr, dataBuffer->size());
try
{
IBinaryStream stream(protocol);
CompilerCacheMemoizingBufferedDeserializer deserializer(
stream,
MemoryPool::getFreeStorePool(),
PolymorphicSharedPtr<VectorDataMemoryManager>(),
*this
);
uword_t entryCount;
double t0 = curClock();
deserializer.deserialize(entryCount);
for (int i = 0; i < entryCount; ++i)
{
ObjectIdentifier objId;
MemoizableObject obj;
deserializer.deserialize(objId);
deserializer.deserialize(obj);
mSavedObjectMap.insert(make_pair(objId, obj));
}
mPerformanceCounters.addDeserializationTime(curClock()-t0);
auto memoizedRestoredObjects = deserializer.getRestoredObjectMap();
if (memoizedRestoredObjects)
mSavedObjectMap.insert(
memoizedRestoredObjects->begin(),
memoizedRestoredObjects->end());
}
catch (std::logic_error& e)
{
LOG_ERROR << e.what();
return false;
}
return true;
}
bool OnDiskCompilerStore::checksumAndStore(const NoncontiguousByteBlock& data, fs::path file)
{
ofstream ofs(file.string(), ios::out | ios::binary | ios::trunc);
if (!ofs.is_open())
{
LOG_ERROR << "Failed to open file for writing: " << file.string();
return false;
}
hash_type checksum = data.hash();
ONoncontiguousByteBlockProtocol protocol;
{
OBinaryStream stream(protocol);
CompilerCacheDuplicatingSerializer serializer(stream);
serializer.serialize(checksum);
}
auto serializedChecksum = protocol.getData();
if (!serializedChecksum)
{
LOG_ERROR << "Failed to serialize checksum";
return false;
}
double t0 = curClock();
ofs << *serializedChecksum;
ofs << data;
mPerformanceCounters.addDiskStoreTime(curClock()-t0);
ofs.close();
return true;
}
template<class Key, class Value>
bool OnDiskCompilerStore::serializeAndStoreMap(
const map<Key, Value>& map,
const fs::path& file,
bool justTheIndex)
{
ONoncontiguousByteBlockProtocol protocol;
{
OBinaryStream stream(protocol);
CompilerCacheDuplicatingSerializer serializer(stream);
uword_t entryCount = map.size();
double t0 = curClock();
serializer.serialize(entryCount);
for(auto& pair: map)
{
serializer.serialize(pair.first);
if (!justTheIndex)
serializer.serialize(pair.second);
}
mPerformanceCounters.addSerializationTime(curClock()-t0);
}
auto serializedData = protocol.getData();
if (!serializedData)
{
LOG_ERROR << "Failed to serialize Compiler-Cache index";
return false;
}
return checksumAndStore(*serializedData, file);
}
bool OnDiskCompilerStore::flushToDisk()
{
bool noErrorSoFar = true;
auto pair = getFreshStoreFilePair();
const fs::path& dataFile = mBasePath / pair.first;
const fs::path& indexFile = mBasePath / pair.second;
// serialize mUnsavedObjectMap
shared_ptr<map<ObjectIdentifier, MemoizableObject> > storedObjects;
{
ONoncontiguousByteBlockProtocol protocol;
{
OBinaryStream stream(protocol);
CompilerCacheMemoizingBufferedSerializer serializer(stream, *this);
double t0 = curClock();
serializer.serialize(mUnsavedObjectMap.size());
for (auto& pair: mUnsavedObjectMap)
{
const ObjectIdentifier& curId = pair.first;
const MemoizableObject& curObj = pair.second;
serializer.serialize(curId);
serializer.serialize(curObj);
}
double time = curClock() - t0;
mPerformanceCounters.addSerializationTime(time);
mUnsavedObjectMap.clear();
storedObjects = serializer.getStoredObjectMap();
if (storedObjects)
{
mSavedObjectMap.insert(storedObjects->begin(), storedObjects->end());
}
}
// write .dat file
auto serializedData = protocol.getData();
if (!serializedData)
{
LOG_ERROR << "Failed to serialize Compiler-Cache data";
return false;
}
noErrorSoFar &= checksumAndStore(*serializedData, dataFile);
}
if (storedObjects)
noErrorSoFar &= serializeAndStoreMap(*storedObjects, indexFile, true);
// write .map file
fs::path newMapFile = getFreshMapFile();
bool res = serializeAndStoreMap(mMap, mBasePath / newMapFile);
if (res)
{ // find and delete all other .map files
vector<fs::path> mapFiles;
getFilesWithExtension(mBasePath, MAP_FILE_EXTENSION, mapFiles);
for (auto& mapFile: mapFiles)
if (mapFile != newMapFile)
removeIfExists(mBasePath / mapFile);
}
noErrorSoFar &= res;
return noErrorSoFar;
}
OnDiskCompilerStore::OnDiskCompilerStore(fs::path inBasePath) :
mBasePath(inBasePath)
{
if (!fs::exists(mBasePath))
fs::create_directories(mBasePath);
initializeStoreIndex();
initializeMap();
validateIndex();
}
bool OnDiskCompilerStore::containsOnDisk(const ObjectIdentifier& inKey) const
{
if (mSavedObjectMap.find(inKey) != mSavedObjectMap.end() ||
mLocationIndex.hasKey(inKey))
return true;
else
return false;
}
void OnDiskCompilerStore::validateIndex()
{
std::set<fs::path> valuesToDrop;
for (auto term : mLocationIndex.getValueToKeys())
{
if (!fs::exists(mBasePath / term.first))
valuesToDrop.insert(term.first);
}
for (auto value : valuesToDrop)
{
mLocationIndex.dropValue(value);
LOG_WARN << "Dropping Compiler Store object IDs to file '"
<< value.string() << "'";
}
}
template<class T>
Nullable<T> OnDiskCompilerStore::lookupInMemory(const ObjectIdentifier& inKey) const
{
mPerformanceCounters.incrMemLookups();
auto it = mSavedObjectMap.find(inKey);
if (it != mSavedObjectMap.end())
return null() << (*it).second.extract<T>();
it = mUnsavedObjectMap.find(inKey);
if (it != mUnsavedObjectMap.end())
return null() << (*it).second.extract<T>();
return null();
}
template<class T>
Nullable<T> OnDiskCompilerStore::lookup(const ObjectIdentifier& inKey)
{
auto res = lookupInMemory<T>(inKey);
if (res)
return res;
auto file = mLocationIndex.tryGetValue(inKey);
if (!file)
return null();
if (!loadDataFromDisk(*file))
{
LOG_WARN << "Unable to load Compiler Cache data from file '"
<< (mBasePath / *file).string() << "'";
return null();
}
res = lookupInMemory<T>(inKey);
return res;
}
template
Nullable<Expression> OnDiskCompilerStore::lookup<Expression>(const ObjectIdentifier& inKey);
template
Nullable<Type> OnDiskCompilerStore::lookup<Type>(const ObjectIdentifier& inKey);
template
Nullable<JOV> OnDiskCompilerStore::lookup<JOV>(const ObjectIdentifier& inKey);
template<class T>
void OnDiskCompilerStore::store(const ObjectIdentifier& inKey, const T& inValue)
{
auto findIt = mSavedObjectMap.find(inKey);
bool inSavedMap = false;
if (findIt != mSavedObjectMap.end())
{
auto& existingValue =(*findIt).second.extract<T>();
if(existingValue == inValue)
{
inSavedMap = true;
// don't return, proceed to check if (key, value) pair exists on disk as well
}
else
{
// found key that maps to different values
LOG_ERROR << "Compiler-Cache key maps to different values:\n"
<< "Key in Compiler-Cache: " << prettyPrintString(inKey)
<< "Value in Compiler-Cache:\n" << prettyPrintString(existingValue)
<< "Value to be inserted (which has identical key):\n"
<< prettyPrintString(inValue)
;
lassert(false);
}
}
if (mLocationIndex.hasKey(inKey))
{
if (!inSavedMap)
mSavedObjectMap.insert(
make_pair(inKey, MemoizableObject::makeMemoizableObject(inValue))
);
return; // already exists // TODO: perhaps check that the location is valid
}
auto value = make_pair(inKey, MemoizableObject::makeMemoizableObject(inValue));
auto insRes = mUnsavedObjectMap.insert(value);
// TEMP SOLUTION TO FLUSHING
if(mUnsavedObjectMap.size() > 5)
flushToDisk();
}
template
void OnDiskCompilerStore::store<MemoizableObject>(const ObjectIdentifier& inKey, const MemoizableObject& inValue);
Nullable<ControlFlowGraph> OnDiskCompilerStore::get(const CompilerMapKey& inKey)
{
ControlFlowGraph tr;
auto objIt = mMap.find(inKey);
if (objIt == mMap.end())
{
return null();
}
const ObjectIdentifier objId = (*objIt).second;
auto res = lookup<ControlFlowGraph>(objId);
return res;
}
void OnDiskCompilerStore::set(const CompilerMapKey& inKey, const ControlFlowGraph& inCFG)
{
ObjectIdentifier objId(makeObjectIdentifier(inCFG));
mMap.insert(make_pair(inKey, objId));
store(objId, inCFG);
}
| 26.510204 | 114 | 0.71786 | [
"object",
"vector"
] |
d8c518fdd8cf624923627b7c93309d496fda3d78 | 1,811 | cpp | C++ | tests/MaximalSquareTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | tests/MaximalSquareTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | tests/MaximalSquareTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "catch.hpp"
#include "MaximalSquare.hpp"
TEST_CASE("Maximal Square") {
MaximalSquare s;
SECTION("Sample test") {
vector<vector<char>> matrix{
{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}
};
REQUIRE(s.maximalSquare(matrix) == 4);
}
SECTION("Single item test") {
vector<vector<char>> matrix{
{'1'}
};
REQUIRE(s.maximalSquare(matrix) == 1);
}
SECTION("All zeros test") {
vector<vector<char>> matrix{
{'0', '0', '0', '0', '0'},
{'0', '0', '0', '0', '0'},
{'0', '0', '0', '0', '0'},
{'0', '0', '0', '0', '0'}
};
REQUIRE(s.maximalSquare(matrix) == 0);
}
SECTION("Normal tests") {
vector<vector<char>> matrix1{
{'1', '0', '1', '1', '0'},
{'1', '1', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}
};
REQUIRE(s.maximalSquare(matrix1) == 4);
vector<vector<char>> matrix2{
{'0', '0', '0', '1'},
{'1', '1', '0', '1'},
{'1', '1', '1', '1'},
{'0', '1', '1', '1'},
{'0', '1', '1', '1'}
};
REQUIRE(s.maximalSquare(matrix2) == 9);
vector<vector<char>> matrix3{
{'0', '1', '1', '0', '1'},
{'1', '1', '0', '1', '0'},
{'0', '1', '1', '1', '0'},
{'1', '1', '1', '1', '0'},
{'1', '1', '1', '1', '1'},
{'0', '0', '0', '0', '0'}
};
REQUIRE(s.maximalSquare(matrix3) == 9);
}
}
| 31.224138 | 47 | 0.312535 | [
"vector"
] |
d8c5454c8d4137d70b9c4c9dea3a15d71827235b | 2,247 | cpp | C++ | client/cpp-tizen/src/VersionResponse.cpp | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | null | null | null | client/cpp-tizen/src/VersionResponse.cpp | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | 70 | 2021-11-03T11:38:21.000Z | 2022-03-31T16:23:30.000Z | client/cpp-tizen/src/VersionResponse.cpp | KaNaDaAT/java-spring-template | 451bb58563bfcdbc3fe735f2e95ea52a3cf9e76e | [
"Unlicense"
] | 1 | 2021-11-11T13:06:13.000Z | 2021-11-11T13:06:13.000Z | #include <map>
#include <cstdlib>
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "Helpers.h"
#include "VersionResponse.h"
using namespace std;
using namespace Tizen::ArtikCloud;
VersionResponse::VersionResponse()
{
//__init();
}
VersionResponse::~VersionResponse()
{
//__cleanup();
}
void
VersionResponse::__init()
{
//version = std::string();
//stable = bool(false);
}
void
VersionResponse::__cleanup()
{
//if(version != NULL) {
//
//delete version;
//version = NULL;
//}
//if(stable != NULL) {
//
//delete stable;
//stable = NULL;
//}
//
}
void
VersionResponse::fromJson(char* jsonStr)
{
JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL));
JsonNode *node;
const gchar *versionKey = "version";
node = json_object_get_member(pJsonObject, versionKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&version, node, "std::string", "");
} else {
}
}
const gchar *stableKey = "stable";
node = json_object_get_member(pJsonObject, stableKey);
if (node !=NULL) {
if (isprimitive("bool")) {
jsonToValue(&stable, node, "bool", "");
} else {
}
}
}
VersionResponse::VersionResponse(char* json)
{
this->fromJson(json);
}
char*
VersionResponse::toJson()
{
JsonObject *pJsonObject = json_object_new();
JsonNode *node;
if (isprimitive("std::string")) {
std::string obj = getVersion();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *versionKey = "version";
json_object_set_member(pJsonObject, versionKey, node);
if (isprimitive("bool")) {
bool obj = getStable();
node = converttoJson(&obj, "bool", "");
}
else {
}
const gchar *stableKey = "stable";
json_object_set_member(pJsonObject, stableKey, node);
node = json_node_alloc();
json_node_init(node, JSON_NODE_OBJECT);
json_node_take_object(node, pJsonObject);
char * ret = json_to_string(node, false);
json_node_free(node);
return ret;
}
std::string
VersionResponse::getVersion()
{
return version;
}
void
VersionResponse::setVersion(std::string version)
{
this->version = version;
}
bool
VersionResponse::getStable()
{
return stable;
}
void
VersionResponse::setStable(bool stable)
{
this->stable = stable;
}
| 16.522059 | 80 | 0.679128 | [
"object"
] |
d8c7315ddb457f51ef1f724f1380de691ca00b6c | 19,228 | hh | C++ | src/ProcIO2.hh | glennklockwood/procmon | c6e67d63e7c9c24f85a46b6d8965b8c615097edc | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/ProcIO2.hh | glennklockwood/procmon | c6e67d63e7c9c24f85a46b6d8965b8c615097edc | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/ProcIO2.hh | glennklockwood/procmon | c6e67d63e7c9c24f85a46b6d8965b8c615097edc | [
"BSD-3-Clause-LBNL"
] | null | null | null | /*******************************************************************************
procmon, Copyright (c) 2014, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
If you have questions about your rights to use or distribute this software,
please contact Berkeley Lab's Technology Transfer Department at TTD@lbl.gov.
The LICENSE file in the root directory of the source code archive describes the
licensing and distribution rights and restrictions on this software.
Author: Douglas Jacobsen <dmj@nersc.gov>
*******************************************************************************/
#ifndef __PROCIO2_HH_
#define __PROCIO2_HH_
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <algorithm>
#include <exception>
#include <string>
#include <map>
#include <unordered_map>
#include <vector>
#include <memory>
#include <iostream>
#ifdef USE_HDF5
#include "hdf5.h"
#endif /* USE_HDF5 */
#ifdef USE_AMQP
#include <amqp_tcp_socket.h>
#include <amqp_framing.h>
#endif
#include "ProcData.hh"
#define AMQP_BUFFER_SIZE 3145728 /* 3 MB */
#define TEXT_BUFFER_SIZE 8192 /* 8 kB */
using namespace std;
namespace pmio2 {
//! Flag values to determine IO access mode
enum IoMode {
MODE_READ = 0, //!< Read-only access
MODE_WRITE = 1, //!< Write access
MODE_INVALID = 2, //!< Invalid mode
};
//! The metadata context of collected/monitored data
struct Context {
string system; //!< Overall system where data were collected
string hostname; //!< Hostname where data were collected
string identifier; //!< Primary tag
string subidentifier; //!< Secondary tag
string contextString; //!< Automatically generated summary string
Context() {
}
Context(const string &_system, const string &_hostname,
const string &_identifier, const string &_subidentifier)
{
size_t endPos = _system.find('.');
endPos = endPos == string::npos ? _system.size() : endPos;
system = string(_system, 0, endPos);
endPos = _hostname.find('.');
endPos = endPos == string::npos ? _hostname.size() : endPos;
hostname = string(_hostname, 0, endPos);
endPos = _identifier.find('.');
endPos = endPos == string::npos ? _identifier.size() : endPos;
identifier = string(_identifier, 0, endPos);
endPos = _subidentifier.find('.');
endPos = endPos == string::npos ? _subidentifier.size() : endPos;
subidentifier = string(_subidentifier, 0, endPos);
contextString = system + "." + hostname + "." + identifier + "." + subidentifier;
}
bool operator==(const Context &other) const {
return contextString == other.contextString;
}
};
struct DatasetContext {
Context context;
string datasetName;
DatasetContext(const Context& _context, const string& _datasetName):
context(_context), datasetName(_datasetName)
{
}
bool operator==(const DatasetContext& other) const {
return context == other.context && datasetName == other.datasetName;
}
};
};
namespace std {
template <>
struct hash<pmio2::Context> {
size_t operator()(const pmio2::Context &k) const {
return hash<string>()(k.contextString);
}
};
template <>
struct hash<pmio2::DatasetContext> {
size_t operator()(const pmio2::DatasetContext &k) const {
return (hash<pmio2::Context>()(k.context) ^ (hash<string>()(k.datasetName) << 1)) >> 1;
}
};
}
namespace pmio2 {
class Dataset;
class DatasetFactory {
public:
virtual shared_ptr<Dataset> operator()() = 0;
virtual ~DatasetFactory() { }
};
class IoMethod {
public:
IoMethod() {
contextSet = false;
contextOverride = false;
}
virtual ~IoMethod() { }
bool setContext(const string& _system, const string& _hostname, const string& _identifier, const string& _subidentifier) {
Context context(_system, _hostname, _identifier, _subidentifier);
setContext(context);
}
virtual bool setContext(const Context &context) {
this->context = context;
return true;
}
virtual const Context &getContext() {
return context;
}
virtual bool setContextOverride(bool _override) {
contextOverride = _override;
}
virtual const bool getContextOverride() const {
return contextOverride;
}
virtual bool addDataset(const string &dsName, shared_ptr<DatasetFactory> dsGen) {
auto ds = find_if(
registeredDatasets.begin(),
registeredDatasets.end(),
[dsName](pair<string,shared_ptr<DatasetFactory> >& e) { return dsName == e.first; }
);
if (ds == registeredDatasets.end()) {
registeredDatasets.emplace_back(dsName, dsGen);
return true;
}
return false;
}
virtual bool addDatasetContext(shared_ptr<Dataset> ptr, const Context &context, const string &dsetName) {
DatasetContext key(context, dsetName);
dsMap[key] = ptr;
return true;
}
virtual const bool writable() const = 0;
protected:
bool contextSet;
bool contextOverride;
Context context;
unordered_map<DatasetContext, shared_ptr<Dataset> > dsMap;
unordered_map<string, shared_ptr<Dataset> > currentDatasets;
vector<pair<string,shared_ptr<DatasetFactory> > > registeredDatasets;
};
class Dataset : public enable_shared_from_this<Dataset> {
public:
Dataset(shared_ptr<IoMethod> _ioMethod, const string &dsName) {
ioMethod = _ioMethod;
}
virtual ~Dataset() { }
protected:
shared_ptr<IoMethod> ioMethod;
};
/*
class TextIO : public IoMethod {
public:
TextIO(const string& _filename, IoMode _mode);
~TextIO();
private:
int fill_buffer();
string filename;
IoMode mode;
FILE *filePtr;
char *sPtr, *ePtr, *ptr;
char buffer[TEXT_BUFFER_SIZE];
};
*/
#ifdef USE_HDF5
class Hdf5Io;
template <class pmType>
struct Hdf5TypeFactory {
hid_t operator()(shared_ptr<Hdf5Io> io) {
return -1;
}
};
template <class pmType>
class Hdf5Type {
public:
Hdf5Type(shared_ptr<Hdf5Io> io) {
type = initializeType(io);
}
Hdf5Type(shared_ptr<Hdf5Io> io, Hdf5TypeFactory<pmType>& factory) {
type = factory(io);
}
~Hdf5Type() {
if (set) {
H5Tclose(type);
set = false;
}
}
const hid_t getType() {
return type;
}
protected:
bool set;
hid_t type;
hid_t initializeType(shared_ptr<Hdf5Io> io);
};
class Hdf5Group {
public:
Hdf5Group(Hdf5Io &hdf5File, const string &groupName);
~Hdf5Group() {
H5Gclose(group);
}
const hid_t getGroup() {
return group;
}
private:
hid_t group;
bool set;
};
template <class pmType>
class Hdf5Dataset: public Dataset {
public:
Hdf5Dataset(
shared_ptr<Hdf5Io> _ioMethod,
shared_ptr<Hdf5Type<pmType> > _h5type,
unsigned int _maxSize, // 0 for unlimited
unsigned int _blockSize, // 0 for non-chunked data
unsigned int _zipLevel,
const string &_dsName
);
~Hdf5Dataset() {
if (size_id >= 0) {
H5Aclose(size_id);
}
if (dataset >= 0) {
H5Dclose(dataset);
}
}
size_t write(pmType *start, pmType *end, size_t start_id = 0, bool append = true);
size_t read(pmType *start, size_t maxRead, size_t start_id = 0);
inline const size_t howmany() const { return size; }
protected:
shared_ptr<Hdf5Type<pmType> > type;
shared_ptr<Hdf5Group> group;
string dsName;
int zipLevel;
hid_t dataset;
hid_t size_id;
unsigned int blockSize;
unsigned int maxSize;
size_t size;
time_t lastUpdate;
size_t initializeDataset();
};
template <class pmType>
class Hdf5DatasetFactory : public DatasetFactory {
public:
Hdf5DatasetFactory(
shared_ptr<Hdf5Io> _ioMethod,
shared_ptr<Hdf5Type<pmType> > _h5type,
unsigned int _maxSize,
unsigned int _blockSize,
unsigned int _zipLevel,
const string &_dsName
):
ioMethod(_ioMethod), h5type(_h5type), maxSize(_maxSize),
blockSize(_blockSize), zipLevel(_zipLevel), dsName(_dsName)
{ }
shared_ptr<Dataset> operator()() {
shared_ptr<Dataset> ptr(new Hdf5Dataset<pmType>(
ioMethod, h5type, maxSize, blockSize, zipLevel, dsName
));
return ptr;
}
private:
shared_ptr<Hdf5Io> ioMethod;
shared_ptr<Hdf5Type<pmType> > h5type;
unsigned int maxSize;
unsigned int blockSize;
unsigned int zipLevel;
string dsName;
};
class Hdf5Io : public IoMethod {
friend class Hdf5Type<class T>;
friend class Hdf5Group;
public:
Hdf5Io(const string& filename, IoMode mode);
~Hdf5Io();
virtual bool setContext(const Context &context);
bool metadataSetString(const char*, const char*);
bool metadataSetUint(const char*, unsigned long);
bool metadataGetString(const char*, char**);
bool metadataGetUint(const char*, unsigned long*);
template <class pmType>
size_t write(const string &dsName, pmType *start, pmType *end, size_t start_id = 0, bool append = true);
template <class pmType>
size_t read(const string &dsName, pmType *start, size_t count, size_t start_id = 0);
template <class pmType>
size_t read(const string &dsName, pmType *start, size_t count) {
return read(dsName, start, count, 0);
}
template <class pmType>
size_t howmany(const string &dsName);
virtual inline const bool writable() const {
if (mode == IoMode::MODE_WRITE) {
return true;
}
}
const vector<string>& getGroups();
const shared_ptr<Hdf5Group> getCurrentGroup() {
return group;
}
void flush();
void trimDatasets(time_t cutoff);
protected:
void initializeTypes();
string filename;
IoMode mode;
hid_t file;
hid_t root;
unordered_map<Context,shared_ptr<Hdf5Group> > groups;
shared_ptr<Hdf5Group> group;
public:
/* identifiers for string types */
hid_t strType_exeBuffer;
hid_t strType_buffer;
hid_t strType_idBuffer;
hid_t strType_variable;
};
#endif
#ifdef USE_AMQP_NEW
template <typename pmType> bool amqpEncode(const pmType *, const pmType *, string &);
template <typename pmType> size_t amqpDecode(const string &, pmType **);
template <typename pmType>
class AmqpDataset : public Dataset {
public:
AmqpDataset(
shared_ptr<AmqpIo> _amqp,
const Context &context,
const string &dsName
);
AmqpDataset(
shared_ptr<AmqpIo> _amqp,
const Context &context,
const string &dsName,
function<int(pmType *, size_t n) streamRead_cb
);
virtual ~AmqpDataset();
size_t write(pmType *start, pmType *end);
private:
};
class AmqpIo : public IoMethod {
public:
AmqpIo(
const string &_mqServer, int _port, const string &_mqVHost,
const string &_username, const string &_password,
const string &_exchangeName, const int _frameSize, IoMode mode
);
~AmqpIo();
bool setQueueName(const string& _queueName);
virtual inline const bool writable() const {
if (mode == IoMode::MODE_WRITE) {
return true;
}
}
template <class pmType>
size_t write(const string &dsName, pmType *start, pmType *end, size_t start_id = 0);
private:
bool _amqp_open();
bool _amqp_close(bool);
bool _amqp_bind_context();
bool _amqp_eval_status(amqp_rpc_reply_t _status);
bool _set_frame_context(const string& routingKey);
bool _send_message(const char *tag, amqp_bytes_t& message);
string mqServer;
int port;
string mqVHost;
string username;
string password;
string exchangeName;
int frameSize;
IoMode mode;
bool connected;
amqp_connection_state_t conn;
amqp_socket_t* socket;
amqp_rpc_reply_t status;
bool queueConnected;
string queueName;
bool amqpError;
string amqpErrorMessage;
};
#endif
class IoException : public exception {
public:
IoException(const string& err): error(err) {
}
virtual const char* what() const throw() {
return error.c_str();
}
~IoException() throw() { }
private:
string error;
};
template <class pmType>
Hdf5Dataset<pmType>::Hdf5Dataset(
shared_ptr<Hdf5Io> _ioMethod,
shared_ptr<Hdf5Type<pmType> > _h5type,
unsigned int _maxSize,
unsigned int _blockSize,
unsigned int _zipLevel,
const string &_dsName
):
Dataset(_ioMethod, _dsName), dsName(_dsName)
{
type = _h5type;
blockSize = _blockSize;
maxSize = _maxSize;
zipLevel = _zipLevel;
lastUpdate = 0;
size = 0;
dataset = 0;
size_id = 0;
group = _ioMethod->getCurrentGroup();
initializeDataset();
}
template <class pmType>
size_t Hdf5Dataset<pmType>::initializeDataset() {
size = 0;
const hid_t group_id = group->getGroup();
if (group_id < 0) {
IoException e("Called initializeDataset before group was opened!");
throw &e;
}
if (H5Lexists(group_id, dsName.c_str(), H5P_DEFAULT) == 1) {
dataset = H5Dopen2(group_id, dsName.c_str(), H5P_DEFAULT);
size_id = H5Aopen(dataset, "nRecords", H5P_DEFAULT);
hid_t attr_type = H5Aget_type(size_id);
H5Aread(size_id, attr_type, &size);
H5Tclose(attr_type);
} else if (ioMethod->writable()) {
hid_t param;
hsize_t rank = 1;
hsize_t initial_dims = 0;
hsize_t maximal_dims = maxSize;
if (maxSize == 0) {
maximal_dims = H5S_UNLIMITED;
}
hid_t dataspace = H5Screate_simple(rank, &initial_dims, &maximal_dims);
param = H5Pcreate(H5P_DATASET_CREATE);
if (zipLevel > 0) {
H5Pset_deflate(param, zipLevel);
}
if (blockSize > 0) {
H5Pset_layout(param, H5D_CHUNKED);
hsize_t chunk_dims = blockSize;
H5Pset_chunk(param, rank, &chunk_dims);
}
dataset = H5Dcreate(group_id, dsName.c_str(), type->getType(), dataspace, H5P_DEFAULT, param, H5P_DEFAULT);
H5Pclose(param);
H5Sclose(dataspace);
hid_t a_id = H5Screate(H5S_SCALAR);
size_id = H5Acreate2(dataset, "nRecords", H5T_NATIVE_UINT, a_id, H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(size_id, H5T_NATIVE_UINT, &size);
H5Sclose(a_id);
} else {
IoException e(string("Dataset ") + dsName + " doesn't exist and cannot be created (h5 file not writable");
throw &e;
}
return size;
}
template <class pmType>
size_t Hdf5Dataset<pmType>::read(pmType *start_pointer, size_t count, size_t start_id) {
lastUpdate = time(NULL);
hsize_t targetRecords = 0;
hsize_t localRecords = count;
hsize_t remoteStart = start_id > 0 ? start_id : 0;
hsize_t localStart = 0;
hsize_t nRecords = 0;
hid_t dataspace = H5Dget_space(dataset);
hid_t memspace = H5Screate_simple(1, &localRecords, NULL);
herr_t status = 0;
//int rank = H5Sget_simple_extent_ndims(dataspace);
status = H5Sget_simple_extent_dims(dataspace, &nRecords, NULL);
if (remoteStart < nRecords) {
targetRecords = count < (nRecords - remoteStart) ? count : (nRecords - remoteStart);
status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, &remoteStart, H5P_DEFAULT, &targetRecords, H5P_DEFAULT);
status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &localStart, H5P_DEFAULT, &localRecords, H5P_DEFAULT);
status = H5Dread(dataset, type->getType(), memspace, dataspace, H5P_DEFAULT, start_pointer);
}
H5Sclose(dataspace);
H5Sclose(memspace);
return (size_t) count;
}
template <class pmType>
size_t Hdf5Dataset<pmType>::write(pmType *start, pmType *end, size_t start_id, bool append) {
if (!ioMethod->getContextOverride()) {
const Context &context = ioMethod->getContext();
for (pmType *ptr = start; ptr != end; ++ptr) {
snprintf(ptr->identifier, IDENTIFIER_SIZE, "%s", context.identifier.c_str());
snprintf(ptr->subidentifier, IDENTIFIER_SIZE, "%s", context.subidentifier.c_str());
}
}
size_t count = end - start;
hsize_t rank = 1;
hsize_t maxRecords = 0;
hsize_t startRecord = 0;
hsize_t targetRecords = 0;
hsize_t newRecords = end - start;
unsigned int old_nRecords = 0;
if (append && start_id != 0) {
IoException e("write start_id must be 0 when appending to a dataset");
throw &e;
}
startRecord = start_id > 0 ? start_id : 0;
size_t *nRecords = &size;
hid_t filespace;
herr_t status;
lastUpdate = time(NULL);
hid_t dataspace = H5Dget_space(dataset);
status = H5Sget_simple_extent_dims(dataspace, &maxRecords, NULL);
H5Sclose(dataspace);
if (append) startRecord = *nRecords;
if (startRecord + count > maxRecords) {
targetRecords = startRecord + count;
} else {
targetRecords = maxRecords;
}
status = H5Dset_extent(dataset, &targetRecords);
filespace = H5Dget_space(dataset);
status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, &startRecord, NULL, &newRecords, NULL);
dataspace = H5Screate_simple(rank, &newRecords, NULL);
H5Dwrite(dataset, type->getType(), dataspace, filespace, H5P_DEFAULT, start);
old_nRecords = *nRecords;
*nRecords = startRecord + count > *nRecords ? startRecord + count : *nRecords;
H5Awrite(size_id, H5T_NATIVE_UINT, nRecords);
H5Sclose(filespace);
H5Sclose(dataspace);
return count;
}
template <class pmType>
size_t Hdf5Io::write(const string &dsName, pmType *start, pmType *end, size_t start_id, bool append) {
auto it = currentDatasets.find(dsName);
if (it == currentDatasets.end()) {
return 0;
}
shared_ptr<Dataset> baseDs = it->second;
shared_ptr<Hdf5Dataset<pmType> > dataset = dynamic_pointer_cast<Hdf5Dataset<pmType> >(baseDs);
return dataset->write(start, end, start_id, append);
}
template <class pmType>
size_t Hdf5Io::read(const string &dsName, pmType *start, size_t count, size_t start_id) {
auto it = currentDatasets.find(dsName);
if (it == currentDatasets.end()) {
return 0;
}
shared_ptr<Dataset> baseDs = it->second;
shared_ptr<Hdf5Dataset<pmType> > dataset = dynamic_pointer_cast<Hdf5Dataset<pmType> >(baseDs);
return dataset->read(start, count, start_id);
}
template <class pmType>
size_t Hdf5Io::howmany(const string &dsName) {
auto it = currentDatasets.find(dsName);
if (it == currentDatasets.end()) {
IoException e(string("No dataset named ") + dsName);
throw &e;
}
shared_ptr<Dataset> baseDs = it->second;
shared_ptr<Hdf5Dataset<pmType> > dataset = dynamic_pointer_cast<Hdf5Dataset<pmType> >(baseDs);
return dataset->howmany();
}
}
#endif /* PROCFMT_H_ */
| 27.706052 | 126 | 0.646557 | [
"vector"
] |
d8c9bb3ea324fc1400c36d4a2817b0c410c7bc03 | 1,756 | cpp | C++ | polymorphism/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | polymorphism/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | polymorphism/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Shape
{
public:
virtual void draw() = 0;//pure virtual function
virtual ~Shape() {}
};
class Rect : public Shape
{
public:
virtual void draw() { cout << "Rect : " << __FUNCTION__ << endl;}
~Rect() { cout << "Rect dtor" << endl;}
private:
int height;
int width;
};
class Square : public Rect
{
public:
virtual void draw(){ cout << "Square : " << __FUNCTION__ << endl;}
~Square() { cout << "Square dtor" << endl;}
};
class Ellipse : public Shape
{
public:
virtual void draw(){ cout << "Ellipse : " << __FUNCTION__ << endl;}
~Ellipse() { cout << "Ellipse dtor" << endl;}
private:
int x, y;
int r1, r2;
};
class Circle : public Ellipse
{
public:
virtual void draw(){ cout << "Circle : " << __FUNCTION__ << endl;}
~Circle() { cout << "Circle dtor" << endl;}
};
void drawAll(const vector<Shape*> &v){
for(auto& elem : v)
elem->draw();
}
int main(int argc, char **argv)
{
Rect r1;
Square q1;
r1.draw();
q1.draw();
Rect* Rptr = new Rect;
Rptr->draw();
delete Rptr;
//if Shape class doesn't declare virtual dtor then the Rect's dtor would not be invoked.
Shape* Sptr = new Rect;
Sptr->draw();
delete Sptr;
cout << "Shape size : " << sizeof(Shape) << endl;
cout << "Rect size : " << sizeof(Rect) << endl;
cout << "Square size : " << sizeof(Square) << endl;
cout << "Ellipse size : " << sizeof(Ellipse) << endl;
cout << "Circle size : " << sizeof(Circle) << endl;
vector<Shape*> shapeIs;
shapeIs.push_back(&r1);
shapeIs.push_back(&q1);
shapeIs.push_back(new Circle);
shapeIs.push_back(new Ellipse);
drawAll(shapeIs);
return 0;
} | 21.414634 | 92 | 0.583144 | [
"shape",
"vector"
] |
d8cf7c1957d9cc751bee6df926d4fb7fa97357cd | 15,613 | cxx | C++ | src/FesExposure.cxx | fermi-lat/EbfWriter | ede39be090864de859e21103bd862839cbf4116a | [
"BSD-3-Clause"
] | null | null | null | src/FesExposure.cxx | fermi-lat/EbfWriter | ede39be090864de859e21103bd862839cbf4116a | [
"BSD-3-Clause"
] | null | null | null | src/FesExposure.cxx | fermi-lat/EbfWriter | ede39be090864de859e21103bd862839cbf4116a | [
"BSD-3-Clause"
] | null | null | null | /**: @file FesExposure.cxx
@brief declare and implement the Algorithm FesExposure
$Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/EbfWriter/src/FesExposure.cxx,v 1.4 2011/05/20 15:01:26 heather Exp $
*/
// Include files
// Gaudi system includes
#include "GaudiKernel/Algorithm.h"
#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/AlgFactory.h"
#include "GaudiKernel/IDataProviderSvc.h"
#include "GaudiKernel/SmartDataPtr.h"
#include "GaudiKernel/SmartRefVector.h"
#include "Event/MonteCarlo/Exposure.h"
#include "astro/SkyDir.h"
#include "astro/EarthCoordinate.h"
#include "astro/SolarSystem.h"
//flux
#include "FluxSvc/IFluxSvc.h"
#include "flux/IFlux.h"
#include "astro/GPS.h"
#include "facilities/Util.h"
#include <cassert>
#include <vector>
#include <fstream>
#include <iomanip>
// Record Size LDF Header (4 32bit) +
// 5 Attitude 5*(13 32bit) +
// 1 Position (8 32 bit) = 77 32bit words
#define attRecordSize 77
// Time from Jan 1, 2001 to launch ~7 years * 30 million seconds
//THB time is already in MET #define launchOffset 210000000
/**
* \class FesExposure
*
* \brief This is an Algorithm designed to get information about the GLAST locatation and orientaion
* and save it in a special tuple
*
* \author Brian Winer, mods by T. Burnett
*
*/
static inline unsigned int writeAtt (unsigned int* data, FILE* fp);
static inline void swap (unsigned int *wrds, int nwrds);
static inline CLHEP::Hep3Vector fromRaDec(double RA, double Dec);
class FesExposure : public Algorithm {
public:
FesExposure(const std::string& name, ISvcLocator* pSvcLocator);
//stuff that an Algorithm needs.
StatusCode initialize();
StatusCode execute();
StatusCode finalize();
StatusCode addAttitudeHeader();
StatusCode calcAttitudeContribution(CLHEP::Hep3Vector xaxis, CLHEP::Hep3Vector zaxis);
StatusCode calcPositionContribution(double x, double y, double z);
StatusCode convertTime(double time);
private:
int m_tickCount;
IFluxSvc* m_fluxSvc;
unsigned int* m_att_data_start;
unsigned int* m_att_data;
int m_attCont;
FILE* m_outfile;
bool m_startCont;
unsigned int m_secTime;
unsigned int m_microTime;
double m_lastx,m_lasty,m_lastz;
double m_lastAttTime, m_lastPosTime;
CLHEP::Hep3Vector m_lastXaxis,m_lastYaxis,m_lastZaxis;
std::string m_FileName;
StringProperty m_timerName;
typedef union IntDble_t {
unsigned int dui[2];
double dbl;
} IntDble;
typedef union IntFlt_t {
unsigned int intVal;
float fltVal;
} IntFlt;
};
//------------------------------------------------------------------------
//static const AlgFactory<FesExposure> Factory;
//const IAlgFactory& FesExposureFactory = Factory;
DECLARE_ALGORITHM_FACTORY(FesExposure);
//------------------------------------------------------------------------
//! ctor
FesExposure::FesExposure(const std::string& name, ISvcLocator* pSvcLocator)
: Algorithm(name, pSvcLocator)
, m_tickCount(0)
, m_attCont(0)
, m_outfile(0)
, m_startCont(true)
, m_secTime(0)
, m_microTime(0)
{
declareProperty("FileName" ,m_FileName="Attitude");
declareProperty("TimerName" ,m_timerName="timer_5Hz");
}
//------------------------------------------------------------------------
//! set parameters and attach to various perhaps useful services.
StatusCode FesExposure::initialize(){
StatusCode sc = StatusCode::SUCCESS;
MsgStream log(msgSvc(), name());
// Use the Job options service to set the Algorithm's parameters
setProperties();
m_att_data_start = 0;
if ( service("FluxSvc", m_fluxSvc).isFailure() ){
log << MSG::ERROR << "Couldn't find the FluxSvc!" << endreq;
return StatusCode::FAILURE;
}
// access the properties of FluxSvc
IProperty* propMgr=0;
sc = serviceLocator()->service("FluxSvc", propMgr );
if( sc.isFailure()) {
log << MSG::ERROR << "Unable to locate PropertyManager Service" << endreq;
return sc;
}
/* Allocate a buffer big enough to hold a maximally sized event */
unsigned char* ptr = (unsigned char *)malloc (attRecordSize*4);
if (ptr == 0) { return StatusCode::FAILURE; }
m_att_data_start = (unsigned int *)ptr;
m_att_data = m_att_data_start;
// Open up the output file, with optional env var
std::string filename(m_FileName);
facilities::Util::expandEnvVar(&filename);
char file[120];
sprintf(file,"%s.ldf",filename.c_str());
m_outfile = fopen (file, "wb");
if (!m_outfile)
{
/* Error in opening the output file.. */
free (ptr);
log << MSG::ERROR << "Unable to open file to write Attitude Information" << endreq;
return StatusCode::FAILURE;
}
m_lastx = m_lasty = m_lastz = 0.;
m_lastAttTime = m_lastPosTime = 0.;
m_lastXaxis = CLHEP::Hep3Vector(0.,0.,0.);
m_lastYaxis = CLHEP::Hep3Vector(0.,0.,0.);
m_lastZaxis = CLHEP::Hep3Vector(0.,0.,0.);
return sc;
}
static void swap (unsigned int *wrds, int nwrds)
/*
DESCRIPTION
-----------
Performs a byte-swap on the specified number of 32-bit words. This
is an El-Cheapo implementation, it should not be used for heavy
duty byte-swapping.
PARAMETERS
----------
wrds: The 32-bit words to byte-swap
nwrds: The number of 32-bit words to byte-swap.
RETURNS
-------
Nothing
*/
{
while (--nwrds >= 0)
{
unsigned int tmp;
tmp = *wrds;
tmp = ((tmp & 0x000000ff) << 24) |
((tmp & 0x0000ff00) << 8) |
((tmp & 0x00ff0000) >> 8) |
((tmp & 0xff000000) >> 24);
*wrds++ = tmp;
}
return;
}
static unsigned int writeAtt (unsigned int* data, FILE* fp)
{
/*
| !!! KLUDGE !!!
| --------------
| Need to know whether the machine executing this code is a big
| or little endian machine. I've checked around and found no one
| who can tell me of a compiler defined symbol containing this
| tidbit of information. Currently, I've only every run GLEAM on
| Intel processors, so I've hardwired this to be little-endian.
*/
swap (data, attRecordSize);
if(fp) return fwrite (data, sizeof (*data), attRecordSize, fp);
return 0;
}
//------------------------------------------------------------------------
//! process an event
StatusCode FesExposure::execute()
{
using astro::GPS;
StatusCode sc = StatusCode::SUCCESS;
MsgStream log( msgSvc(), name() );
IFlux* flux=m_fluxSvc->currentFlux();
if(flux->name() != m_timerName.value()) return sc;
//printf("found time tick\n");
// The GPS singleton has current time and orientation
GPS* gps = m_fluxSvc->GPSinstance();
double time = gps->time();
CLHEP::Hep3Vector location = 1.e3* gps->position(); // special, needs its own time
// cartesian location of the LAT (in m)
double posX = location.x();
double posY = location.y();
double posZ = location.z();
/* printf("FES::Attitude Information:
Time: %f
Latitude: %f
Longitude:%f
Altitude: %f
PosX: %f
PosY: %f
PosZ: %f
RightAsX: %f
DelX: %f
RightAsZ: %f
DelZ: %f \n",time,latitude,longitude,altitude,posX,posY,posZ,RightAsX,DeclX,RightAsZ,DeclZ);
*/
// Convert Time to seconds and microseconds since Jan 1, 2001
convertTime(time);
// If this is a new contribution, add the header
if(m_startCont) {
m_att_data = m_att_data_start;
addAttitudeHeader();
// printf("Adding the Header\n");
m_startCont = false;
}
// Calculate the attitude Contribution
calcAttitudeContribution(gps->xAxisDir()(), gps->zAxisDir()());
// printf("Adding the Att. Contribution # %i at time %f\n",m_attCont,time);
m_attCont++;
// If it is the end of 1 second, calculate the position information
if(m_attCont > 4) {
calcPositionContribution(posX,posY,posZ);
// printf("Adding the Position Cont at time %f\n",time);
// flush this contributions to the file
writeAtt(m_att_data_start,m_outfile);
// printf("Dumping the Att file\n");
// Next time through we need to start a new contribution
m_startCont = true;
m_attCont = 0;
}
m_tickCount++;
return sc;
}
StatusCode FesExposure::addAttitudeHeader() {
StatusCode sc = StatusCode::SUCCESS;
int LATdatagramID = 0xF0002;
int LD_Version = 0x800; //MSB must be set
*m_att_data++ = (LD_Version)<<20 | (LATdatagramID & 0xfffff);
*m_att_data++ = (attRecordSize & 0xffffff);
int LATcontribID = 0xFFFFF;
int LC_Version = 0x000;
*m_att_data++ = (LC_Version)<<20 | (LATcontribID & 0xfffff);
*m_att_data++ = ((attRecordSize-2) & 0xffffff);
return sc;
}
StatusCode FesExposure::calcAttitudeContribution(CLHEP::Hep3Vector xAxis, CLHEP::Hep3Vector zAxis){
StatusCode sc = StatusCode::SUCCESS;
// Now get the directions starting from the Z axis. Why?
CLHEP::Hep3Vector yAxis = zAxis.cross(xAxis).unit();
xAxis = yAxis.cross(zAxis);
// Now Convert these directional vectors to a Quaternion
double s = 1.0 + xAxis.x() + yAxis.y() + zAxis.z();
IntDble q1,q2,q3,q4;
if(s > 0.01) {
q1.dbl = yAxis.z() - zAxis.y();
q2.dbl = zAxis.x() - xAxis.z();
q3.dbl = xAxis.y() - yAxis.x();
q4.dbl = s;
} else {
if(xAxis.x() >= yAxis.y() && xAxis.x() >= zAxis.z()) {
q1.dbl = 1.0 + xAxis.x() - yAxis.y() - zAxis.z();
q2.dbl = yAxis.x() + xAxis.y();
q3.dbl = zAxis.x() + xAxis.z();
q4.dbl = yAxis.z() - zAxis.y();
} else if(yAxis.y() >= xAxis.x() && yAxis.y() >= zAxis.z()) {
q1.dbl = yAxis.x() + xAxis.y();
q2.dbl = 1.0 - xAxis.x() + yAxis.y() - zAxis.z();
q3.dbl = zAxis.y() + yAxis.z();
q4.dbl = zAxis.x() - xAxis.z();
} else {
q1.dbl = zAxis.x() + xAxis.z();
q2.dbl = zAxis.y() + yAxis.z();
q3.dbl = 1.0 - xAxis.x() - yAxis.y() + zAxis.z();
q4.dbl = xAxis.y() - yAxis.x();
}
}
// Determine the normalization of the components and then scale so
// the quaternion has unit length.
double norm = q1.dbl*q1.dbl+q2.dbl*q2.dbl+q3.dbl*q3.dbl+q4.dbl*q4.dbl;
if(norm >0.) {
norm = sqrt(norm);
q1.dbl = q1.dbl/norm;
q2.dbl = q2.dbl/norm;
q3.dbl = q3.dbl/norm;
q4.dbl = q4.dbl/norm;
}
/*
printf("RaX %f DecX %f RaX %f DecX %f\n",RAx,DecX,RAz,DecZ);
printf("X-Axis Vector i,j,k,mag: %f %f %f %f Angle y %f Angle z %f\n",xAxis.x(),xAxis.y(),xAxis.z(),xAxis.mag(),xAxis.angle(yAxis),xAxis.angle(zAxis));
printf("Y-Axis Vector i,j,k,mag: %f %f %f %f\n",yAxis.x(),yAxis.y(),yAxis.z(),yAxis.mag());
printf("Z-Axis Vector i,j,k,mag: %f %f %f %f\n",zAxis.x(),zAxis.y(),zAxis.z(),zAxis.mag());
printf("Q1 %f Q2 %f Q3 %f Q4 %f\n",q1.dbl,q2.dbl,q3.dbl,q4.dbl);
*/
// First put in the time stamp
*m_att_data++ = m_secTime;
*m_att_data++ = m_microTime;
// Now Quaternion q1 (64 bits)
*m_att_data++ = q1.dui[1];
*m_att_data++ = q1.dui[0];
// Now Quaternion q2 (64 bits)
*m_att_data++ = q2.dui[1];
*m_att_data++ = q2.dui[0];
// Now Quaternion q3 (64 bits)
*m_att_data++ = q3.dui[1];
*m_att_data++ = q3.dui[0];
// Now Quaternion q4 (64 bits)
*m_att_data++ = q4.dui[1];
*m_att_data++ = q4.dui[0];
// Now Angular Velocity x,y,z
// This is not part of Gleam/GPS(?) so extrapolate from
// previous point. This info is not used in FSW
// First entry fill with zeros
// Time since last Attitude Info
double newTime = (double)m_secTime + ((double)m_microTime)/1000000.;
double deltaTime = newTime - m_lastAttTime;
if(m_lastXaxis.mag() == 0) {
IntFlt dummy;
dummy.fltVal = 0.;
*m_att_data++ = dummy.intVal;
*m_att_data++ = dummy.intVal;
*m_att_data++ = dummy.intVal;
} else {
// get change in direction of axes
IntFlt angVelX,angVelY,angVelZ;
if( deltaTime>0) {
angVelX.fltVal = xAxis.angle(m_lastXaxis)/deltaTime;
angVelY.fltVal = yAxis.angle(m_lastYaxis)/deltaTime;
angVelZ.fltVal = zAxis.angle(m_lastZaxis)/deltaTime;
}
else{
angVelX.intVal=angVelY.intVal=angVelZ.intVal = 0;
}
// printf("Angular Velocity (rad/sec) x,y,z,dt: %f %f %f %f\n",angVelX.fltVal,angVelY.fltVal,angVelZ.fltVal,deltaTime);
// Stuff the Angular Velocity into the Record
*m_att_data++ = angVelX.intVal;
*m_att_data++ = angVelY.intVal;
*m_att_data++ = angVelZ.intVal;
}
m_lastXaxis = xAxis;
m_lastYaxis = yAxis;
m_lastZaxis = zAxis;
m_lastAttTime = newTime;
return sc;
}
static inline CLHEP::Hep3Vector fromRaDec(double RA, double Dec){
double theta = (90.0 - Dec)*M_PI/180.0;
double phi = RA*M_PI/180.0;
double sinTheta = sin(theta);
CLHEP::Hep3Vector vec = CLHEP::Hep3Vector(sinTheta*cos(phi), sinTheta*sin(phi), cos(theta));
return vec;
}
StatusCode FesExposure::calcPositionContribution(double x, double y, double z) {
StatusCode sc = StatusCode::SUCCESS;
// First put in the time stamp
*m_att_data++ = m_secTime;
*m_att_data++ = m_microTime;
// Setup variables
IntFlt xpos,ypos,zpos;
xpos.fltVal = (float)x;
ypos.fltVal = (float)y;
zpos.fltVal = (float)z;
// Now Position x,y,z
*m_att_data++ = xpos.intVal;
*m_att_data++ = ypos.intVal;
*m_att_data++ = zpos.intVal;
// Now Velocity x,y,z
// this info is not really in GLEAM/GPS(?) For now make an
// estimate based on the last postion. The Flight software
// does really make use of this information
double newTime = (double)m_secTime + ((double)m_microTime)/1000000.;
double deltaTime = newTime - m_lastPosTime;
IntFlt vx,vy,vz;
if(m_lastx == 0. && m_lasty == 0. && m_lastz == 0.) {
vx.fltVal = vy.fltVal = vz.fltVal = 0.;
} else {
vx.fltVal = (float)(x-m_lastx)/deltaTime;
vy.fltVal = (float)(y-m_lasty)/deltaTime;
vz.fltVal = (float)(z-m_lastz)/deltaTime;
}
// Putting in the estimate of the velocity
*m_att_data++ = vx.intVal;
*m_att_data++ = vy.intVal;
*m_att_data++ = vz.intVal;
// Store for next time through
m_lastPosTime = newTime;
m_lastx = x;
m_lasty = y;
m_lastz = z;
// printf("Position x,y,z %f, %f, %f\n",x,y,z);
// printf("Velocity x,y,z %f, %f, %f\n",vx.fltVal,vy.fltVal,vz.fltVal);
return sc;
}
//------------------------------------------------------------------------
//! clean up, summarize
StatusCode FesExposure::convertTime(double time){
// finish up
StatusCode sc = StatusCode::SUCCESS;
static int launchOffset(0); // THB since time is already in MET
m_secTime = launchOffset + (int)time;
m_microTime = (int)(1000000.*(time - (int)time));
// printf("Time %f seconds %i microseconds %i\n",time,m_secTime,m_microTime);
return sc;
}
//------------------------------------------------------------------------
//! clean up, summarize
StatusCode FesExposure::finalize(){
// finish up
StatusCode sc = StatusCode::SUCCESS;
MsgStream log(msgSvc(), name());
log << MSG::INFO << "FesExposure Processed " << m_tickCount << " ticks" << endreq;
if(m_outfile) fclose(m_outfile);
return sc;
}
| 29.570076 | 154 | 0.604816 | [
"vector"
] |
d8d1f83ed1b9b873b297f21116b99820a315ab82 | 464 | cc | C++ | tile/ocl_exec/intrinsic.cc | redoclag/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 4,535 | 2017-10-20T05:03:57.000Z | 2022-03-30T15:42:33.000Z | tile/ocl_exec/intrinsic.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 984 | 2017-10-20T17:16:09.000Z | 2022-03-30T05:43:18.000Z | tile/ocl_exec/intrinsic.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 492 | 2017-10-20T18:22:32.000Z | 2022-03-30T09:00:05.000Z | #include "tile/ocl_exec/intrinsic.h"
namespace vertexai {
namespace tile {
namespace hal {
namespace opencl {
std::vector<lang::IntrinsicSpec> ocl_intrinsics = {
{"vloadn", EmitVloadn},
{"vstoren", EmitVstoren},
};
sem::ExprPtr EmitVloadn(const stripe::Intrinsic& in) { return nullptr; }
sem::ExprPtr EmitVstoren(const stripe::Intrinsic& in) { return nullptr; }
} // namespace opencl
} // namespace hal
} // namespace tile
} // namespace vertexai
| 22.095238 | 73 | 0.706897 | [
"vector"
] |
d8d8e1c8dc28587999cbc46a6add208e60bd3991 | 28,408 | cpp | C++ | osr_perf/src/roboclaw.cpp | ljb2208/osr-rover-code | f4791d835cd760446777a226d37bb3114256affd | [
"Apache-2.0"
] | null | null | null | osr_perf/src/roboclaw.cpp | ljb2208/osr-rover-code | f4791d835cd760446777a226d37bb3114256affd | [
"Apache-2.0"
] | null | null | null | osr_perf/src/roboclaw.cpp | ljb2208/osr-rover-code | f4791d835cd760446777a226d37bb3114256affd | [
"Apache-2.0"
] | null | null | null | /*
* roboclaw.cpp - implementation of the roboclaw C++ library using ROS serial
*
* This code is a modified version of the Ion Motion Control Arduino library.
* To view the code in its original form, download it at
* http://downloads.ionmc.com/code/arduino.zip
*/
#include "../include/roboclaw.h"
/*
* Macros taken directly from Arduino Library
*/
#define MAXRETRY 2
#define SetDWORDval(arg) (uint8_t)(((uint32_t)arg)>>24),(uint8_t)(((uint32_t)arg)>>16),(uint8_t)(((uint32_t)arg)>>8),(uint8_t)arg
#define SetWORDval(arg) (uint8_t)(((uint16_t)arg)>>8),(uint8_t)arg
#define SetSignedDWORDval(arg) (uint8_t)(((int32_t)arg)>>24),(uint8_t)(((int32_t)arg)>>16),(uint8_t)(((int32_t)arg)>>8),(uint8_t)arg
/*
* Constructor opens port at desired baudrate
*/
Roboclaw::Roboclaw(std::string &port, uint32_t baudrate)
{
/* initialize pointer to a new Serial port object */
port_ = new serial::Serial(port, baudrate, serial::Timeout::simpleTimeout(100));
port_->open();
}
/*
* Destructor closes serial port and frees the associated memory
*/
Roboclaw::~Roboclaw()
{
port_->close();
delete port_;
}
/*
* writes a single byte to the serial port
*/
void Roboclaw::write(uint8_t byte)
{
port_->write(&byte, 1);
}
/*
* reads and returns a single byte from the serial port or -1 in error or timeout
* returns an int16_t to be consistent with the Arduino library and allow for
* returning -1 error
*/
int16_t Roboclaw::read()
{
uint8_t buff[1];
if (port_->read(buff, 1) == 1)
{
return buff[0];
}
else
{
return -1;
}
}
/*
* flushes the serial port's input and output buffers
*/
void Roboclaw::flush()
{
port_->flush();
}
/*
* resets the crc calculation
*/
void Roboclaw::crc_clear()
{
crc_ = 0;
}
/*
* updates the crc calculation with based on the specified byte
* see the Roboclaw sheet and user manual for more on this
*/
void Roboclaw::crc_update (uint8_t data)
{
int i;
crc_ = crc_^ ((uint16_t)data << 8);
for (i=0; i<8; i++)
{
if (crc_ & 0x8000)
crc_ = (crc_ << 1) ^ 0x1021;
else
crc_ <<= 1;
}
}
/*
* returns the current value of the crc
* this is not necessary as private methods can directly access the crc_ attribute,
* but it is being kept for now to keep the original Arduino code intact
*/
uint16_t Roboclaw::crc_get()
{
return crc_;
}
/*
* writes n bytes to the serial port as specified by function arguments
*/
bool Roboclaw::write_n(uint8_t cnt, ... )
{
uint8_t trys=MAXRETRY;
do{
crc_clear();
va_list marker;
va_start(marker, cnt); /* Initialize variable arguments */
/* read each argument after cnt, update crc, and send the data */
for(uint8_t index=0;index<cnt;index++){
uint8_t data = va_arg(marker, int);
crc_update(data);
write(data);
}
va_end( marker ); /* Reset variable arguments */
/* send the crc to the Roboclaw and check for return value */
port_->write((uint8_t *) &crc_, 2);
if(read()==0xFF)
return true;
}while(trys--);
return false;
}
/*
* reads the output of a command into n uint32_t variables specified by pointer arguments
*/
bool Roboclaw::read_n(uint8_t cnt,uint8_t address,uint8_t cmd,...)
{
uint32_t value=0;
uint8_t trys=MAXRETRY;
int16_t data;
do{
flush();
data=0;
crc_clear();
write(address);
crc_update(address);
write(cmd);
crc_update(cmd);
/* read each four byte output of the command into a uint32_t */
va_list marker;
va_start( marker, cmd ); /* Initialize variable arguments. */
for(uint8_t index=0;index<cnt;index++){
/* retrieve the pointer to the next uint32_t to be updated */
uint32_t *ptr = va_arg(marker, uint32_t *);
if(data!=-1){
data = read();
crc_update(data);
value=(uint32_t)data<<24;
}
else{
break;
}
if(data!=-1){
data = read();
crc_update(data);
value|=(uint32_t)data<<16;
}
else{
break;
}
if(data!=-1){
data = read();
crc_update(data);
value|=(uint32_t)data<<8;
}
else{
break;
}
if(data!=-1){
data = read();
crc_update(data);
value|=(uint32_t)data;
}
else{
break;
}
*ptr = value;
}
va_end( marker ); /* Reset variable arguments. */
/* read crc from the roboclaw and double check with our calculation */
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
return crc_get()==ccrc;
}
}
}
}while(trys--);
return false;
}
/*
* reads a one byte register returning its contents or false in error
*/
uint8_t Roboclaw::read1(uint8_t address,uint8_t cmd,bool *valid)
{
if(valid)
*valid = false;
uint8_t value=0;
uint8_t trys=MAXRETRY;
/* data is a signed int to allow for -1 assignment in error */
int16_t data;
do{
flush();
crc_clear();
write(address);
crc_update(address);
write(cmd);
crc_update(cmd);
data = read();
crc_update(data);
value=data;
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
if(crc_get()==ccrc){
*valid = true;
return value;
}
}
}
}
}while(trys--);
return false;
}
/*
* reads a two byte register, returning its contents or false in error
*/
uint16_t Roboclaw::read2(uint8_t address,uint8_t cmd,bool *valid)
{
if(valid)
*valid = false;
uint16_t value=0;
uint8_t trys=MAXRETRY;
int16_t data;
do{
flush();
crc_clear();
write(address);
crc_update(address);
write(cmd);
crc_update(cmd);
data = read();
crc_update(data);
value=(uint16_t)data<<8;
if(data!=-1){
data = read();
crc_update(data);
value|=(uint16_t)data;
}
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
if(crc_get()==ccrc){
*valid = true;
return value;
}
}
}
}
}while(trys--);
return false;
}
/*
* reads a four byte register
* returns register contents or false in error
*/
uint32_t Roboclaw::read4(uint8_t address, uint8_t cmd, bool *valid)
{
if(valid)
*valid = false;
uint16_t value=0;
uint8_t trys=MAXRETRY;
int16_t data;
do{
flush();
crc_clear();
write(address);
crc_update(address);
write(cmd);
crc_update(cmd);
data = read();
crc_update(data);
value=(uint16_t)data<<8;
if(data!=-1){
data = read();
crc_update(data);
value|=(uint16_t)data;
}
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
if(crc_get()==ccrc){
*valid = true;
return value;
}
}
}
}
}while(trys--);
return false;
}
/*
* Reads a four byte register along with the roboclaw's status
* returns the value of the register or false in the event of a timeout or error
* updates value of status pointer argument
* indicates success/failure through the valid argument
*/
uint32_t Roboclaw::read4_1(uint8_t address, uint8_t cmd, uint8_t *status, bool *valid)
{
if(valid)
*valid = false;
uint16_t value=0;
uint8_t trys=MAXRETRY;
int16_t data;
do{
flush();
crc_clear();
write(address);
crc_update(address);
write(cmd);
crc_update(cmd);
data = read();
crc_update(data);
value=(uint16_t)data<<8;
if(data!=-1){
data = read();
crc_update(data);
value|=(uint16_t)data;
}
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
if(crc_get()==ccrc){
*valid = true;
return value;
}
}
}
}
}while(trys--);
return false;
}
/************************************************************
* original methods unchanged from original Arduino library *
************************************************************/
bool Roboclaw::ForwardM1(uint8_t address, uint8_t speed){
return write_n(3,address,M1FORWARD,speed);
}
bool Roboclaw::BackwardM1(uint8_t address, uint8_t speed){
return write_n(3,address,M1BACKWARD,speed);
}
bool Roboclaw::SetMinVoltageMainBattery(uint8_t address, uint8_t voltage){
return write_n(3,address,SETMINMB,voltage);
}
bool Roboclaw::SetMaxVoltageMainBattery(uint8_t address, uint8_t voltage){
return write_n(3,address,SETMAXMB,voltage);
}
bool Roboclaw::ForwardM2(uint8_t address, uint8_t speed){
return write_n(3,address,M2FORWARD,speed);
}
bool Roboclaw::BackwardM2(uint8_t address, uint8_t speed){
return write_n(3,address,M2BACKWARD,speed);
}
bool Roboclaw::ForwardBackwardM1(uint8_t address, uint8_t speed){
return write_n(3,address,M17BIT,speed);
}
bool Roboclaw::ForwardBackwardM2(uint8_t address, uint8_t speed){
return write_n(3,address,M27BIT,speed);
}
bool Roboclaw::ForwardMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDFORWARD,speed);
}
bool Roboclaw::BackwardMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDBACKWARD,speed);
}
bool Roboclaw::TurnRightMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDRIGHT,speed);
}
bool Roboclaw::TurnLeftMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDLEFT,speed);
}
bool Roboclaw::ForwardBackwardMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDFB,speed);
}
bool Roboclaw::LeftRightMixed(uint8_t address, uint8_t speed){
return write_n(3,address,MIXEDLR,speed);
}
uint32_t Roboclaw::ReadEncM1(uint8_t address, uint8_t *status,bool *valid){
return read4_1(address,GETM1ENC,status,valid);
}
uint32_t Roboclaw::ReadEncM2(uint8_t address, uint8_t *status,bool *valid){
return read4_1(address,GETM2ENC,status,valid);
}
uint32_t Roboclaw::ReadSpeedM1(uint8_t address, uint8_t *status,bool *valid){
return read4_1(address,GETM1SPEED,status,valid);
}
uint32_t Roboclaw::ReadSpeedM2(uint8_t address, uint8_t *status,bool *valid){
return read4_1(address,GETM2SPEED,status,valid);
}
bool Roboclaw::ResetEncoders(uint8_t address){
return write_n(2,address,RESETENC);
}
bool Roboclaw::ReadVersion(uint8_t address,char *version){
uint8_t data;
uint8_t trys=MAXRETRY;
do{
flush();
data = 0;
crc_clear();
write(address);
crc_update(address);
write(GETVERSION);
crc_update(GETVERSION);
uint8_t i;
for(i=0;i<48;i++){
if(data!=-1){
data=read();
version[i] = data;
crc_update(version[i]);
if(version[i]==0){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
return crc_get()==ccrc;
}
}
break;
}
}
else{
break;
}
}
}while(trys--);
return false;
}
bool Roboclaw::SetEncM1(uint8_t address, int val){
return write_n(6,address,SETM1ENCCOUNT,SetDWORDval(val));
}
bool Roboclaw::SetEncM2(uint8_t address, int val){
return write_n(6,address,SETM2ENCCOUNT,SetDWORDval(val));
}
uint16_t Roboclaw::ReadMainBatteryVoltage(uint8_t address,bool *valid){
return read2(address,GETMBATT,valid);
}
uint16_t Roboclaw::ReadLogicBatteryVoltage(uint8_t address,bool *valid){
return read2(address,GETLBATT,valid);
}
bool Roboclaw::SetMinVoltageLogicBattery(uint8_t address, uint8_t voltage){
return write_n(3,address,SETMINLB,voltage);
}
bool Roboclaw::SetMaxVoltageLogicBattery(uint8_t address, uint8_t voltage){
return write_n(3,address,SETMAXLB,voltage);
}
bool Roboclaw::SetM1VelocityPID(uint8_t address, float kp_fp, float ki_fp, float kd_fp, uint32_t qpps){
uint32_t kp = kp_fp*65536;
uint32_t ki = ki_fp*65536;
uint32_t kd = kd_fp*65536;
return write_n(18,address,SETM1PID,SetDWORDval(kd),SetDWORDval(kp),SetDWORDval(ki),SetDWORDval(qpps));
}
bool Roboclaw::SetM2VelocityPID(uint8_t address, float kp_fp, float ki_fp, float kd_fp, uint32_t qpps){
uint32_t kp = kp_fp*65536;
uint32_t ki = ki_fp*65536;
uint32_t kd = kd_fp*65536;
return write_n(18,address,SETM2PID,SetDWORDval(kd),SetDWORDval(kp),SetDWORDval(ki),SetDWORDval(qpps));
}
uint32_t Roboclaw::ReadISpeedM1(uint8_t address,uint8_t *status,bool *valid){
return read4_1(address,GETM1ISPEED,status,valid);
}
uint32_t Roboclaw::ReadISpeedM2(uint8_t address,uint8_t *status,bool *valid){
return read4_1(address,GETM2ISPEED,status,valid);
}
bool Roboclaw::DutyM1(uint8_t address, uint16_t duty){
return write_n(4,address,M1DUTY,SetWORDval(duty));
}
bool Roboclaw::DutyM2(uint8_t address, uint16_t duty){
return write_n(4,address,M2DUTY,SetWORDval(duty));
}
bool Roboclaw::DutyM1M2(uint8_t address, uint16_t duty1, uint16_t duty2){
return write_n(6,address,MIXEDDUTY,SetWORDval(duty1),SetWORDval(duty2));
}
bool Roboclaw::SpeedM1(uint8_t address, uint32_t speed){
return write_n(6,address,M1SPEED,SetDWORDval(speed));
}
bool Roboclaw::SpeedM2(uint8_t address, uint32_t speed){
return write_n(6,address,M2SPEED,SetDWORDval(speed));
}
bool Roboclaw::SpeedM1M2(uint8_t address, uint32_t speed1, uint32_t speed2){
return write_n(10,address,MIXEDSPEED,SetDWORDval(speed1),SetDWORDval(speed2));
}
bool Roboclaw::SpeedAccelM1(uint8_t address, int32_t accel, int32_t speed){
return write_n(10,address,M1SPEEDACCEL,SetSignedDWORDval(accel),SetSignedDWORDval(speed));
}
bool Roboclaw::SpeedAccelM2(uint8_t address, int32_t accel, int32_t speed){
return write_n(10,address,M2SPEEDACCEL,SetSignedDWORDval(accel),SetSignedDWORDval(speed));
}
bool Roboclaw::SpeedAccelM1M2(uint8_t address, int32_t accel, int32_t speed1, int32_t speed2){
return write_n(14,address,MIXEDSPEEDACCEL,SetSignedDWORDval(accel),SetSignedDWORDval(speed1),SetSignedDWORDval(speed2));
}
bool Roboclaw::SpeedDistanceM1(uint8_t address, uint32_t speed, uint32_t distance, uint8_t flag){
return write_n(11,address,M1SPEEDDIST,SetDWORDval(speed),SetDWORDval(distance),flag);
}
bool Roboclaw::SpeedDistanceM2(uint8_t address, uint32_t speed, uint32_t distance, uint8_t flag){
return write_n(11,address,M2SPEEDDIST,SetDWORDval(speed),SetDWORDval(distance),flag);
}
bool Roboclaw::SpeedDistanceM1M2(uint8_t address, uint32_t speed1, uint32_t distance1, uint32_t speed2, uint32_t distance2, uint8_t flag){
return write_n(19,address,MIXEDSPEEDDIST,SetDWORDval(speed1),SetDWORDval(distance1),SetDWORDval(speed2),SetDWORDval(distance2),flag);
}
bool Roboclaw::SpeedAccelDistanceM1(uint8_t address, int32_t accel, int32_t speed, int32_t distance, uint8_t flag){
return write_n(15,address,M1SPEEDACCELDIST,SetSignedDWORDval(accel),SetSignedDWORDval(speed),SetSignedDWORDval(distance),flag);
}
bool Roboclaw::SpeedAccelDistanceM2(uint8_t address, int32_t accel, int32_t speed, int32_t distance, uint8_t flag){
return write_n(15,address,M2SPEEDACCELDIST,SetSignedDWORDval(accel),SetSignedDWORDval(speed),SetSignedDWORDval(distance),flag);
}
bool Roboclaw::SpeedAccelDistanceM1M2(uint8_t address, int32_t accel, int32_t speed1, int32_t distance1, int32_t speed2, int32_t distance2, uint8_t flag){
return write_n(23,address,MIXEDSPEEDACCELDIST,SetSignedDWORDval(accel),SetSignedDWORDval(speed1),SetSignedDWORDval(distance1),SetSignedDWORDval(speed2),SetSignedDWORDval(distance2),flag);
}
bool Roboclaw::ReadBuffers(uint8_t address, uint8_t &depth1, uint8_t &depth2){
bool valid;
uint16_t value = read2(address,GETBUFFERS,&valid);
if(valid){
depth1 = value>>8;
depth2 = value;
}
return valid;
}
bool Roboclaw::ReadPWMs(uint8_t address, int16_t &pwm1, int16_t &pwm2){
bool valid;
uint32_t value = read4(address,GETPWMS,&valid);
if(valid){
pwm1 = value>>16;
pwm2 = value&0xFFFF;
}
return valid;
}
bool Roboclaw::ReadCurrents(uint8_t address, int16_t ¤t1, int16_t ¤t2){
bool valid;
uint32_t value = read4(address,GETCURRENTS,&valid);
if(valid){
current1 = value>>16;
current2 = value&0xFFFF;
}
return valid;
}
bool Roboclaw::SpeedAccelM1M2_2(uint8_t address, uint32_t accel1, uint32_t speed1, uint32_t accel2, uint32_t speed2){
return write_n(18,address,MIXEDSPEED2ACCEL,SetDWORDval(accel1),SetDWORDval(speed1),SetDWORDval(accel2),SetDWORDval(speed2));
}
bool Roboclaw::SpeedAccelDistanceM1M2_2(uint8_t address, uint32_t accel1, uint32_t speed1, uint32_t distance1, uint32_t accel2, uint32_t speed2, uint32_t distance2, uint8_t flag){
return write_n(27,address,MIXEDSPEED2ACCELDIST,SetDWORDval(accel1),SetDWORDval(speed1),SetDWORDval(distance1),SetDWORDval(accel2),SetDWORDval(speed2),SetDWORDval(distance2),flag);
}
bool Roboclaw::DutyAccelM1(uint8_t address, uint16_t duty, uint32_t accel){
return write_n(8,address,M1DUTYACCEL,SetWORDval(duty),SetDWORDval(accel));
}
bool Roboclaw::DutyAccelM2(uint8_t address, uint16_t duty, uint32_t accel){
return write_n(8,address,M2DUTYACCEL,SetWORDval(duty),SetDWORDval(accel));
}
bool Roboclaw::DutyAccelM1M2(uint8_t address, uint16_t duty1, uint32_t accel1, uint16_t duty2, uint32_t accel2){
return write_n(14,address,MIXEDDUTYACCEL,SetWORDval(duty1),SetDWORDval(accel1),SetWORDval(duty2),SetDWORDval(accel2));
}
bool Roboclaw::ReadM1VelocityPID(uint8_t address,float &Kp_fp,float &Ki_fp,float &Kd_fp,uint32_t &qpps){
uint32_t Kp,Ki,Kd;
bool valid = read_n(4,address,READM1PID,&Kp,&Ki,&Kd,&qpps);
Kp_fp = ((float)Kp)/65536;
Ki_fp = ((float)Ki)/65536;
Kd_fp = ((float)Kd)/65536;
return valid;
}
bool Roboclaw::ReadM2VelocityPID(uint8_t address,float &Kp_fp,float &Ki_fp,float &Kd_fp,uint32_t &qpps){
uint32_t Kp,Ki,Kd;
bool valid = read_n(4,address,READM2PID,&Kp,&Ki,&Kd,&qpps);
Kp_fp = ((float)Kp)/65536;
Ki_fp = ((float)Ki)/65536;
Kd_fp = ((float)Kd)/65536;
return valid;
}
bool Roboclaw::SetMainVoltages(uint8_t address,uint16_t min,uint16_t max){
return write_n(6,address,SETMAINVOLTAGES,SetWORDval(min),SetWORDval(max));
}
bool Roboclaw::SetLogicVoltages(uint8_t address,uint16_t min,uint16_t max){
return write_n(6,address,SETLOGICVOLTAGES,SetWORDval(min),SetWORDval(max));
}
bool Roboclaw::ReadMinMaxMainVoltages(uint8_t address,uint16_t &min,uint16_t &max){
bool valid;
uint32_t value = read4(address,GETMINMAXMAINVOLTAGES,&valid);
if(valid){
min = value>>16;
max = value&0xFFFF;
}
return valid;
}
bool Roboclaw::ReadMinMaxLogicVoltages(uint8_t address,uint16_t &min,uint16_t &max){
bool valid;
uint32_t value = read4(address,GETMINMAXLOGICVOLTAGES,&valid);
if(valid){
min = value>>16;
max = value&0xFFFF;
}
return valid;
}
bool Roboclaw::SetM1PositionPID(uint8_t address,float kp_fp,float ki_fp,float kd_fp,uint32_t kiMax,uint32_t deadzone,uint32_t min,uint32_t max){
uint32_t kp=kp_fp*1024;
uint32_t ki=ki_fp*1024;
uint32_t kd=kd_fp*1024;
return write_n(30,address,SETM1POSPID,SetDWORDval(kd),SetDWORDval(kp),SetDWORDval(ki),SetDWORDval(kiMax),SetDWORDval(deadzone),SetDWORDval(min),SetDWORDval(max));
}
bool Roboclaw::SetM2PositionPID(uint8_t address,float kp_fp,float ki_fp,float kd_fp,uint32_t kiMax,uint32_t deadzone,uint32_t min,uint32_t max){
uint32_t kp=kp_fp*1024;
uint32_t ki=ki_fp*1024;
uint32_t kd=kd_fp*1024;
return write_n(30,address,SETM2POSPID,SetDWORDval(kd),SetDWORDval(kp),SetDWORDval(ki),SetDWORDval(kiMax),SetDWORDval(deadzone),SetDWORDval(min),SetDWORDval(max));
}
bool Roboclaw::ReadM1PositionPID(uint8_t address,float &Kp_fp,float &Ki_fp,float &Kd_fp,uint32_t &KiMax,uint32_t &DeadZone,uint32_t &Min,uint32_t &Max){
uint32_t Kp,Ki,Kd;
bool valid = read_n(7,address,READM1POSPID,&Kp,&Ki,&Kd,&KiMax,&DeadZone,&Min,&Max);
Kp_fp = ((float)Kp)/1024;
Ki_fp = ((float)Ki)/1024;
Kd_fp = ((float)Kd)/1024;
return valid;
}
bool Roboclaw::ReadM2PositionPID(uint8_t address,float &Kp_fp,float &Ki_fp,float &Kd_fp,uint32_t &KiMax,uint32_t &DeadZone,uint32_t &Min,uint32_t &Max){
uint32_t Kp,Ki,Kd;
bool valid = read_n(7,address,READM2POSPID,&Kp,&Ki,&Kd,&KiMax,&DeadZone,&Min,&Max);
Kp_fp = ((float)Kp)/1024;
Ki_fp = ((float)Ki)/1024;
Kd_fp = ((float)Kd)/1024;
return valid;
}
bool Roboclaw::SpeedAccelDeccelPositionM1(uint8_t address,int32_t accel,int32_t speed,int32_t deccel,int32_t position,uint8_t flag){
return write_n(19,address,M1SPEEDACCELDECCELPOS,SetSignedDWORDval(accel),SetSignedDWORDval(speed),SetSignedDWORDval(deccel),SetSignedDWORDval(position),flag);
}
bool Roboclaw::SpeedAccelDeccelPositionM2(uint8_t address,int32_t accel,int32_t speed,int32_t deccel,int32_t position,uint8_t flag){
return write_n(19,address,M2SPEEDACCELDECCELPOS,SetSignedDWORDval(accel),SetSignedDWORDval(speed),SetSignedDWORDval(deccel),SetSignedDWORDval(position),flag);
}
bool Roboclaw::SpeedAccelDeccelPositionM1M2(uint8_t address,int32_t accel1,int32_t speed1,int32_t deccel1,int32_t position1,int32_t accel2,int32_t speed2,int32_t deccel2,int32_t position2,uint8_t flag){
return write_n(35,address,MIXEDSPEEDACCELDECCELPOS,SetSignedDWORDval(accel1),SetSignedDWORDval(speed1),SetSignedDWORDval(deccel1),SetSignedDWORDval(position1),SetSignedDWORDval(accel2),SetSignedDWORDval(speed2),SetSignedDWORDval(deccel2),SetSignedDWORDval(position2),flag);
}
bool Roboclaw::SetM1DefaultAccel(uint8_t address, uint32_t accel){
return write_n(6,address,SETM1DEFAULTACCEL,SetDWORDval(accel));
}
bool Roboclaw::SetM2DefaultAccel(uint8_t address, uint32_t accel){
return write_n(6,address,SETM2DEFAULTACCEL,SetDWORDval(accel));
}
bool Roboclaw::SetPinFunctions(uint8_t address, uint8_t S3mode, uint8_t S4mode, uint8_t S5mode){
return write_n(5,address,SETPINFUNCTIONS,S3mode,S4mode,S5mode);
}
bool Roboclaw::GetPinFunctions(uint8_t address, uint8_t &S3mode, uint8_t &S4mode, uint8_t &S5mode){
uint8_t crc;
bool valid = false;
uint8_t val1,val2,val3;
uint8_t trys=MAXRETRY;
int16_t data;
do{
flush();
crc_clear();
write(address);
crc_update(address);
write(GETPINFUNCTIONS);
crc_update(GETPINFUNCTIONS);
data = read();
crc_update(data);
val1=data;
if(data!=-1){
data = read();
crc_update(data);
val2=data;
}
if(data!=-1){
data = read();
crc_update(data);
val3=data;
}
if(data!=-1){
uint16_t ccrc;
data = read();
if(data!=-1){
ccrc = data << 8;
data = read();
if(data!=-1){
ccrc |= data;
if(crc_get()==ccrc){
S3mode = val1;
S4mode = val2;
S5mode = val3;
return true;
}
}
}
}
}while(trys--);
return false;
}
bool Roboclaw::SetDeadBand(uint8_t address, uint8_t Min, uint8_t Max){
return write_n(4,address,SETDEADBAND,Min,Max);
}
bool Roboclaw::GetDeadBand(uint8_t address, uint8_t &Min, uint8_t &Max){
bool valid;
uint16_t value = read2(address,GETDEADBAND,&valid);
if(valid){
Min = value>>8;
Max = value;
}
return valid;
}
bool Roboclaw::ReadEncoders(uint8_t address,uint32_t &enc1,uint32_t &enc2){
bool valid = read_n(2,address,GETENCODERS,&enc1,&enc2);
return valid;
}
bool Roboclaw::ReadISpeeds(uint8_t address,uint32_t &ispeed1,uint32_t &ispeed2){
bool valid = read_n(2,address,GETISPEEDS,&ispeed1,&ispeed2);
return valid;
}
bool Roboclaw::RestoreDefaults(uint8_t address){
return write_n(2,address,RESTOREDEFAULTS);
}
bool Roboclaw::ReadTemp(uint8_t address, uint16_t &temp){
bool valid;
temp = read2(address,GETTEMP,&valid);
return valid;
}
bool Roboclaw::ReadTemp2(uint8_t address, uint16_t &temp){
bool valid;
temp = read2(address,GETTEMP2,&valid);
return valid;
}
uint16_t Roboclaw::ReadError(uint8_t address,bool *valid){
return read2(address,GETERROR,valid);
}
bool Roboclaw::ReadEncoderModes(uint8_t address, uint8_t &M1mode, uint8_t &M2mode){
bool valid;
uint16_t value = read2(address,GETENCODERMODE,&valid);
if(valid){
M1mode = value>>8;
M2mode = value;
}
return valid;
}
bool Roboclaw::SetM1EncoderMode(uint8_t address,uint8_t mode){
return write_n(3,address,SETM1ENCODERMODE,mode);
}
bool Roboclaw::SetM2EncoderMode(uint8_t address,uint8_t mode){
return write_n(3,address,SETM2ENCODERMODE,mode);
}
bool Roboclaw::WriteNVM(uint8_t address){
return write_n(6,address,WRITENVM, SetDWORDval(0xE22EAB7A) );
}
bool Roboclaw::ReadNVM(uint8_t address){
return write_n(2,address,READNVM);
}
bool Roboclaw::SetConfig(uint8_t address, uint16_t config){
return write_n(4,address,SETCONFIG,SetWORDval(config));
}
bool Roboclaw::GetConfig(uint8_t address, uint16_t &config){
bool valid;
uint16_t value = read2(address,GETCONFIG,&valid);
if(valid){
config = value;
}
return valid;
}
bool Roboclaw::SetM1MaxCurrent(uint8_t address,uint32_t max){
return write_n(10,address,SETM1MAXCURRENT,SetDWORDval(max),SetDWORDval(0));
}
bool Roboclaw::SetM2MaxCurrent(uint8_t address,uint32_t max){
return write_n(10,address,SETM2MAXCURRENT,SetDWORDval(max),SetDWORDval(0));
}
bool Roboclaw::ReadM1MaxCurrent(uint8_t address,uint32_t &max){
uint32_t tmax,dummy;
bool valid = read_n(2,address,GETM1MAXCURRENT,&tmax,&dummy);
if(valid)
max = tmax;
return valid;
}
bool Roboclaw::ReadM2MaxCurrent(uint8_t address,uint32_t &max){
uint32_t tmax,dummy;
bool valid = read_n(2,address,GETM2MAXCURRENT,&tmax,&dummy);
if(valid)
max = tmax;
return valid;
}
bool Roboclaw::SetPWMMode(uint8_t address, uint8_t mode){
return write_n(3,address,SETPWMMODE,mode);
}
bool Roboclaw::GetPWMMode(uint8_t address, uint8_t &mode){
bool valid;
uint8_t value = read1(address,GETPWMMODE,&valid);
if(valid){
mode = value;
}
return valid;
}
| 29.407867 | 277 | 0.634434 | [
"object"
] |
d8e2b1fe15cc582ce259a89ea28a672bab03e697 | 6,585 | cpp | C++ | src/EC_Core/Components/tetromino.cpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | src/EC_Core/Components/tetromino.cpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | src/EC_Core/Components/tetromino.cpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | #include "tetromino.hpp"
#include "transform.hpp"
#include "appearance.hpp"
#include "collider.hpp"
#include "gamefield.hpp"
#include "soundeffects.hpp"
#include "../../debug.hpp"
#include "../../math.hpp"
#include "../../texture.hpp"
#include "../../media.hpp"
Tetromino::Tetromino() {
direction = 0;
type = TETRO_I;
src = {0, 0, 0, 0};
target = {0, 0, 0, 0};
rowIndex = 19;
colIndex = 4;
hold = false;
}
Tetromino::~Tetromino() {
Entity* gamefield = owner->manager.getEntityByName("Playfield");
if (!gamefield) return;
GameField* playfield = gamefield->getComponent<GameField>();
Appearance* appearance = owner->getComponent<Appearance>();
Texture* texture = appearance->getTexture();
if (!texture) return;
SDL_Rect src = appearance->getSrc();
for (int x = 0; x < src.h; x ++) {
for (int y = 0; y < src.w; y ++) {
CPixel* info = texture->getInfo(y + src.x, x + src.y);
playfield->occupy(rowIndex + x, colIndex + y, info);
}
}
}
void Tetromino::setHold(bool flag) {
hold = flag;
}
void Tetromino::rotateRight() {
if (!hold) return;
Collider* collider = owner->getComponent<Collider>();
int temp = (direction + 1) % 4;
if (!collider->willCollide(rowIndex, colIndex, src.x + temp * src.w, src.y, src.w, src.h)) {
direction = temp;
Entity* gamefield = owner->manager.getEntityByName("Playfield");
SoundEffects* sfx = gamefield->getComponent<SoundEffects>();
sfx->triggerRotate();
}
}
void Tetromino::rotateLeft() {
if (!hold) return;
Collider* collider = owner->getComponent<Collider>();
int temp = (direction + 3) % 4;
if (!collider->willCollide(rowIndex, colIndex, src.x + temp * src.w, src.y, src.w, src.h)) {
direction = temp;
Entity* gamefield = owner->manager.getEntityByName("Playfield");
SoundEffects* sfx = gamefield->getComponent<SoundEffects>();
sfx->triggerRotate();
}
}
void Tetromino::moveRight() {
if (!hold) return;
Collider* collider = owner->getComponent<Collider>();
if (!collider->willCollide(rowIndex, colIndex + 1, src.x + direction * src.w, src.y, src.w, src.h))
colIndex ++;
}
void Tetromino::moveLeft() {
if (!hold) return;
Collider* collider = owner->getComponent<Collider>();
if (!collider->willCollide(rowIndex, colIndex - 1, src.x + direction * src.w, src.y, src.w, src.h))
colIndex --;
}
void Tetromino::moveDown() {
if (!hold) return;
Collider* collider = owner->getComponent<Collider>();
if (!collider->willCollide(rowIndex + 1, colIndex, src.x + direction * src.w, src.y, src.w, src.h)) {
rowIndex ++;
Entity* gamefield = owner->manager.getEntityByName("Playfield");
SoundEffects* sfx = gamefield->getComponent<SoundEffects>();
sfx->triggerSoftDrop();
} else {
owner->destroy();
}
}
void Tetromino::harddrop() {
if (!hold) return;
rowIndex = target.y;
Entity* gamefield = owner->manager.getEntityByName("Playfield");
SoundEffects* sfx = gamefield->getComponent<SoundEffects>();
sfx->triggerHardDrop();
GameField* playfield = gamefield->getComponent<GameField>();
playfield->triggerAirflow(
rowIndex + typeOffsets[type][direction * 3 + 1],
colIndex + typeOffsets[type][direction * 3 + 0],
typeOffsets[type][direction * 3 + 2]);
owner->destroy();
}
void Tetromino::init() {
static std::vector<TetroType> bag = {};
if (bag.empty()) {
bag = {TETRO_I, TETRO_J, TETRO_L, TETRO_O, TETRO_S, TETRO_T, TETRO_Z};
std::random_shuffle(bag.begin(), bag.end());
}
type = TetroType(bag.back());
bag.pop_back();
src = typeInfo[type];
}
void Tetromino::update() {
if (hold) {
Entity* playfield = owner->manager.getEntityByName("Playfield");
Transform* playfieldTransform = playfield->getComponent<Transform>();
Appearance* appearance = owner->getComponent<Appearance>();
Transform* transform = owner->getComponent<Transform>();
transform->position.x = playfieldTransform->position.x + 1 + colIndex;
transform->position.y = playfieldTransform->position.y -19 + rowIndex;
appearance->setSrc(src.x + direction * src.w, src.y, src.w, src.h);
Collider* collider = owner->getComponent<Collider>();
collider->changeCollider(src.x + direction * src.w, src.y, src.w, src.h);
target = {colIndex, rowIndex, src.w, src.h};
while (!collider->willCollide(target.y + 1, target.x, src.x + direction * src.w, src.y, src.w, src.h)) {
target.y ++;
}
}
}
void Tetromino::render() {
Media* gfx = owner->game->getGFX();
Entity* interface = owner->manager.getEntityByName("Interface");
Transform* interfaceTransform = interface->getComponent<Transform>();
Appearance* appearance = owner->getComponent<Appearance>();
Texture* texture = appearance->getTexture();
if (hold) {
Entity* playfield = owner->manager.getEntityByName("Playfield");
Transform* playfieldTransform = playfield->getComponent<Transform>();
SDL_Rect tsrc = {src.x + direction * src.w, src.y, src.w, src.h};
SDL_Rect tdest = {static_cast<int>(round(interfaceTransform->position.x + 1)),
static_cast<int>(round(interfaceTransform->position.y + 2)),
src.w, src.h};
for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 4; j ++) {
gfx->setBackColor(0, 0, 0, 255, i + tdest.x, j + tdest.y);
}
}
if (src.w == 3) tdest.x ++;
if (src.h == 3) tdest.y ++;
gfx->drawTexture(texture, tsrc, tdest);
tdest.x = target.x + playfieldTransform->position.x + 1;
tdest.y = target.y + playfieldTransform->position.y -19;
gfx->drawTexture(texture, tsrc, tdest, 0.3);
} else {
SDL_Rect tsrc = {src.x + direction * src.w, src.y, src.w, src.h};
SDL_Rect tdest = {static_cast<int>(round(interfaceTransform->position.x + 17)),
static_cast<int>(round(interfaceTransform->position.y + 1)),
src.w, src.h};
for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 4; j ++) {
gfx->setBackColor(0, 0, 0, 255, i + tdest.x, j + tdest.y);
}
}
if (src.w == 3) tdest.x ++;
if (src.h == 3) tdest.y ++;
gfx->drawTexture(texture, tsrc, tdest);
}
}
| 35.403226 | 112 | 0.593014 | [
"render",
"vector",
"transform"
] |
d8e5190aecd91808752e420df42d6b5b521a8ebd | 738 | hh | C++ | astra-sim/system/Usage.hh | brianwuuu/astra-sim | b28636b8f6fecf41f486e5680b009447c7c124c3 | [
"MIT"
] | 35 | 2020-08-20T17:59:12.000Z | 2022-03-03T07:14:31.000Z | astra-sim/system/Usage.hh | brianwuuu/astra-sim | b28636b8f6fecf41f486e5680b009447c7c124c3 | [
"MIT"
] | 24 | 2020-08-24T22:27:15.000Z | 2022-03-05T14:19:49.000Z | astra-sim/system/Usage.hh | brianwuuu/astra-sim | b28636b8f6fecf41f486e5680b009447c7c124c3 | [
"MIT"
] | 24 | 2020-08-26T16:46:53.000Z | 2022-02-28T15:29:22.000Z | /******************************************************************************
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*******************************************************************************/
#ifndef __USAGE_HH__
#define __USAGE_HH__
#include <assert.h>
#include <math.h>
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <ctime>
#include <fstream>
#include <list>
#include <map>
#include <sstream>
#include <tuple>
#include <vector>
#include "Common.hh"
namespace AstraSim {
class Usage {
public:
int level;
uint64_t start;
uint64_t end;
Usage(int level, uint64_t start, uint64_t end);
};
} // namespace AstraSim
#endif | 23.0625 | 80 | 0.578591 | [
"vector"
] |
d8e6c8fdfb4e2062fd211957b432176dba1c951f | 1,794 | cpp | C++ | testbed/tests/environments/small_hills.cpp | DomiKoPL/BoxCar2D.cpp | a3bbb80304bccf7a8a232bfb8fe78718c47e03f7 | [
"MIT"
] | null | null | null | testbed/tests/environments/small_hills.cpp | DomiKoPL/BoxCar2D.cpp | a3bbb80304bccf7a8a232bfb8fe78718c47e03f7 | [
"MIT"
] | null | null | null | testbed/tests/environments/small_hills.cpp | DomiKoPL/BoxCar2D.cpp | a3bbb80304bccf7a8a232bfb8fe78718c47e03f7 | [
"MIT"
] | null | null | null | #include "small_hills.hpp"
#include <vector>
SmallHills::SmallHills(bool blocked) : CarEnvironment(blocked) {
m_map_width = 1000.f;
b2Vec2 gravity;
gravity.Set(0.0f, -20.0f);
m_world->SetGravity(gravity);
b2BodyDef groundBody;
groundBody.position.Set(0.0f, 0.0f);
b2Body* ground = m_world->CreateBody(&groundBody);
b2EdgeShape shape;
b2FixtureDef fd;
fd.shape = &shape;
fd.density = 0.0f;
fd.friction = 0.6f;
std::vector<b2Vec2> points {
b2Vec2(-200.0f, 0.0f),
b2Vec2(30.0f, 0.0f),
b2Vec2(100.f, 30.0f),
b2Vec2(200.f, 50.0f),
b2Vec2(300.f, -10.0f),
b2Vec2(350.f, 20.0f),
b2Vec2(400.f, 25.0f),
b2Vec2(600.f, 15.0f),
b2Vec2(900.f, 30.0f),
b2Vec2(m_map_width, 50.f),
b2Vec2(m_map_width + 20.f, 50.f)
};
for(int i = 1; i < points.size(); i++) {
shape.SetTwoSided(points[i - 1], points[i]);
ground->CreateFixture(&fd);
}
}
std::vector<float> SmallHills::evaluate_function(std::vector<Chromosome>& chromosomes)
{
Settings s_settings;
Lock();
CreateCars(chromosomes, 50);
if(not m_blocked)
{
DeleteCars();
}
Unlock();
auto stepsBefore = m_stepCount;
if(m_blocked)
{
while(m_stepCount - stepsBefore < 60 * 20)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
else
{
while(m_stepCount - stepsBefore < 60 * 20)
{
Step(s_settings);
}
}
Lock();
std::vector<float> dists;
for(int i = 0; i < chromosomes.size(); ++i)
{
dists.push_back(m_map_width - m_cars.at(i)->GetBody()->GetPosition().x);
}
Unlock();
return dists;
}
| 21.105882 | 86 | 0.555741 | [
"shape",
"vector"
] |
d8e6ce160958882dacb9ca683dc1006ee28a8603 | 573 | cpp | C++ | Difficulty 1/cups.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/cups.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | Difficulty 1/cups.cpp | BrynjarGeir/Kattis | a151972cbae3db04a8e6764d5fa468d0146c862b | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int N, r, d;
string color, number;
vector<pair<int, string>> cr;
cin >> N;
for(int i = 0; i < N; i++) {
cin >> color >> number;
bool digit = isdigit(color[0]);
if (digit) {
cr.push_back(make_pair(stoi(color), number));
} else {
cr.push_back(make_pair(stoi(number)*2, color));
}
}
sort(cr.begin(), cr.end());
for(pair<int, string> p: cr) {
cout << p.second << endl;
}
} | 21.222222 | 59 | 0.514834 | [
"vector"
] |
d8f2783ab7bb7f51812af10f28f5ae92f74dc924 | 928 | cpp | C++ | android-29/android/media/MediaSession2Service_MediaNotification.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/media/MediaSession2Service_MediaNotification.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/media/MediaSession2Service_MediaNotification.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../app/Notification.hpp"
#include "./MediaSession2Service_MediaNotification.hpp"
namespace android::media
{
// Fields
// QJniObject forward
MediaSession2Service_MediaNotification::MediaSession2Service_MediaNotification(QJniObject obj) : JObject(obj) {}
// Constructors
MediaSession2Service_MediaNotification::MediaSession2Service_MediaNotification(jint arg0, android::app::Notification arg1)
: JObject(
"android.media.MediaSession2Service$MediaNotification",
"(ILandroid/app/Notification;)V",
arg0,
arg1.object()
) {}
// Methods
android::app::Notification MediaSession2Service_MediaNotification::getNotification() const
{
return callObjectMethod(
"getNotification",
"()Landroid/app/Notification;"
);
}
jint MediaSession2Service_MediaNotification::getNotificationId() const
{
return callMethod<jint>(
"getNotificationId",
"()I"
);
}
} // namespace android::media
| 25.081081 | 123 | 0.757543 | [
"object"
] |
d8f3496b67fe8d7f132f64ed7ace5761e5d85954 | 1,430 | cpp | C++ | LightOJ/LOJ_AC/1076 - Get the Containers .cpp | Saikat-S/acm-problems-solutions | 921c0f3e508e1ee8cd14be867587952d5f67bbb9 | [
"MIT"
] | 3 | 2018-05-11T07:33:20.000Z | 2020-08-30T11:02:02.000Z | LightOJ/LOJ_AC/1076 - Get the Containers .cpp | Saikat-S/acm-problems-solutions | 921c0f3e508e1ee8cd14be867587952d5f67bbb9 | [
"MIT"
] | 1 | 2018-05-11T18:10:26.000Z | 2018-05-12T18:00:28.000Z | LightOJ/LOJ_AC/1076 - Get the Containers .cpp | Saikat-S/acm-problems-solutions | 921c0f3e508e1ee8cd14be867587952d5f67bbb9 | [
"MIT"
] | null | null | null | /***************************************************
* Problem name : 1076 - Get the Containers .cpp
* OJ : LOJ
* Result : Accepted
* Date : 29-03-17
* Problem Type : Binary Search
* Author Name : Saikat Sharma
* University : CSE, MBSTU
***************************************************/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define pii pair<int,int>
#define MAX 1005
using namespace std;
typedef long long ll;
ll ar[MAX],sm,n,m,mx;
ll BinarySearch(){
ll high = sm;
ll low = mx;
ll ans;
while(high>=low){
ll mid = (high+low)/2;
int sum = 0;
ll chk = 1;
for(int i = 0; i<n; i++){
sum+=ar[i];
if(sum>mid){
chk++;
sum = ar[i];
}
}
if(chk<=m){
high = mid -1;
ans = mid;
}
else{
low = mid+1;
}
}
return ans;
}
int main () {
ll tc;
scanf("%lld", &tc);
for(ll t = 1; t<=tc; t++){
scanf("%lld %lld", &n, &m);
sm = 0;
mx = 0;
for(int i = 0; i<n; i++){
scanf("%lld", &ar[i]);
if(mx<=ar[i]){
mx = ar[i];
}
sm+=ar[i];
}
printf("Case %lld: %lld\n",t,BinarySearch());
}
return 0;
}
| 20.140845 | 71 | 0.441958 | [
"vector"
] |
d8f7cdb8b0a5c6f721e8dd326c8654c949e3e255 | 3,040 | cpp | C++ | controllers/retagcontroller.cpp | ideeinc/Deepagent | 5d37ecf8e196d54d3914edc0c7b309377f772c1f | [
"BSD-3-Clause"
] | null | null | null | controllers/retagcontroller.cpp | ideeinc/Deepagent | 5d37ecf8e196d54d3914edc0c7b309377f772c1f | [
"BSD-3-Clause"
] | null | null | null | controllers/retagcontroller.cpp | ideeinc/Deepagent | 5d37ecf8e196d54d3914edc0c7b309377f772c1f | [
"BSD-3-Clause"
] | null | null | null | #include "retagcontroller.h"
#include "containers/retagsearchcontainer.h"
#include "containers/retagshowcontainer.h"
void RetagController::search()
{
switch (httpRequest().method()) {
case Tf::Get:
case Tf::Post: {
auto req = httpRequest();
QStringList args = { req.queryItemValue("tag0"), req.queryItemValue("tag1"), req.queryItemValue("tag2") };
if (args.filter(QRegExp("\\S+")).isEmpty()) {
auto container = service.search("", "", "", httpRequest(), session());
texport(container);
render();
} else {
auto url = urla("search", args);
redirect(url);
}
break; }
default:
renderErrorResponse(Tf::NotFound);
break;
}
}
void RetagController::search(const QString &tag0)
{
search(tag0, "", "");
}
void RetagController::search(const QString &tag0, const QString &tag1)
{
search(tag0, tag1, "");
}
void RetagController::search(const QString &tag0, const QString &tag1, const QString &tag2)
{
switch (httpRequest().method()) {
case Tf::Get: {
// serach, store session, show list
auto container = service.search(tag0, tag1, tag2, httpRequest(), session());
texport(container);
render();
break; }
case Tf::Post:
default:
renderErrorResponse(Tf::NotFound);
break;
}
}
void RetagController::sequential(const QString &index)
{
switch (httpRequest().method()) {
case Tf::Get: {
auto container = service.sequential(index, httpRequest(), session());
if (container.imagePath.isEmpty()) {
redirect(QUrl(recentAccessPath()));
} else {
texport(container);
render("show");
}
break; }
case Tf::Post: {
auto container = service.startSequential(recentAccessPath(), httpRequest(), session());
if (container.imagePath.isEmpty()) {
redirect(QUrl(recentAccessPath()));
} else {
texport(container);
render("show");
}
break; }
default:
renderErrorResponse(Tf::NotFound);
break;
}
}
void RetagController::show(const QString &image)
{
switch (httpRequest().method()) {
case Tf::Get: {
// show a image
auto container = service.show(image, session());
texport(container);
render();
break; }
case Tf::Post:
default:
renderErrorResponse(Tf::NotFound);
break;
}
}
void RetagController::save(const QString &image, int nextStep)
{
switch (httpRequest().method()) {
case Tf::Get: {
// show a image
service.saveForm(image, session());
break; }
case Tf::Post: {
// save
// nextStop 1:next 0:keep -1:prev
service.save(image, nextStep, session());
break; }
default:
renderErrorResponse(Tf::NotFound);
break;
}
}
// Don't remove below this line
T_DEFINE_CONTROLLER(RetagController)
| 24.32 | 114 | 0.574013 | [
"render"
] |
d8fe7fc150340a3af476f7fd11a73bcd87744a8e | 646 | cpp | C++ | notebook/math/sieve.cpp | brnpapa/icpc | 8149397daddc630e0fe2395f3f48e017154d223d | [
"MIT"
] | 19 | 2020-10-05T08:02:40.000Z | 2021-08-17T08:13:16.000Z | notebook/math/sieve.cpp | brnpapa/judge-resolutions | 8149397daddc630e0fe2395f3f48e017154d223d | [
"MIT"
] | null | null | null | notebook/math/sieve.cpp | brnpapa/judge-resolutions | 8149397daddc630e0fe2395f3f48e017154d223d | [
"MIT"
] | 10 | 2020-10-05T08:03:43.000Z | 2021-08-19T17:19:25.000Z | /*
Motivation: generate all primes until an upper bound UB < 10^7.
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int UB = 1e7;
vector<int> primes; // all primes in range [2..UB]
bitset<UB+1> is_composite;
/* O(UB*log(log(UB))) */
void build_sieve() {
primes.clear();
is_composite.reset(); is_composite[0] = is_composite[1] = 1;
for (ll i = 2; i <= UB; i++)
if (!is_composite[i]) {
primes.push_back(i);
// descarta todos os múltiplos de i, a partir de i*i
for (ll j = i*i; j <= UB; j += i)
is_composite[j] = 1;
}
}
int main() {
build_sieve();
}
| 21.533333 | 66 | 0.577399 | [
"vector"
] |
d8ff2b65369caf6ce8861e7928db82bee53f3d80 | 903 | cpp | C++ | cpp-leetcode/leetcode313-super-ugly-number_dp.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode313-super-ugly-number_dp.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode313-super-ugly-number_dp.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes)
{
int k = primes.size();
vector<int>p(k,0); /* p数组放有每个质数 2, 3, 5...等的指针, 一开始都是0 */
vector<int>results({1});
for (int i=0; i<n-1; i++)
{
int next = INT_MAX;
for (int j=0; j<k; j++)
next = min(next, primes[j] * results[p[j]]);
for (int j=0; j<k; j++)
{
if (next == primes[j] * results[p[j]])
p[j]++;
}
results.push_back(next);
}
return results.back();
}
};
// Test
int main()
{
Solution sol;
int n = 12;
vector<int> primes = {2, 7, 13, 19};
auto res = sol.nthSuperUglyNumber(n, primes);
cout << res << endl;
return 0;
} | 21.5 | 71 | 0.468439 | [
"vector"
] |
2b00e7e60b5a2f9478422a66aeb953981466eedd | 2,378 | cpp | C++ | CH6 Writing a Program/E09.cpp | essentialblend/cplusplus-mega | 23a91280532f246c96ad4d918bff4b8e15c30ac6 | [
"MIT"
] | null | null | null | CH6 Writing a Program/E09.cpp | essentialblend/cplusplus-mega | 23a91280532f246c96ad4d918bff4b8e15c30ac6 | [
"MIT"
] | null | null | null | CH6 Writing a Program/E09.cpp | essentialblend/cplusplus-mega | 23a91280532f246c96ad4d918bff4b8e15c30ac6 | [
"MIT"
] | null | null | null | /*IE09: Read digits from input and compose them into
integers. Handle number with one to four digits.
Hint: '5'-'0' == 5 (get integer value of character)*/
#include <iostream>
#include <vector>
std::vector<std::string> WordArray{ "thousand", "hundred", "ten", "one" };
int ConvertCharToInt(std::vector<int> TempVector)
{
if (TempVector.size() == 0)
{
throw std::runtime_error("Empty array was provided to Char->Int Array function.");
}
if (TempVector.size() > 4)
{
throw std::runtime_error("Char->Int function can only handle upto 4 digits.");
}
int TempInt{ 0 };
for (int i{ 0 }; i < TempVector.size(); i++)
{
TempInt = (10 * TempInt) + TempVector[i];
}
return TempInt;
}
void HandlePlurals(int TempInt)
{
if (TempInt == 0 || TempInt > 1) std::cout << "s";
if (TempInt == 1) return;
if (TempInt < 0) throw std::runtime_error("HandlePlurals() can only handle +ve numbers.");
}
void PrintResult(std::vector<int> TempVec, int UNum)
{
if (UNum > 9999)
{
throw std::runtime_error("PrintResult() can only handle upto 4 digits.");
}
if (TempVec.size() == 0)
{
throw std::runtime_error("PrintResult() was handed an empty number.");
}
std::cout << UNum << " is: ";
for (int i{ 0 }; i < TempVec.size(); i++)
{
std::cout << TempVec[i] << " " << WordArray[(double)i + 4 - TempVec.size()];
HandlePlurals(TempVec[i]);
if (i < (TempVec.size() - 1))
{
std::cout << " and ";
}
}
std::cout << ".\n";
}
int main()
try
{
std::vector<int> CharUserInput;
char UserChar{ ' ' };
std::cout << "Enter (up to a 4) digit number: ";
while (true)
{
while (std::cin >> UserChar)
{
if (UserChar == 'q') return 0;
if (UserChar < '0' || UserChar > '9')
{
std::cin.ignore(10000, '\n');
break;
}
CharUserInput.push_back(UserChar - '0');
}
int BufferInt = ConvertCharToInt(CharUserInput);
PrintResult(CharUserInput, BufferInt);
std::cout << "Try again...: ";
}
return 0;
}
catch (std::exception& exc)
{
std::cout << "Runtime error: " << exc.what() << "\n";
return 1;
}
catch (...)
{
std::cout << "Unknown exception!\n";
return 2;
}
| 25.847826 | 94 | 0.540791 | [
"vector"
] |
2b0a666390e09b2e369c5c6c8c75015e070f069e | 3,956 | cpp | C++ | virtual_clay_2/virtual_clay_2/src/d3d/d3d_camera.cpp | RythBlade/virtual_clay_2 | 987eeebe24521d7f3d8b38235121bb3f9c464b10 | [
"MIT"
] | null | null | null | virtual_clay_2/virtual_clay_2/src/d3d/d3d_camera.cpp | RythBlade/virtual_clay_2 | 987eeebe24521d7f3d8b38235121bb3f9c464b10 | [
"MIT"
] | null | null | null | virtual_clay_2/virtual_clay_2/src/d3d/d3d_camera.cpp | RythBlade/virtual_clay_2 | 987eeebe24521d7f3d8b38235121bb3f9c464b10 | [
"MIT"
] | null | null | null | // LCCREDIT start of 3DGraph1
#include <iostream>
#include "d3d_camera.h"
#include "settings/window_settings.h"
/*----------------------------------------------------------------------------\
* Camera defaults |
*----------------------------------------------------------------------------*/
#define DEFAULT_CAMERA_FOV DirectX::XM_PIDIV4
#define DEFAULT_CAMERA_NEAR_PLANE 0.01f
#define DEFAULT_CAMERA_FAR_PLANE 1000.0f
namespace virtual_clay
{
/*----------------------------------------------------------------------------\
* Initialisation and Clean up |
*----------------------------------------------------------------------------*/
/*
Constructs and initialises a camera object
*/
D3DCamera::D3DCamera()
{
m_cameraPos = DirectX::XMFLOAT3( 0.0f, 0.0f, -1.0f );
m_cameraTarget = DirectX::XMFLOAT3( 0.0f, 0.0f, 0.0f );
m_cameraUp = DirectX::XMFLOAT3( 0.0f, 1.0f, 0.0f );
m_horizontalRotation = 0.0f;
// make sure we are looking down the z axis
m_verticalRotation = DirectX::XM_PIDIV2;
m_radius = 1.0f;
m_nearPlane = DEFAULT_CAMERA_NEAR_PLANE;
m_farPlane = DEFAULT_CAMERA_FAR_PLANE;
m_fieldOfView = DEFAULT_CAMERA_FOV;
}
/*
Destructs a camera object
*/
D3DCamera::~D3DCamera()
{
}
/*----------------------------------------------------------------------------\
* Transformation pipeline code |
*----------------------------------------------------------------------------*/
/*
Sets the view and projection transformation matrices.
*/
void D3DCamera::setMatrices()
{
setViewMatrix();
setProjectionMatrix();
}
/*
Sets the view transformation matrix.
*/
void D3DCamera::setViewMatrix()
{
DirectX::FXMVECTOR cameraPos = DirectX::XMLoadFloat3( &m_cameraPos );
DirectX::FXMVECTOR cameraTarget = DirectX::XMLoadFloat3( &m_cameraTarget );
DirectX::FXMVECTOR cameraUp = DirectX::XMLoadFloat3( &m_cameraUp );
m_matView = DirectX::XMMatrixLookAtLH( cameraPos, cameraTarget, cameraUp );
}
/*
Sets the projection transformation matrix.
*/
void D3DCamera::setProjectionMatrix()
{
m_matProj = DirectX::XMMatrixPerspectiveFovLH( m_fieldOfView, g_defaultWindowWidth / g_defaultWindowWidth, m_nearPlane, m_farPlane );
}
/*----------------------------------------------------------------------------\
* Camera controls |
*----------------------------------------------------------------------------*/
/*
sets the horizontal rotation of the camera
Parameter list
rotation: to horizontal rotation of the camera
*/
void D3DCamera::setHorizontalRotation( float rotation )
{
m_horizontalRotation = fmod( rotation, 2.0f * DirectX::XM_PI );
updateCameraVectors();
}
/*
sets the vertical rotation of the camera
Parameter list
rotation: to vertical rotation of the camera
*/
void D3DCamera::setVerticalRotation( float rotation )
{
m_verticalRotation = rotation;
if ( m_verticalRotation > DirectX::XM_PI )
{
m_verticalRotation = DirectX::XM_PI;
}
else if ( m_verticalRotation < 0.0f )
{
m_verticalRotation = 0.0f;
}
updateCameraVectors();
}
void D3DCamera::setRadius( float radius )
{
if ( radius != 0 )
{
m_radius = radius;
if ( m_radius < 0.0f )
{
m_radius = 0.0f;
}
updateCameraVectors();
}
}
/*
recalculates and updates the camera vectors
*/
void D3DCamera::updateCameraVectors()
{
DirectX::XMFLOAT3 forward( sinf( m_horizontalRotation ), cosf( m_verticalRotation ), cosf( m_horizontalRotation ) );
DirectX::XMVECTOR vectorToNormalise = DirectX::XMLoadFloat3( &forward );
vectorToNormalise = DirectX::XMVector3Normalize( vectorToNormalise );
DirectX::XMStoreFloat3( &forward, vectorToNormalise );
m_cameraPos.x = m_radius * forward.x;
m_cameraPos.y = m_radius * forward.y;
m_cameraPos.z = m_radius * forward.z;
}
// end of 3DGraph1
} | 25.522581 | 135 | 0.575329 | [
"object"
] |
2b0aad1f9fc2186854ac717313b24d3f91323b9b | 3,820 | cpp | C++ | warn_unused_result/warn_unused_result.cpp | sinelaw/elfs-clang-plugins | a71525c90534806f9a12f15fb94c4ecbfdf9f41b | [
"MIT"
] | 97 | 2017-08-13T07:03:30.000Z | 2022-02-12T22:51:18.000Z | warn_unused_result/warn_unused_result.cpp | sinelaw/elfs-clang-plugins | a71525c90534806f9a12f15fb94c4ecbfdf9f41b | [
"MIT"
] | 3 | 2017-10-12T14:24:18.000Z | 2018-11-01T13:55:36.000Z | warn_unused_result/warn_unused_result.cpp | sinelaw/elfs-clang-plugins | a71525c90534806f9a12f15fb94c4ecbfdf9f41b | [
"MIT"
] | 6 | 2017-08-13T23:54:49.000Z | 2020-05-22T15:29:04.000Z | #include "../plugins_common.h"
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/MacroInfo.h>
#include <clang/AST/Decl.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/AST/ASTContext.h>
#include <clang/Tooling/Tooling.h>
#include <llvm/Support/raw_ostream.h>
#include <map>
#include <set>
#include <iostream>
#include <string>
#include <cinttypes>
// TODO accept as parameter
#define MAX_ALLOWED_ASSIGN_SIZE (64)
#define ON_DEBUG(x)
//#define ON_DEBUG(x) x
using namespace clang;
using namespace clang::ast_matchers;
namespace {
static void emit_warn(DiagnosticsEngine &diagEngine, SourceLocation loc)
{
unsigned diagID = diagEngine.getCustomDiagID(
diagEngine.getWarningsAsErrors()
? DiagnosticsEngine::Error
: DiagnosticsEngine::Warning,
"missing attribute warn_unused_result");
DiagnosticBuilder DB = diagEngine.Report(loc, diagID);
}
class WarnUnusedResultMatchCallback : public MatchFinder::MatchCallback
{
private:
bool m_static_only;
public:
WarnUnusedResultMatchCallback(bool static_only) : m_static_only(static_only) { }
virtual void run(const MatchFinder::MatchResult &Result)
{
ASTContext *context = Result.Context;
DiagnosticsEngine &diagEngine = context->getDiagnostics();
const FunctionDecl *func = Result.Nodes.getNodeAs<FunctionDecl>("badFunc");
const bool is_static = func->getStorageClass() == clang::StorageClass::SC_Static;
if (!is_static && m_static_only) return;
emit_warn(diagEngine, func->getLocation());
}
};
class WarnUnusedResultAction : public PluginASTAction {
bool m_static_only;
public:
WarnUnusedResultAction() {
m_static_only = false;
}
protected:
DeclarationMatcher missingWarnUnusedResultMatcher =
functionDecl(isExpansionInMainFile(),
unless(isImplicit()),
unless(hasName("main")),
unless(returns(asString("void"))),
unless(hasAttr(clang::attr::Kind::WarnUnusedResult))).bind("badFunc");
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &UNUSED(CI),
llvm::StringRef UNUSED(filename)) override
{
MatchFinder *const find = new MatchFinder();
find->addMatcher(missingWarnUnusedResultMatcher, new WarnUnusedResultMatchCallback(m_static_only));
return find->newASTConsumer();
}
const std::string param_static_only = "--static-only";
bool ParseArgs(const CompilerInstance &CI,
const std::vector<std::string> &args) override
{
if (args.size() == 0) {
return true;
}
if ((args.size() == 1) && (args.front() == param_static_only)) {
m_static_only = true;
return true;
}
DiagnosticsEngine &D = CI.getDiagnostics();
unsigned DiagID = D.getCustomDiagID(DiagnosticsEngine::Error,
"warn_unused_result plugin: invalid arguments");
D.Report(DiagID);
llvm::errs() << "warn_unused_result plugin: Accepted arguments: [" << param_static_only << "]\n";
return false;
}
};
}
static FrontendPluginRegistry::Add<WarnUnusedResultAction> X(
"warn_unused_result",
"Emit a warning about functions that lack a warn_unused_result attribute; use --static-only to ignore all non-static functions");
| 33.80531 | 133 | 0.623037 | [
"vector"
] |
2b12b3220e199817ae1bbd75a704e943b5aa999c | 25,049 | cpp | C++ | src/caskbench.cpp | bryceharrington/caskbench | 45f67bf2ab96f15ef2d99848ef150128b3d44465 | [
"BSD-3-Clause"
] | 4 | 2018-11-11T20:58:08.000Z | 2022-01-21T10:26:48.000Z | src/caskbench.cpp | Acidburn0zzz/caskbench | 45f67bf2ab96f15ef2d99848ef150128b3d44465 | [
"BSD-3-Clause"
] | null | null | null | src/caskbench.cpp | Acidburn0zzz/caskbench | 45f67bf2ab96f15ef2d99848ef150128b3d44465 | [
"BSD-3-Clause"
] | 3 | 2018-07-16T10:31:56.000Z | 2020-04-11T02:28:31.000Z | /*
* Copyright 2014 © Samsung Research America, Silicon Valley
*
* Use of this source code is governed by the 3-Clause BSD license
* specified in the COPYING file included with this source code.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <sys/time.h>
#include <popt.h>
#include <err.h>
#include "caskbench.h"
#include "caskbench_context.h"
#include "caskbench_result.h"
#include "device_config.h"
#include "tests.h"
#include "git_info.h"
typedef struct _caskbench_options {
int dry_run;
int iterations;
int json_output;
int list_surfaces;
char *output_file;
char *surface_type;
int size;
int version;
unsigned int disable_egl_sample_buffers;
char *shape_name;
int x_position;
int y_position;
int width;
int height;
char *fill_type;
char *fill_color;
char *stroke_color;
double red;
double green;
double blue;
double alpha;
int animation;
char *stock_image_path;
int stroke_width;
int cap_style;
int join_style;
int dash_style;
unsigned int enable_output_images;
double tolerance;
int canvas_width;
int canvas_height;
int list_tests;
int list_gles_versions;
int gles_version;
char *drawing_lib;
int list_drawing_libs;
int depth_size;
int luminance_size;
int min_swap_interval;
int max_swap_interval;
int match_native_pixmap;
int deferred_canvas;
int short_help;
const char **tests;
} caskbench_options_t;
typedef enum {
CB_STATUS_PASS,
CB_STATUS_FAIL,
CB_STATUS_ERROR,
CB_STATUS_CRASH,
} caskbench_status_t;
static const char *
_status_to_string(int result)
{
switch (result) {
case CB_STATUS_PASS:
return "PASS";
case CB_STATUS_FAIL:
return "FAIL";
case CB_STATUS_ERROR:
return "ERROR";
case CB_STATUS_CRASH:
return "CRASH";
default:
return "unknown";
}
}
static void
print_version()
{
printf("%s version %s+%.7s\n",
PACKAGE_NAME,
PACKAGE_VERSION,
git_sha);
}
static void
print_surfaces_available()
{
printf("image\n");
#if USE_GLX
printf("glx\n");
#endif
#if USE_EGL
printf("egl\n");
#endif
#if USE_XCB
printf("xcb\n");
#endif
}
static void
print_tests_available()
{
char *token = NULL;
char test_name[MAX_BUFFER];
for (int c = 0; c < num_perf_tests; c = c+2) {
memset (test_name, 0, sizeof(test_name));
strncpy (test_name, perf_tests[c].name, strlen(perf_tests[c].name));
token = strtok (test_name, "-");
if (token) {
token = strtok (NULL, "-");
printf("%s\n", token);
}
}
}
static void
print_gles_versions_available ()
{
#if HAVE_GLES2_H
printf("2\n");
#endif
#if HAVE_GLES3_H
printf("3\n");
#endif
}
static void
print_drawing_libs_available()
{
#if USE_CAIRO
printf("cairo\n");
#endif
#if USE_SKIA
printf("skia\n");
#endif
}
static void
print_json_result(FILE *fp, const caskbench_result_t *result)
{
fprintf(fp, " {\n");
fprintf(fp, " \"test case\": \"%s\",\n", result->test_case_name);
fprintf(fp, " \"size\": \"%d\",\n", result->size);
fprintf(fp, " \"status\": \"%s\",\n", _status_to_string(result->status));
fprintf(fp, " \"iterations\": %d,\n", result->iterations);
fprintf(fp, " \"minimum run time (s)\": %f,\n", result->min_run_time);
fprintf(fp, " \"average run time (s)\": %f,\n", result->avg_run_time);
fprintf(fp, " \"maximum run time (s)\": %f,\n", result->max_run_time);
fprintf(fp, " \"median run time (s)\": %f,\n", result->median_run_time);
fprintf(fp, " \"standard deviation of run time (s)\": %f,\n", result->standard_deviation);
fprintf(fp, " \"avg frames per second (fps)\": %-4.0f\n", result->avg_frames_per_second);
fprintf(fp, " }");
}
void
process_options(caskbench_options_t *opt, int argc, char *argv[])
{
int rc;
poptContext pc;
struct poptOption po[] = {
{"dry-run", 'n', POPT_ARG_NONE, &opt->dry_run, 0,
"Just list the selected test case names without executing",
NULL},
{"iterations", 'i', POPT_ARG_INT, &opt->iterations, 0,
"The number of times each test case should be run",
NULL},
{"json", 'j', POPT_ARG_NONE, &opt->json_output, 0,
"Write JSON style output to stdout",
NULL},
{"list-surfaces", 'l', POPT_ARG_NONE, &opt->list_surfaces, 0,
"List the available graphics surface types",
NULL},
{"output-file", 'o', POPT_ARG_STRING, &opt->output_file, 0,
"Filename to write JSON output to",
NULL},
{"surface-type", 't', POPT_ARG_STRING, &opt->surface_type, 0,
"Type of graphics surface to use (see --list-surfaces for available surfaces)",
NULL},
{"test-size", 's', POPT_ARG_INT, &opt->size, 0,
"Controls the complexity of the tests, such as number of drawn elements",
NULL},
{"version", 'V', POPT_ARG_NONE, &opt->version, 0,
"Display the program version and exit",
NULL},
{"disable-egl-sample-buffers", '\0', POPT_ARG_NONE, &opt->disable_egl_sample_buffers, 0,
"Turn off sample buffers in EGL attributes",
NULL},
{"shape", 'S', POPT_ARG_STRING, &opt->shape_name, 0,
"Controls which type of shape to draw for the test object (e.g. 'circle', 'star', etc.)",
NULL},
{"x-position", 'X', POPT_ARG_INT, &opt->x_position, 0,
"The X location to draw the test object",
NULL},
{"y-position", 'Y', POPT_ARG_INT, &opt->y_position, 0,
"The Y location to draw the test object",
NULL},
{"object-width", '\0', POPT_ARG_INT, &opt->width, 0,
"Width of the test object",
NULL},
{"object-height", '\0', POPT_ARG_INT, &opt->height, 0,
"Height of the test object",
NULL},
{"fill-type", 'f', POPT_ARG_STRING, &opt->fill_type, 0,
"Use specified fill style ('solid', 'linear-gradient', 'radial-gradient', 'image-pattern')",
NULL},
{"fill-color", '\0', POPT_ARG_STRING, &opt->fill_color, 0,
"RGBA color value for fill (e.g. ABCDEFFF)",
NULL},
{"stroke-color", '\0', POPT_ARG_STRING, &opt->stroke_color, 0,
"RGBA color value for stroke (e.g. ABCDEFFF)",
NULL},
{"animation", 'g', POPT_ARG_INT, &opt->animation, 0,
"Controls the kinematics of the objects drawn",
NULL},
{"image-path", 'I', POPT_ARG_STRING, &opt->stock_image_path, 0,
"Path to a stock image for use in clipping, patterns, etc.",
NULL},
{"stroke-width", '\0', POPT_ARG_INT, &opt->stroke_width, 0,
"Line width for stroked test objects",
NULL},
#if 0
{"cap-style", 'C', POPT_ARG_INT, &opt->cap_style, 0,
"Line ending style for stroked test objects",
NULL},
{"join-style", 'J', POPT_ARG_INT, &opt->join_style, 0,
"Corner type for multi-segmented, stroked test objects",
NULL},
{"dash-style", 'D', POPT_ARG_INT, &opt->dash_style, 0,
"Dash style for stroked test objects",
NULL},
#endif
{"enable-output-images", '\0', POPT_ARG_NONE, &opt->enable_output_images, 0,
"Generate image PNG files displaying the final rendering frame from each test run.",
NULL},
{"tolerance", '\0', POPT_ARG_DOUBLE, &opt->tolerance, 0,
"Sets tesselation tolerance value for cairo",
NULL},
{"canvas_width", 'W', POPT_ARG_INT, &opt->canvas_width, 0,
"Width of canvas used for each test case (defaults to 800)",
NULL},
{"canvas_height", 'H', POPT_ARG_INT, &opt->canvas_height, 0,
"Height of canvas used for each test case (defaults to 400)",
NULL},
{"list-tests", '\0', POPT_ARG_NONE, &opt->list_tests, 0,
"List the tests available",
NULL},
#if USE_EGL
{"list-gles-versions", '\0', POPT_ARG_NONE, &opt->list_gles_versions, 0,
"List the GLES versions available",
NULL},
{"gles-version", '\0', POPT_ARG_INT, &opt->gles_version, 0,
"GLES version to use",
NULL},
{"depth-size", '\0', POPT_ARG_INT, &opt->depth_size, 0,
"EGL depth size to use",
NULL},
{"luminance-size", '\0', POPT_ARG_INT, &opt->luminance_size, 0,
"EGL luminance size to use",
NULL},
{"min-swap-interval", '\0', POPT_ARG_INT, &opt->min_swap_interval, 0,
"EGL minimum swap interval to use",
NULL},
{"max-swap-interval", '\0', POPT_ARG_INT, &opt->max_swap_interval, 0,
"EGL maximum swap interval to use",
NULL},
{"match-native-pixmap", '\0', POPT_ARG_INT, &opt->match_native_pixmap, 0,
"EGL pixmap handle to use",
NULL},
{"deferred-rendering", '\0', POPT_ARG_NONE, &opt->deferred_canvas, 0,
"Creates Deferred Canvas for skia rendering for EGL backend. Deferred rendering records graphics commands and stores the intermediate result. It can be played back by the application appropriately.",
NULL},
#endif
{"list-drawing-libs", '\0', POPT_ARG_NONE, &opt->list_drawing_libs, 0,
"List the drawing libraries available",
NULL},
{"drawing-lib", 'D', POPT_ARG_STRING, &opt->drawing_lib, 0,
"Drawing libraries to be used for drawing (e.g. 'cairo', 'cairo,skia')",
NULL},
{"short-help", 'h', POPT_ARG_NONE, &opt->short_help, 0,
"Display brief usage message",
NULL},
POPT_AUTOHELP
{NULL}
};
// Initialize options
memset (opt, 0, sizeof(caskbench_options_t));
opt->iterations = 100;
opt->size = 100;
// Process the command line
pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
poptSetOtherOptionHelp(pc, "[ARG...]");
poptReadDefaultConfig(pc, 0);
while ((rc = poptGetNextOpt(pc)) >= 0) {
printf("%d\n", rc);
}
if (rc != -1) {
// handle error
switch(rc) {
case POPT_ERROR_NOARG:
errx(1, "Argument missing for an option\n");
case POPT_ERROR_BADOPT:
errx(1, "Unknown option or argument\n");
case POPT_ERROR_BADNUMBER:
case POPT_ERROR_OVERFLOW:
errx(1, "Option could not be converted to number\n");
default:
errx(1, "Unknown error in option processing\n");
}
}
if (opt->short_help) {
poptPrintHelp(pc, stdout, 0);
exit(0);
}
// Remaining args are the tests to be run, or all if this list is empty
opt->tests = poptGetArgs(pc);
}
double
get_tick (void)
{
struct timeval now;
gettimeofday (&now, NULL);
return (double)now.tv_sec + (double)now.tv_usec / 1000000.0;
}
uint32_t
convertToColorValue (const char* hexString)
{
char *end_ptr;
uint32_t color_val = 0;
int r, g, b;
if ((hexString == NULL) || (strlen(hexString) != 8))
{
color_val = -1;
return color_val;
}
color_val = strtoul(hexString, &end_ptr, 16);
return color_val;
}
void
shape_defaults_init(shapes *shape_defaults, caskbench_options_t *opt)
{
shape_defaults->x = opt->x_position;
shape_defaults->y = opt->y_position;
shape_defaults->dx1 = 0;
shape_defaults->dy1 = 0;
shape_defaults->dx2 = 0;
shape_defaults->dy2 = 0;
shape_defaults->width = opt->width;
shape_defaults->height = opt->height;
shape_defaults->shape_type = convertToShapeType(opt->shape_name);
shape_defaults->fill_type = convertToFillType(opt->fill_type);
shape_defaults->fill_color = convertToColorValue(opt->fill_color);
shape_defaults->stroke_color = convertToColorValue(opt->stroke_color);
shape_defaults->stroke_width = opt->stroke_width;
shape_defaults->animation = opt->animation;
shape_defaults->cap_style = opt->cap_style;
shape_defaults->join_style = opt->join_style;
shape_defaults->dash_style = opt->dash_style;
shape_defaults->radius = 0.0;
}
double median_run_time (double data[], int n)
{
double temp;
int i, j;
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
{
if (data[i] > data[j])
{
temp = data[j];
data[j] = data[i];
data[i] = temp;
}
}
if (n % 2 == 0)
return (data[n/2] + data[n/2-1])/2;
else
return data[n/2];
}
double standard_deviation (const double data[], int n, double mean)
{
double sum_deviation = 0.0;
int i;
for (i = 0; i < n; ++i)
sum_deviation += (data[i]-mean) * (data[i]-mean);
return sqrt (sum_deviation / n);
}
int
convertToTestId(const char* test_name)
{
int j = 0;
if (test_name == NULL)
return -1;
/* Checks whether the user provided test case is valid */
for(j = 0; j < num_perf_tests; j++) {
if (strcmp (perf_tests[j].name, test_name) == 0)
return j;
}
return -1;
}
void
process_drawing_libs (const char *libs, int &num_tests, int *test_ids)
{
int test_index = 0, j = 0;
int index = 0, i = -1;
char filter[MAX_BUFFER];
bool skia_cairo = false;
memset(filter, 0, sizeof(filter));
#ifndef USE_CAIRO
if (strstr(libs, "cairo"))
errx (0, "cairo is unavailable in the build\n");
#endif
#ifndef USE_SKIA
if (strstr(libs, "skia"))
errx (0, "skia is unavailable in this build\n");
#endif
/* Caskbench runs as usual */
if (strcmp(libs, "cairo,skia") == 0)
return;
if (strncmp(libs,"cairo", strlen(libs)) == 0)
strncpy(filter, "cairo", 5);
else if (strncmp(libs, "skia", strlen(libs)) == 0)
strncpy(filter, "skia", 4);
else if (strncmp(libs, "skia,cairo", strlen(libs)) == 0)
skia_cairo = true;
else
errx (0, "Invalid library is specified\n");
/* Handle the case if user has already provided list of tests to run */
index = num_tests ? num_tests:num_perf_tests;
for (j = 0; j < index; j++) {
i = (test_ids[j]!=-1) ? test_ids[j]:j;
if (strstr (perf_tests[i].name, filter) && !skia_cairo) {
test_ids[test_index++] = i;
}
if (skia_cairo) {
/* Add skia test followed by cairo */
test_ids[test_index++] = i+1;
test_ids[test_index++] = i;
j++;
}
}
num_tests = test_index;
}
void
populate_user_tests (const char** tests, int& num_tests, int* test_ids)
{
int i = 0, id = -1, test_index = 0;
char skia_test[MAX_BUFFER];
char cairo_test[MAX_BUFFER];
strncpy(cairo_test, "cairo-", 6);
strncpy(skia_test, "skia-", 5);
if (tests == NULL)
return;
while (tests[i] != NULL) {
if (strlen(tests[i])+6 >= MAX_BUFFER)
errx (0, "Invalid test case: test name is too long\n");
#ifdef USE_CAIRO
cairo_test[6] = '\0';
strncat(cairo_test, tests[i], strlen(tests[i]));
/* Add cairo test index to the test list */
id = convertToTestId (cairo_test);
if (id < 0)
errx (0, "Unrecognized cairo test case '%s'\n", cairo_test);
test_ids[test_index++] = id;
num_tests = num_tests + 1;
#endif
#ifdef USE_SKIA
skia_test[5] = '\0';
strncat(skia_test, tests[i], strlen(tests[i]));
/* Add skia test index to the test list */
id = convertToTestId (skia_test);
if (id < 0)
errx (0, "Unrecognized skia test case '%s'\n", skia_test);
test_ids[test_index++] = id;
num_tests = num_tests + 1;
#endif
i++;
}
}
int
main (int argc, char *argv[])
{
int c, i, num_user_tests = 0, num_tests = 0;
int user_test_ids[num_perf_tests];
caskbench_options_t opt;
double start_time, stop_time, run_time, run_total;
double cairo_avg_time = 0.0;
double skia_avg_time = 0.0;
FILE *fp = NULL;
char fname[256], *end_ptr;
device_config_t config;
int foo;
setenv("CAIRO_GL_COMPOSITOR", "msaa", 1);
process_options(&opt, argc, argv);
double run_time_values[opt.iterations];
memset (&config, 0, sizeof(device_config_t));
config.egl_min_swap_interval = -1;
config.egl_max_swap_interval = -1;
if (opt.version) {
print_version();
exit(0);
}
if (opt.list_surfaces) {
print_surfaces_available();
exit(0);
}
if (opt.list_tests) {
print_tests_available();
exit(0);
}
if(opt.list_gles_versions) {
print_gles_versions_available();
exit(0);
}
#if HAVE_GLES3_H
config.egl_gles_version = 3;
#elif HAVE_GLES2_H
config.egl_gles_version = 2;
#endif
if(opt.gles_version) {
if (opt.surface_type == NULL || (strncmp(opt.surface_type,"image",5)==0))
errx(0, "gles-version is not usable with image backend");
if (opt.gles_version < 2 || opt.gles_version > 3)
errx(0, "gles-version provided is invalid");
#ifndef HAVE_GLES2_H
if (opt.gles_version == 2)
errx(0, "gles-version 2 is not supported in the hardware");
#endif
#ifndef HAVE_GLES3_H
if (opt.gles_version == 3)
errx(0, "gles-version 3 is not supported in the hardware");
#endif
config.egl_gles_version = opt.gles_version;
}
if (opt.list_drawing_libs) {
print_drawing_libs_available();
exit(0);
}
if (opt.output_file) {
// start writing json to output file
fp = fopen(opt.output_file, "w");
fprintf(fp, "[\n");
}
if (opt.json_output) {
fprintf(stdout, "[\n");
}
if (!opt.disable_egl_sample_buffers) {
config.egl_samples = 4;
config.egl_sample_buffers = 1;
}
if (opt.depth_size)
config.egl_depth_size = opt.depth_size;
if (opt.luminance_size)
config.egl_luminance_size = opt.luminance_size;
if (opt.min_swap_interval)
config.egl_min_swap_interval = opt.min_swap_interval;
if (opt.max_swap_interval)
config.egl_max_swap_interval = opt.max_swap_interval;
if (opt.match_native_pixmap)
config.egl_match_native_pixmap = opt.match_native_pixmap;
memset (user_test_ids, -1, sizeof(user_test_ids));
populate_user_tests (opt.tests, num_user_tests, user_test_ids);
if(opt.drawing_lib)
process_drawing_libs (opt.drawing_lib, num_user_tests, user_test_ids);
num_tests = num_user_tests ? num_user_tests : num_perf_tests;
for(int s = 0; s < num_tests; s++) {
c = num_user_tests ? user_test_ids[s] : s;
caskbench_context_t context;
caskbench_result_t result;
/* Disable stroke: Displays no output to file */
if (!strncmp(perf_tests[c].name, "cairo-stroke", 12) ||
!strncmp(perf_tests[c].name, "skia-stroke", 11))
continue;
/* Reinitialize random seed to a known state */
srnd();
context_init(&context, opt.size);
if(opt.canvas_width)
context.canvas_width = opt.canvas_width;
if(opt.canvas_height)
context.canvas_height = opt.canvas_height;
if (opt.stock_image_path)
context.stock_image_path = opt.stock_image_path;
if (opt.surface_type && opt.deferred_canvas)
context.is_egl_deferred = !strncmp(opt.surface_type, "egl", 3);
else if (opt.deferred_canvas)
errx (0, "Deferred rendering is not available with the current configuration");
shape_defaults_init(&context.shape_defaults, &opt);
result_init(&result, perf_tests[c].name);
config.width = context.canvas_width;
config.height = context.canvas_height;
config.surface_type = opt.surface_type;
if(opt.tolerance)
context.tolerance = opt.tolerance;
perf_tests[c].context_setup(&context, config);
if (perf_tests[c].setup != NULL)
if (!perf_tests[c].setup(&context)) {
result.status = CB_STATUS_ERROR;
goto FINAL;
}
// If dry run, just list the test cases
if (opt.dry_run) {
printf("%s\n", perf_tests[c].name);
continue;
}
// Run once to warm caches and calibrate
perf_tests[c].test_case(&context);
run_total = 0;
for (i=opt.iterations; i>0; --i) {
try {
assert(perf_tests[c].test_case);
// Clearing the canvas between iterations
perf_tests[c].context_clear(&context);
start_time = get_tick();
// Execute test_case
if (perf_tests[c].test_case(&context))
result.status = CB_STATUS_PASS;
else
result.status = CB_STATUS_FAIL;
perf_tests[c].context_update(&context);
stop_time = get_tick();
run_time = stop_time - start_time;
run_time_values[opt.iterations-i] = run_time;
if (result.min_run_time < 0)
result.min_run_time = run_time;
else
result.min_run_time = MIN(run_time, result.min_run_time);
result.max_run_time = MAX(run_time, result.max_run_time);
run_total += run_time;
} catch (...) {
warnx("Unknown exception encountered\n");
result.status = CB_STATUS_CRASH;
goto FINAL;
}
}
result.iterations = opt.iterations - i;
result.avg_run_time = run_total / (double)result.iterations;
result.size = opt.size;
result.median_run_time = median_run_time (run_time_values, result.iterations);
result.standard_deviation = standard_deviation (run_time_values, result.iterations, result.avg_run_time);
result.avg_frames_per_second = (1.0 / result.avg_run_time);
result.avg_frames_per_second = (result.avg_frames_per_second<9999) ? result.avg_frames_per_second:9999;
// Write image to file
if (opt.enable_output_images && perf_tests[c].write_image) {
snprintf(fname, sizeof(fname), "%s.png", perf_tests[c].name);
perf_tests[c].write_image (fname, &context);
}
FINAL:
if (! opt.json_output) {
printf("%-20s %-4d %s %d %4.0f",
result.test_case_name,
result.size,
_status_to_string(result.status),
result.iterations,
result.avg_frames_per_second);
if (result.test_case_name[0] == 'c')
cairo_avg_time = result.avg_run_time;
if (result.test_case_name[0] == 's')
skia_avg_time = result.avg_run_time;
if (s%2 == 1) {
if (opt.drawing_lib != NULL) {
if ((strcmp(opt.drawing_lib, "cairo,skia") == 0)) {
double perf_improvement = (cairo_avg_time - result.avg_run_time)/cairo_avg_time;
printf(" %4.2f%%", perf_improvement * 100.0);
cairo_avg_time = 0.0;
}
else if ((strcmp(opt.drawing_lib, "skia,cairo") == 0)) {
double perf_improvement = (skia_avg_time - result.avg_run_time)/skia_avg_time;
printf(" %4.2f%%", perf_improvement * 100.0);
skia_avg_time = 0.0;
}
} else {
double perf_improvement = (cairo_avg_time - result.avg_run_time)/cairo_avg_time;
printf(" %4.2f%%", perf_improvement * 100.0);
cairo_avg_time = 0.0;
}
}
} else {
print_json_result(stdout, &result);
if (s < num_tests-1)
fprintf(stdout, ",");
fprintf(stdout, "\n");
}
printf("\n");
if (fp != NULL) {
print_json_result(fp, &result);
if (s < num_tests-1)
fprintf(fp, ",");
fprintf(fp, "\n");
}
if (perf_tests[c].teardown != NULL)
perf_tests[c].teardown();
perf_tests[c].context_destroy(&context);
}
if (opt.output_file) {
// End json
fprintf(fp, "]\n");
fclose(fp);
}
if (opt.json_output) {
// End json
fprintf(stdout, "]\n");
}
}
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
| 31.627525 | 208 | 0.584175 | [
"object",
"shape",
"solid"
] |
2b152251448ef95c7bfbe45575675bc02dd299a3 | 64,110 | cpp | C++ | examples/example_win32_directx10/main.cpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | 4 | 2021-05-09T23:33:54.000Z | 2022-03-06T10:16:31.000Z | examples/example_win32_directx10/main.cpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | null | null | null | examples/example_win32_directx10/main.cpp | Laxer3a/psdebugtool | 41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb | [
"MIT"
] | 6 | 2021-05-09T21:41:48.000Z | 2021-09-08T10:54:28.000Z | // Dear ImGui: standalone example application for DirectX 10
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx10.h"
#include <d3d10_1.h>
#include <d3d10.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
#include <stdio.h>
#include "GPUCommandGen.h"
#include "gpu_ref.h"
GPUCommandGen* gCommandReg = new GPUCommandGen();
GPUCommandGen* getCommandGen() {
return gCommandReg;
}
/*
DONE 1 - Activate / Deactivate the device.
DONE 4 - Properly display names.
DONE 2 - Time display with graduation in cycle and uS / Proper time scale display.
DONE A - Fix the bug of display ( I think it is not a fetch issue but a stupid flush problem to the rendering)
DONE B - I think I will resolve the issue of hidden/overwritten stuff using color channel : R = Write, W=Green, Blue=DMA.
DONE C - Display filtered events.
TOMORROW
D - Click on time and display log of events...
*/
// Data
static ID3D10Device* g_pd3dDevice = NULL;
static IDXGISwapChain* g_pSwapChain = NULL;
static ID3D10RenderTargetView* g_mainRenderTargetView = NULL;
struct ImageAssetDX10 {
ID3D10SamplerState* sampler;
ID3D10ShaderResourceView* textureView;
};
/* Load Texture, return handler */
static void* LoadImageRGBA(void* pixels, int width, int height, ImTextureID* textureOut) {
ImageAssetDX10* pNewAsset = new ImageAssetDX10();
{
D3D10_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D10_USAGE_DEFAULT;
desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D10Texture2D* pTexture = NULL;
D3D10_SUBRESOURCE_DATA subResource;
subResource.pSysMem = pixels;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
ZeroMemory(&srv_desc, sizeof(srv_desc));
srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srv_desc.Texture2D.MipLevels = desc.MipLevels;
srv_desc.Texture2D.MostDetailedMip = 0;
g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &pNewAsset->textureView);
pTexture->Release();
}
*textureOut = pNewAsset->textureView;
// Create texture sampler
{
D3D10_SAMPLER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
desc.MipLODBias = 0.f;
desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
desc.MinLOD = 0.f;
desc.MaxLOD = 0.f;
g_pd3dDevice->CreateSamplerState(&desc, &pNewAsset->sampler);
}
return pNewAsset;
}
static void ReleaseImage(void* handler) {
ImageAssetDX10* pAsset = (ImageAssetDX10*)handler;
if (pAsset->sampler) { pAsset->sampler->Release(); }
if (pAsset->textureView) { pAsset->textureView->Release(); }
delete pAsset;
}
// Forward declarations of helper functions
bool CreateDeviceD3D (HWND hWnd);
void CleanupDeviceD3D ();
void CreateRenderTarget ();
void CleanupRenderTarget ();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#include <math.h>
#include "helperString.h"
#include "psxevents.h"
#include "memoryMap.h"
#include "cpu/debugger.h"
#include "FileBrowser/ImGuiFileBrowser.h"
/* Problem :
- Block have a fixed length, but filling pace may be different.
Can NOT wait to have a block FILLED until it is added to the queue.
- Solution : length of life in second for an allocated block.
If some data are in it already ( != ZERO RECORDS ), the we push it back to the UI.
0.25 or 0.10 second per block per device seems nice.
Anyway low fill pace, mean that we waste memory BUT the waste is ridiculous.
*/
class Lock {
public:
Lock* allocateLock();
bool init();
void release();
void lock();
void unlock();
protected:
Lock() {}
};
// --------------- Lock_windows.cpp
#include <windows.h>
class WindowsLock : public Lock {
public:
WindowsLock():Lock(),ghMutex(0) {}
HANDLE ghMutex;
};
Lock* Lock::allocateLock() {
return new WindowsLock();
}
bool Lock::init() {
WindowsLock* wLock = (WindowsLock*)this;
wLock->ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
return (wLock->ghMutex != NULL);
}
void Lock::release() {
WindowsLock* wLock = (WindowsLock*)this;
CloseHandle(wLock->ghMutex);
}
void Lock::lock() {
WindowsLock* wLock = (WindowsLock*)this;
DWORD dwWaitResult = WaitForSingleObject(
wLock->ghMutex, // handle to mutex
INFINITE); // no time-out interval
}
void Lock::unlock() {
WindowsLock* wLock = (WindowsLock*)this;
ReleaseMutex(wLock->ghMutex);
}
// -----------
class PSXEventHolderPool {
bool InitPool(u32 megaByteAlloc);
void ReleasePool();
// Full Size (read only , any thread)
inline
u32 getTotalPoolSize() { return totalBlockAlloc; }
// (USB3 Side) Thread Pick rate
inline
u32 getCurrentAvailableInPool() {
return freeIndex;
}
// (USB3 Side, lock A) (USB3 will have its own small pool locally without lock.)
bool allocate(PSXEventHolder** ppStore, u32* amount_InOut);
// When currentAvailable < xxxx (done by polling by UI thread)
// UI Thread will gather an amount of block from all the devices and reclaim memory.
// (UI Thread Side, lock A)
void backToPool(PSXEventHolder** arrayOfHolders, u32 count);
private:
u32 totalBlockAlloc;
PSXEventHolder** freePool;
PSXEventHolder** usedPool;
u32 freeIndex;
u32 usedIndex;
Lock lockA;
};
class ExchangeUSB3ToUI {
bool init (u32 maxListSize);
void release ();
// (USB3 Side, lock B => Enqueue in list)
void pushToUI (Device* pDevice, PSXEventHolder* block);
// (UI Side, lock B => Swap the list (USB3 gets a nice empty list))
u32 UIGetNewData(Device** pDevices, PSXEventHolder** blocks);
Lock lockB;
PSXEventHolder** listHolder [2];
Device** listDevices[2];
int indexCurrentList;
int sizeCurrentList;
};
bool ExchangeUSB3ToUI::init (u32 maxListSize) {
bool res = lockB.init();
listHolder [0] = new PSXEventHolder*[maxListSize];
listHolder [1] = new PSXEventHolder*[maxListSize];
listDevices[0] = new Device*[maxListSize];
listDevices[1] = new Device*[maxListSize];
indexCurrentList = 0;
sizeCurrentList = 0;
// TODO Error on new.
return res;
}
void ExchangeUSB3ToUI::release () {
delete[] listHolder[0];
delete[] listHolder[1];
delete[] listDevices[0];
delete[] listDevices[1];
indexCurrentList = 0;
sizeCurrentList = 0;
lockB.release();
}
// (USB3 Side, lock B => Enqueue in list)
void ExchangeUSB3ToUI::pushToUI(Device* pDevice, PSXEventHolder* block) {
// By construction, we are sure that there are no more event holder than the list length...
lockB.lock();
listHolder [indexCurrentList][sizeCurrentList] = block;
listDevices[indexCurrentList][sizeCurrentList] = pDevice;
sizeCurrentList++;
lockB.unlock();
}
// (UI Side, lock B => Swap the list (USB3 gets a nice empty list))
u32 ExchangeUSB3ToUI::UIGetNewData(Device** pDevices, PSXEventHolder** blocks) {
lockB.lock();
// Get the list
blocks = listHolder [indexCurrentList];
pDevices = listDevices[indexCurrentList];
if (indexCurrentList == 1) {
indexCurrentList = 0;
} else {
indexCurrentList = 1;
}
u32 result = sizeCurrentList;
// Swap to empty list and give the UI the list of blocks...
sizeCurrentList = 0;
lockB.unlock();
return result;
}
// (USB3 Side, lock A) (USB3 will have its own small pool locally without lock.)
bool PSXEventHolderPool::allocate(PSXEventHolder** ppStore, u32* amount_inOut) {
bool res;
lockA.lock(); // Mutex stuff...
u32 amount = *amount_inOut;
if (freeIndex >= amount) {
// amountIn does not change.
} else {
// Take all the reserve.
amount = freeIndex;
}
res = (amount != 0);
if (amount) {
// Move holders to the user pool
memcpy(ppStore,&freePool[freeIndex - amount],amount * sizeof(PSXEventHolder*));
freeIndex -= amount;
// TODO : For now, for performance issue we do not track allocated block
// Normally could do store the pointers in use :
/*
for (int n=0; n < amount; n++) {
usedPool[ppStore[n]->poolIndex] = ppStore[n];
}
*/
}
lockA.unlock();
return res;
}
void PSXEventHolderPool::backToPool(PSXEventHolder** arrayOfHolders, u32 amount) {
lockA.lock(); // Mutex stuff...
if (amount) {
// Move holders to the user pool
memcpy(&freePool[freeIndex],arrayOfHolders,amount * sizeof(PSXEventHolder*));
freeIndex += amount;
// TODO : For now, for performance issue we do not track allocated block
// Normally could do store the pointers in use :
/*
for (int n=0; n < amount; n++) {
usedPool[arrayOfHolders[n]->poolIndex] = NULL;
}
*/
}
lockA.unlock();
}
bool PSXEventHolderPool::InitPool(u32 megaByteAlloc) {
u64 memoryNeeded = ((u64)megaByteAlloc) * 1024 * 1024;
u64 sizeofBlock = sizeof(PSXEventHolder);
u64 blockNeeded = memoryNeeded / sizeofBlock;
// Allocate pointer to pool.
freePool = new PSXEventHolder*[blockNeeded];
usedPool = new PSXEventHolder*[blockNeeded];
if (freePool && usedPool) {
totalBlockAlloc = blockNeeded;
for (int n=0; n < blockNeeded; n++) {
freePool[n] = new PSXEventHolder(); // Memory consumption happens here, no check for now.
freePool[n]->poolIndex = n;
usedPool[n] = NULL;
}
freeIndex = blockNeeded;
usedIndex = 0;
lockA.init();
return true;
} else {
totalBlockAlloc = 0;
delete[] freePool;
delete[] usedPool;
return false;
}
}
void PSXEventHolderPool::ReleasePool() {
for (int n=0; n < freeIndex; n++) {
delete freePool[n];
}
for (int n=0; n < usedIndex; n++) {
delete usedPool[n];
}
delete[] freePool; freePool = NULL;
delete[] usedPool; usedPool = NULL;
totalBlockAlloc = 0;
usedIndex = 0;
freeIndex = 0;
lockA.release();
}
// UI thread stuff :
void ReclaimEventHolderFromDevices(u64 timeLimit, PSXEventHolder** storage, u32* result) {
u32 resultCount = 0;
u32 deviceCount;
Device** pDevices = getDevices(deviceCount);
for (int n=0; n < deviceCount; n++) {
PSXEventHolder* record = pDevices[n]->recordsStart;
while (true) {
if (record && record->lastTime < timeLimit) {
storage[resultCount] = record;
record = record->nextHolder;
// Make list empty, timing will be reset by alloc of events.
storage[resultCount]->eventCount = 0;
resultCount++;
} else {
pDevices[n]->recordsStart = record; // TODO NULL becomes possible, not sure UI is handling this.
// TODO : Check recordLast also updated correctly.
break;
}
}
}
*result = resultCount;
}
void Device::clearEvents() {
PSXEventHolder* pRoot = this->recordsStart;
PSXEventHolder* pParse = pRoot ? pRoot->nextHolder : NULL;
// Keep only one record, make it empty.
this->recordsLast = pRoot;
pRoot->nextHolder = NULL;
pRoot->eventCount = 0;
pRoot->startTime = 0;
pRoot->lastTime = 0;
while (pParse) {
PSXEventHolder* pNext = pParse->nextHolder;
/*
storage[resultCount]->eventCount = 0;
resultCount++;
*/
delete pParse; // TODO RELEASE INTO POOL AGAIN.
pParse = pNext;
}
}
void ClearAllDevices() {
u32 deviceCount;
Device** pDevices = getDevices(deviceCount);
for (u32 n=0; n < deviceCount; n++) {
pDevices[n]->clearEvents();
}
}
// UI thread stuff : New Records to UI
void InsertEventsToDevices(PSXEventHolder** storageList, Device** deviceList, u32 recordCount) {
// By construction each device in the list is having its timing in order.
for (int n=0; n < recordCount; n++) {
PSXEventHolder* pHolder = *storageList++;
Device* pDevice = *deviceList++;
// TODO : Put assert if last record in device does not match time.
pDevice->recordsLast->nextHolder = pHolder;
pDevice->recordsLast = pHolder;
pHolder->nextHolder = NULL; // In case.
}
}
// TODO : USB3 will have to send PSXEventHolder blocks even if not full with a timelimit
// => Low frequency event registering still need to have UI reflecting the changes.
class ConvertScale {
float width;
float timePerPixel;
double startTime;
double endTime;
float clock;
public:
void setClock(int clockMhz) { clock = clockMhz; }
void setDisplaySize(float w) { width = w; }
void setTime(u64 start, u64 end) {
startTime = start;
endTime = end;
setTimeScaleForWidth(end-start);
}
inline float getWidth() { return width; }
// In Clock
inline float getClock() { return clock; }
// In Clock
inline float getStartTime() { return startTime; }
// In Clock
inline float getEndTime() { return endTime; }
void setTimeScaleForWidth(float duration) {
timePerPixel = width / duration;
}
void setTimeScalePerPixel(float duration) { timePerPixel = duration; }
inline double PixelToTimeDistance(float pixel) {
return pixel / timePerPixel;
}
inline double PixelToTime(float pixel) {
return (pixel / timePerPixel) + startTime;
}
/* Rounded to nearest left pixel */
inline float TimeToPixel(double time) {
return trunc((time-startTime) * timePerPixel);
}
inline float TimeToPixelDistance(double time) {
return trunc((time / (endTime-startTime)* width));
}
};
ConvertScale timeScale;
const float DEVICE_TITLE_W = 100.0f;
struct Filter {
void Reset() {
deleteMe = false;
filterAddr = false;
filterValue = false;
filterRead = false;
filterWrite = false;
filterCondition = false;
compAddr = 0;
compValue = 0;
activeFilterColor.x = 1.0f;
activeFilterColor.y = 1.0f;
activeFilterColor.z = 1.0f;
activeFilterColor.w = 1.0f;
compAddrTxt[0] = 0;
compValueTxt[0] = 0;
compCount = 0;
}
bool deleteMe;
bool filterAddr;
bool filterValue;
bool filterRead;
bool filterWrite;
bool filterCondition;
u32 compAddr;
u32 compValue;
char compAddrTxt[10];
char compValueTxt[10];
ImVec4 activeFilterColor;
u32 activeFilterColor32;
int compCount;
int runCount;
};
PSXEvent** eventList = new PSXEvent*[50000];
int eventListCount = 0;
// Edition Filters
Filter filters[100];
int filterCount = 0;
// Display Filters
Filter displayfilters[100];
int displayfilterCount = 0;
void U32ToHex(u8* buff, u32 v) {
*buff++ = 'h';
for (int t=28; t <= 0; t-=4) {
int p = v>>t & 0xF;
if (p < 10) {
*buff++ = '0' + p;
} else {
*buff++ = 'A' + p;
}
}
*buff++ = 0;
}
u8* found(u8* start, u8* sub) {
const char* res;
if (res = strstr((const char*)start,(const char*)sub)) {
res += strlen((const char*)sub);
return (u8*)res;
}
return NULL;
}
u64 ValueHexAfter(u8* start, u8* pattern) {
// Only space and hexa.
// Stop on others.
// Only space and 0..9
// Stop on others.
u8* res = found(start, pattern);
u64 result = -1;
if (res) {
result = 0;
while (*res == ' ') {
res++;
}
// parse all spaces
while ((*res >= '0' && *res <= '9') || (*res >= 'a' && *res <='f') || (*res >= 'A' && *res <= 'F')) {
int v = 0;
if (*res >= '0' && *res <= '9') {
v = (*res - '0');
} else {
if (*res >= 'A' && *res <= 'F') {
v = (*res - 'A') + 10;
} else {
v = (*res - 'a') + 10;
}
}
result = (result * 16) + v;
res++;
}
}
return result;
}
u64 ValueIntAfter(u8* start, u8* pattern) {
// Only space and 0..9
// Stop on others.
u8* res = found(start, pattern);
u64 result = -1;
if (res) {
result = 0;
while (*res == ' ') {
res++;
}
// parse all spaces
while (*res >= '0' && *res <= '9') {
result = (result * 10) + (*res - '0');
res++;
}
}
return result;
}
u32 TextAddrToU32(const char* text) {
// Remove white space.
while (*text != 0 && *text <= ' ') {
text++;
}
// Support Hex
if (*text == 'x' || *text == 'h') {
text++;
return ValueHexAfter((u8*)text,(u8*)"");
}
// Support Int
return ValueIntAfter((u8*)text,(u8*)"");
// Support Constant name for ADR.
// ?;
// Error / undecoded.
return 0xFFFFFFFF;
}
u32 TextValueToU32(const char* text) {
// Remove white space.
while (*text != 0 && *text <= ' ') {
text++;
}
// Support Hex
if (*text == 'x' || *text == 'h') {
text++;
return ValueHexAfter((u8*)text,(u8*)"");
}
// Support Int
return ValueIntAfter((u8*)text,(u8*)"");
}
void ApplyFilters() {
u32 deviceCount;
Device** pDevices = getDevices(deviceCount);
for (int n=0; n < deviceCount; n++) {
// Reset per device
for (int f=0; f < filterCount; f++) {
// At least one parameter is active.
filters[f].runCount = 0;
}
PSXEvent* pEvent;
PSXEventHolder* pHolder;
pDevices[n]->FindEvent(0,&pHolder,&pEvent);
while (pEvent) {
pEvent->filterID = 0; // Reset Event default.
// If multiple filter matches, last filter override.
for (int f=0; f < filterCount; f++) {
// At least one parameter is active.
if (filters[f].filterAddr | filters[f].filterValue | filters[f].filterRead | filters[f].filterWrite) {
bool addrMatch = ((filters[f].filterAddr && (pEvent->adr == filters[f].compAddr )) || (!filters[f].filterAddr ));
bool ValueMatch = ((filters[f].filterValue && (pEvent->value == filters[f].compValue)) || (!filters[f].filterValue));
bool readMatch = (filters[f].filterRead && ((pEvent->type == READ_ADR ) || (pEvent->type == READ_DMA )));
bool writeMatch = (filters[f].filterWrite && ((pEvent->type == WRITE_ADR) || (pEvent->type == WRITE_DMA)));
bool countMatch = ((filters[f].filterCondition && (filters[f].compCount == filters[f].runCount)) || !filters[f].filterCondition);
if (addrMatch && ValueMatch && (readMatch || writeMatch)) {
if (countMatch) {
pEvent->filterID = f + 1;
}
filters[f].runCount++;
}
}
}
pEvent = pHolder->GetNextEvent(pEvent,&pHolder);
}
}
// [Copy filters for display]
memcpy(displayfilters, filters, sizeof(Filter) * 100);
displayfilterCount = filterCount;
}
void ApplyGTEFilter() {
DeviceSingleOp* pGTE = ((DeviceSingleOp*)getDeviceFromType(GTE_T));
PSXEvent* pEvent;
PSXEventHolder* pHolder;
pGTE->FindEvent(0,&pHolder,&pEvent);
while (pEvent) {
pEvent->filterID = 1; // Put near black color by default.(Make then transparent)
if (pEvent->type == READ_DMA) {
// 32 instructions.
u32 opcode = pEvent->value & 0x1F;
u32 color;
switch (opcode) {
case 0x01: color = 0xFF0000FF; break; // RTPS 15 Perspective Transformation single
case 0x06: color = 0xFF00FF00; break; // NCLIP 8 Normal clipping
case 0x0C: color = 0xFFFF0000; break; // OP(sf) 6 Outer product of 2 vectors
case 0x10: color = 0xFFFF00FF; break; // DPCS 8 Depth Cueing single
case 0x11: color = 0xFFFFFF00; break; // INTPL 8 Interpolation of a vector and far color vector
case 0x12: color = 0xFF00FFFF; break; // MVMVA 8 Multiply vector by matrix and add vector (see below)
case 0x13: color = 0xFF00008F; break; // NCDS 19 Normal color depth cue single vector
case 0x14: color = 0xFF008F00; break; // CDP 13 Color Depth Que
case 0x16: color = 0xFF8F0000; break; // NCDT 44 Normal color depth cue triple vectors
case 0x1B: color = 0xFF8F00FF; break; // NCCS 17 Normal Color Color single vector
case 0x1C: color = 0xFF8F8F00; break; // CC 11 Color Color
case 0x1E: color = 0xFF008F8F; break; // NCS 14 Normal color single
case 0x20: color = 0xFF0000FF; break; // NCT 30 Normal color triple
case 0x28: color = 0xFF00FF00; break; // SQR(sf)5 Square of vector IR
case 0x29: color = 0xFFFF0000; break; // DCPL 8 Depth Cue Color light
case 0x2A: color = 0xFFFF00FF; break; // DPCT 17 Depth Cueing triple (should be fake=08h, but isn't)
case 0x2D: color = 0xFFFFFF00; break; // AVSZ3 5 Average of three Z values
case 0x2E: color = 0xFF00FFFF; break; // AVSZ4 6 Average of four Z values
case 0x30: color = 0xFF00008F; break; // RTPT 23 Perspective Transformation triple
case 0x3D: color = 0xFF008F00; break; // GPF(sf)5 General purpose interpolation
case 0x3E: color = 0xFF8F0000; break; // GPL(sf)5 General purpose interpolation with base
case 0x3F: color = 0xFF8F00FF; break; // NCCT 39 Normal Color Color triple vector
default : color = 0xFFFFFFFF; break; //
}
pEvent->filterID = color;
}
pEvent = pHolder->GetNextEvent(pEvent,&pHolder);
}
}
#include "imgui_memory_editor.h"
static MemoryEditor mem_edit;
static bool firstMemEdit = true;
u8 bufferRAM [1024*1024*2]; // PSX RAM, consider as cache.
bool bufferRAML[1024*1024*2];
u8 scratchPad[1024];
u16 bufferVRAM[1024*512];
static DebugCtx cpu;
ImU8 ReadCallBack(const ImU8* data, size_t off) {
// TODO : If data not present, request through protocol... and cache using bufferRAML bit.
off &= 0x1FFFFFFF;
if ((off >= 0 && off < 0x200000)) {
return bufferRAM[off & 0x1FFFFF];
} else {
return off & 1 ? 0xAD : 0xDE;
}
}
void UIMemoryEditorWindow() {
if (firstMemEdit) {
firstMemEdit = false;
mem_edit.ReadFn = ReadCallBack;
}
// static int g = 0;
// g+=4;
// mem_edit.GotoAddr = g;
mem_edit.DrawWindow("Memory Editor", bufferRAM, 1024*1024*2);
}
// pEvent->isRead()
void RenderIOAdr(bool isRead, bool isWrite, u32 addr, u32 value) {
MemoryMapEntry* pEntries = GetBaseEntry(addr);
if (pEntries) {
bool isReadEvent = isRead;
bool isWriteEvent = isWrite;
while (pEntries) {
int rights = pEntries->sizeMask; // 8 / 16
if ((rights == 0) || ((rights & 8) && isWriteEvent) || ((rights & 16) && isReadEvent)) {
if (isWriteEvent) {
// WRITE RED
ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), pEntries->desc);
} else {
// READ GREEN
ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), pEntries->desc);
}
if (pEntries->bitDescArray) {
BitDesc* bitDescArray = pEntries->bitDescArray;
while (bitDescArray->desc) {
u32 v = (value>>bitDescArray->pos) & ((1<<bitDescArray->count)-1);
const char* optDesc = "";
EnumDesc* pEnum = bitDescArray->enums;
while (pEnum) {
if (pEnum->value == v) {
optDesc = pEnum->desc;
break;
}
pEnum = pEnum->next;
}
if (bitDescArray->count == 1) {
bool vb = v ? true : false;
char buff[256];
sprintf(buff,"[%i %s] %s (Bit %i)",v,optDesc,bitDescArray->desc, bitDescArray->pos);
ImGui::Checkbox(buff,&vb);
} else {
if (bitDescArray->format == FORMAT_HEXA) {
ImGui::LabelText("","[%x %s] - %s (Bit %i~%i)",v,optDesc,bitDescArray->desc, bitDescArray->pos,bitDescArray->pos + bitDescArray->count - 1);
} else {
ImGui::LabelText("","[%i %s] - %s (Bit %i~%i)",v,optDesc,bitDescArray->desc, bitDescArray->pos,bitDescArray->pos + bitDescArray->count - 1);
}
}
bitDescArray++;
}
}
}
pEntries = pEntries->nextIdentical;
}
} else {
ImGui::LabelText("","Undefined Addr %p",addr);
}
ImGui::Separator();
}
MemoryMapEntry* selectedIO = NULL;
PSXEvent* selectedEvent = NULL;
void RenderDeviceIOs(DeviceSingleOp* device) {
u32 sa = device->startAdr;
u32 ea = device->endAdr;
MemoryMapEntry* lastEntry = NULL;
static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
if (ImGui::BeginTable("table",5, flags)) {
ImGui::TableSetupColumn("ADDR");
ImGui::TableSetupColumn("DESC");
ImGui::TableHeadersRow();
for (u32 n=sa; n < ea; n++) {
MemoryMapEntry* entry = GetBaseEntry(n);
if (entry && entry != lastEntry) {
ImGui::TableNextRow();
ImGui::PushID(n);
// --------- ADDR -----
ImGui::TableSetColumnIndex(0);
ImGui::LabelText("","A=%08x",entry->addr);
// --------- DESC -----
ImGui::TableSetColumnIndex(1);
if (ImGui::Button("SEL")) {
selectedIO = entry;
selectedEvent = NULL;
}
ImGui::SameLine();
ImGui::LabelText("",entry->desc);
ImGui::PopID();
lastEntry = entry;
}
}
ImGui::EndTable();
}
}
void UIMemoryIOWindow(PSXEvent* pEvent) {
ImGui::Begin("IO"); // Create a window called "Hello, world!" and append into it.
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
if (selectedIO) {
RenderIOAdr(true,true,selectedIO->addr,GetValueIO(selectedIO));
} else {
if (pEvent) {
RenderIOAdr(pEvent->isRead(), pEvent->isWrite(), pEvent->adr, pEvent->value);
}
}
if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
{
// || device[MC1]->CheckAdr(adr) => Auto display tab.
if (ImGui::BeginTabItem("MC1"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(MC1_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("JOY/SIO"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(JOY_T));
RenderDeviceIOs(device);
device = ((DeviceSingleOp*)getDeviceFromType(SIO_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("MC2"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(MC2_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("INT CTRL"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(IRQ_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("DMA"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(DMA_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("TMR"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(TMR_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("CDR"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(CDR_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("GPU"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(GPU_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("MDEC"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(MDEC_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("SPU"))
{
DeviceSingleOp* device = ((DeviceSingleOp*)getDeviceFromType(SPU_T));
RenderDeviceIOs(device);
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::End();
}
void UIFilterList() {
ImGui::PushItemWidth(100.0f);
bool noDelete = true;
for (int n=0; n < filterCount; n++) {
ImGui::PushID(n);
if (ImGui::Button("[DEL]")) {
filters[n].deleteMe = true;
noDelete = false;
}
ImGui::SameLine();
ImGui::Checkbox("Match Adr:",&filters[n].filterAddr);
ImGui::SameLine();
if (filters[n].filterAddr) {
ImGui::PushID("A");
ImGui::InputText("", filters[n].compAddrTxt, 10, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
// Hex to int
filters[n].compAddr = ValueHexAfter((u8*)filters[n].compAddrTxt,(u8*)"");
ImGui::SameLine();
ImGui::PopID();
}
ImGui::Checkbox("Match Val:",&filters[n].filterValue);
ImGui::SameLine();
if (filters[n].filterValue) {
ImGui::PushID("B");
ImGui::InputText("", filters[n].compValueTxt, 10, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
// Hex to int
filters[n].compValue = ValueHexAfter((u8*)filters[n].compValueTxt,(u8*)"");
ImGui::SameLine();
ImGui::PopID();
}
ImGui::Checkbox("[R]",&filters[n].filterRead);
ImGui::SameLine();
ImGui::Checkbox("[W]",&filters[n].filterWrite);
ImGui::SameLine();
ImGui::Checkbox("Hit Count:",&filters[n].filterCondition);
if (filters[n].filterCondition) {
ImGui::PushID("C");
ImGui::SameLine();
ImGui::InputInt("",&filters[n].compCount);
ImGui::PopID();
}
ImGui::SameLine();
ImGuiColorEditFlags misc_flags = 0;
if (ImGui::ColorEdit4("MyColor##3", (float*)&filters[n].activeFilterColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags)) {
u32 color32 = 0xFF000000;
int r = filters[n].activeFilterColor.x * 255;
int g = filters[n].activeFilterColor.y * 255;
int b = filters[n].activeFilterColor.z * 255;
filters[n].activeFilterColor32 = color32 | r | (g<<8) | (b<<16);
}
ImGui::PopID();
}
ImGui::PopItemWidth();
if (ImGui::Button("+")) {
filters[filterCount].Reset();
filterCount++;
}
if (ImGui::Button("Apply Filters")) {
ApplyFilters();
}
ImGui::SameLine();
if (ImGui::Button("Apply GTE OpCode Filter")) {
ApplyGTEFilter();
}
if (!noDelete) {
// Compaction of filters.
int w = 0;
for (int src=0; src < filterCount; src++) {
filters[w] = filters[src];
if (!filters[src].deleteMe) {
w++;
}
}
filterCount--;
}
}
void DrawTimeLine(ImDrawList* draw_list, float x, float y) {
// Select time scale :
// S
// mS
// uS
// Cycle
// Default to mS
float deltaT = ((timeScale.getEndTime()-timeScale.getStartTime())*1000.0) / timeScale.getClock();
float deltaTPerPixel = deltaT / timeScale.getWidth();
double divider = 1000.0 / timeScale.getClock();
const char* unit = "uS";
if (deltaT > 1000) {
unit = "S";
divider = timeScale.getClock();
} else if (deltaT > 1) {
unit = "mS";
divider = timeScale.getClock() / 1000.0;
} else if (deltaT > 0.001) {
unit = "Cycle";
divider = 1.0;
}
draw_list->AddText(ImVec2(x+5,y + 15.0f),0xFFFFFFFF,unit);
int markCount = ((int)truncf(timeScale.getEndTime()-timeScale.getStartTime()) / divider) + 2;
double startMark = truncf(timeScale.getStartTime() / divider) * divider;
int step;
if (markCount < 50) {
step = 1;
} else if (markCount < 200) {
step = 2;
} else if (markCount < 400) {
step = 4;
} else if (markCount < 500) {
step = 10;
} else if (markCount < 1000) {
step = 20;
} else {
step = markCount / 50;
}
int cnt = 0;
for (int n=0; n <= markCount; n += step) {
float pixel = timeScale.TimeToPixel(startMark) + DEVICE_TITLE_W + x;
draw_list->AddLine(ImVec2(pixel,y),ImVec2(pixel,y+50),0xFFFF00FF);
// if (n & 1) {
char txt[500];
sprintf(txt,"%i",(int)(truncf(startMark / divider)));
draw_list->AddText(ImVec2(pixel,y + ((cnt & 1)*25.0f)),0xFFFFFFFF,txt);
// }
startMark += divider * step;
cnt++;
}
}
void DrawDevices(ImDrawList* draw_list, u64 startTime, u64 endTime, float baseX, float baseY) {
u32 deviceCount;
// Cycle to pixel
float pixelWidth = timeScale.TimeToPixel(1.0);
if (pixelWidth < 1.0f) { pixelWidth = 1.0f; }
float start = -1.0f;
Device** devices = getDevices(deviceCount);
// -------------------------------------------------
// Display Device Name
// -------------------------------------------------
// u32 n = 0; // deviceCount = 6;
float devPosY = baseY + 5.0f;
float totalHeight = 0.0f;
for (u32 n=0; n < deviceCount; n++) {
Device* dev = devices[n];
totalHeight += dev->height;
}
draw_list->AddRectFilled(ImVec2(baseX,baseY),ImVec2(baseX + DEVICE_TITLE_W,baseY + totalHeight),0xFF404040);
for (u32 n=0; n < deviceCount; n++) {
Device* dev = devices[n];
float heightDevice = dev->height;
if (dev->visible) {
draw_list->AddText(ImVec2(baseX,devPosY),0xFFFFFFFF,dev->name);
devPosY += heightDevice;
}
}
// -------------------------------------------------
// Display Device Events.
// -------------------------------------------------
for (u32 n=0; n < deviceCount; n++) {
Device* dev = devices[n];
if (!dev->visible) { continue; }
float heightDevice = dev->height;
float bottomY = heightDevice + baseY;
float graphX = baseX + DEVICE_TITLE_W;
PSXEventHolder* pHolder;
PSXEvent* pEvent;
float lastPixel = 0.0f;
float firstPixel= 0.0f;
u32 lastColor = 0;
u32 colorTable[8192];
memset(colorTable,0,8192*sizeof(u32));
bool lockPixel = false;
if (dev->FindEvent(startTime,&pHolder,&pEvent)) {
EventType lastType = UNDEF_EVENT;
while (pEvent) {
u64 time = pEvent->time;
bool before = false;
if (time < startTime) { before = true; time = startTime; } // Clip for display
if (time >= endTime) { break; }
// Convert time to display
float pixel = timeScale.TimeToPixel(time);
bool changeRect = pixel > (lastPixel+1.0f);
int pixelI = pixel < 0.0f ? 0 : pixel;
// Event override color.
if (pEvent->filterID) {
if (pEvent->filterID & 0xFF000000) {
// color given by direct event.
colorTable[pixelI] = pEvent->filterID;
} else {
colorTable[pixelI] = displayfilters[pEvent->filterID-1].activeFilterColor32;
}
lockPixel = true;
} else {
if (!lockPixel) {
// Event Base Color.
u32 eventColor = 0xFF000000 | ((pEvent->type & 1) ? 0x0000FF : 0x00FF00) | ((pEvent->type & 2) ? 0xFF0000 : 0x0);
colorTable[pixelI] |= eventColor;
}
}
if (lastPixel != pixelI) {
lockPixel = false;
}
lastPixel = pixelI;
pEvent = pHolder->GetNextEvent(pEvent,&pHolder);
}
// printf("---------------\n");
u32 prevColor = 0;
int startRect = 0;
int endRect = 0;
float pixel = timeScale.TimeToPixel(endTime);
lastPixel = pixel + 1;
for (int n=0; n <= lastPixel; n++) {
u32 cCol = colorTable[n];
if (cCol==prevColor) {
endRect = n+1;
} else {
// Is rect colored ?
if (prevColor) {
draw_list->AddRectFilled(ImVec2(graphX+startRect, baseY),ImVec2(graphX+endRect,bottomY), prevColor);
}
startRect = n;
endRect = n+1;
}
prevColor = cCol;
}
}
baseY += heightDevice;
}
}
void SelectionWindow(bool computeSelection, double startSelectionTime, double endSelectionTime, PSXEvent** pEventSelected) {
static u32 selectionCount = 0;
if (computeSelection) {
selectionCount = 0;
eventListCount = 0;
if (startSelectionTime < 0.0) { startSelectionTime = 0.0; }
if (endSelectionTime < startSelectionTime) { endSelectionTime = startSelectionTime; }
u64 iStartTime = startSelectionTime;
u64 iEndTime = endSelectionTime;
u32 deviceCount;
Device** pDevices = getDevices(deviceCount);
for (int n=0; n < deviceCount; n++) {
PSXEvent* pEvent;
PSXEventHolder* pHolder;
if (pDevices[n]->visible) {
pDevices[n]->FindEvent(0,&pHolder,&pEvent);
while (pEvent) {
if (pEvent->time >= startSelectionTime) {
if (pEvent->time > endSelectionTime) {
break;
}
if (eventListCount < 50000) {
eventList[eventListCount++] = pEvent;
} else {
// Full -> Early stop
}
selectionCount++;
}
pEvent = pHolder->GetNextEvent(pEvent,&pHolder);
}
}
}
}
ImGui::Begin("Event Detail Window"); // Create a window called "Hello, world!" and append into it.
// 50 event per page.
int pageCount = (eventListCount+49) / 50;
static int currPage = 0;
ImGui::SliderInt("Page:",&currPage,0,pageCount-1);
int pageStart = currPage*50;
int pageEnd = pageStart + 50;
if (pageEnd > eventListCount) { pageEnd = eventListCount; }
static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
if (ImGui::BeginTable("table",5, flags)) {
ImGui::TableSetupColumn("R/W");
ImGui::TableSetupColumn("CYCLE");
ImGui::TableSetupColumn("ADDR");
ImGui::TableSetupColumn("VALUE");
ImGui::TableSetupColumn("BASIC DESCRIPTION");
ImGui::TableHeadersRow();
// Read/Write
if (currPage >= 0) {
for (int n=pageStart; n < pageEnd; n++) {
PSXEvent* pEvent = eventList[n];
const char* wr;
ImGui::TableNextRow();
if (pEvent->type & WRITE_ADR) {
wr = "W";
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, 0xFF000080);
} else {
wr = "R";
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, 0xFF008000);
}
ImGui::PushID(n);
// --------- Write / Size -----
ImGui::TableSetColumnIndex(0);
const char* size="";
ImGui::LabelText("",wr);
/*
MemoryMapEntry* pEntry = GetBaseEntry(pEvent->adr);
if (pEntry) {
} else {
ImGui::LabelText("LblAdr","UNKNOWN %p",pEvent->adr);
}
ImGui::LabelText("Label",s);
*/
// --------- Cycle -----
ImGui::TableSetColumnIndex(1);
ImGui::LabelText("","@%ull",pEvent->time);
// if (ImGui::IsItemHovered())
// --------- ADDR -----
ImGui::TableSetColumnIndex(2);
if (ImGui::Button("SEL")) {
selectedIO = NULL; // Unselect last displayed IO.
*pEventSelected = pEvent;
}
ImGui::SameLine();
ImGui::LabelText("","A=%08x",pEvent->adr);
// if (ImGui::IsItemHovered())
// --------- Value -----
ImGui::TableSetColumnIndex(3);
ImGui::LabelText("","D=%08x",pEvent->value);
// --------- Desc -----
ImGui::TableSetColumnIndex(4);
MemoryMapEntry* pEntry = GetBaseEntry(pEvent->adr);
if (pEntry) {
ImGui::LabelText("",pEntry->desc);
} else {
ImGui::LabelText("","UNKNOWN %p",pEvent->adr);
}
ImGui::PopID();
}
}
ImGui::EndTable();
}
ImGui::LabelText("", "Total Count : %i, Record Count : %i", selectionCount, eventListCount);
ImGui::End();
}
ImTextureID RenderCommandSoftware(u8* srcBuffer, u64 maxTime) {
GPUCommandGen* commandGenerator = getCommandGen();
// Copy VRAM to local
u8* swBuffer = new u8[1024*1024];
memcpy(swBuffer, srcBuffer, 1024*1024);
u32 commandCount;
u32* p = commandGenerator->getRawCommands(commandCount);
u64* pStamp = commandGenerator->getRawTiming(commandCount);
u8* pGP1 = commandGenerator->getGP1Args();
// PSX Context.
GPURdrCtx psxGPU;
psxGPU.swBuffer = (u16*)swBuffer;
if (commandCount != 0) {
// Run the rendering of the commands...
psxGPU.commandDecoder(p,pStamp,pGP1,commandCount,NULL,NULL, maxTime);
}
// Convert 16 bit to 32 bit
u8* buff32 = new u8[4*512*1024];
for (int y=0; y < 512; y++) {
for (int x=0; x < 1024; x++) {
int adr = (x*2 + y*2048);
int lsb = swBuffer[adr];
int msb = swBuffer[adr+1];
int c16 = lsb | (msb<<8);
int r = ( c16 & 0x1F);
int g = ((c16>>5) & 0x1F);
int b = ((c16>>10) & 0x1F);
r = (r >> 2) | (r << 3);
g = (g >> 2) | (g << 3);
b = (b >> 2) | (b << 3);
int base = (x + y*1024)*4;
buff32[base ] = r;
buff32[base+1] = g;
buff32[base+2] = b;
buff32[base+3] = 255;
}
}
// Upload to texture.
static ImTextureID currTexId = NULL;
static void* texHandler = NULL;
if (currTexId) {
ReleaseImage(texHandler);
}
texHandler = LoadImageRGBA(buff32,1024,512,&currTexId);
//
delete[] buff32;
delete[] swBuffer;
return currTexId;
}
void VRAMWindow(u64 endTime) {
ImGui::Begin("VRAM Window");
static ImTextureID tex = 0;
if (ImGui::Button("SIM GPU RENDER")) {
tex = RenderCommandSoftware((u8*)bufferVRAM,endTime);
}
ImGui::Image((void*)(intptr_t)tex, ImVec2(1024, 512));
ImGui::End();
}
//
// Loader Stuff
//
typedef struct
{
char name[16];
uint32_t size;
} t_log_fs_entry;
typedef struct
{
uint32_t pc;
uint32_t status;
uint32_t cause;
uint32_t lo;
uint32_t hi;
uint32_t epc;
uint32_t reg[31];
} t_log_mips_ctx;
void displayThings() {
static u64 startTime = 0;
static u64 endTime = 1;
static u64 fullLength= 1;
u32 deviceCount;
Device** pDevices = getDevices(deviceCount);
ImGui::Begin("Timeline"); // Create a window called "Hello, world!" and append into it.
bool openDump = false;
bool openLog = false;
static imgui_addons::ImGuiFileBrowser browser;
if (ImGui::Button("LOAD DUMP")) { openDump = true; }
ImGui::SameLine();
if (ImGui::Button("LOAD LOG")) { openLog = true; }
if (openDump) { ImGui::OpenPopup("LOAD_DUMP"); }
if (openLog ) { ImGui::OpenPopup("LOAD_LOG"); }
if (browser.showFileDialog("LOAD_DUMP",imgui_addons::ImGuiFileBrowser::DialogMode::OPEN,ImVec2(500,300),".dump")) {
const char* fileFullPath = browser.selected_path.c_str();
FILE* f = fopen(fileFullPath,"rb");
fseek(f,0,SEEK_END);
int size = ftell(f);
u8* data = new u8[size];
fseek(f,SEEK_SET,0);
fread(data,1,size,f);
// Load Each chunk.
u8* parse = data;
while (parse < &data[size]) {
t_log_fs_entry* pEntry = (t_log_fs_entry*)parse;
if (!strcmp(pEntry->name,"mips_ctx.bin")) {
t_log_mips_ctx* pMips = (t_log_mips_ctx*)(parse + sizeof(t_log_fs_entry));
cpu.PC = pMips->pc;
cpu.EPC = pMips->epc;
cpu.viewMemory = cpu.PC;
cpu.reg[0] = 0;
for (int n=1; n <= 31; n++) { // Only 0..30 (1..31
cpu.reg[n] = pMips->reg[n-1];
}
cpu.lo = pMips->lo;
cpu.hi = pMips->hi;
cpu.cause = pMips->cause;
cpu.status = pMips->status;
}
if (!strcmp(pEntry->name,"io.bin")) {
u8* src = &parse[sizeof(t_log_fs_entry)];
for (int n=0; n < pEntry->size; n++) {
SetIOsValueByte(n + 0x1F801000,src[n]);
}
}
if (!strcmp(pEntry->name,"scratch.bin")) {
memcpy(scratchPad,&parse[sizeof(t_log_fs_entry)],2048);
}
if (!strcmp(pEntry->name,"vram.bin")) {
memcpy(bufferVRAM,&parse[sizeof(t_log_fs_entry)],1024*1024);
}
if (!strcmp(pEntry->name,"main.bin")) {
memcpy(bufferRAM,&parse[sizeof(t_log_fs_entry)],1024*1024*2);
// all Cached
memset(bufferRAML,1,1024*1024*2);
}
if (strcmp(pEntry->name,"bios.bin")) {
}
parse += pEntry->size + 16 + 4;
}
delete[] data;
fclose(f);
}
if (browser.showFileDialog("LOAD_LOG",imgui_addons::ImGuiFileBrowser::DialogMode::OPEN,ImVec2(500,300),".txt")) {
ClearAllDevices();
const char* fileFullPath = browser.selected_path.c_str();
parserSIMLOG(fileFullPath,&fullLength);
endTime = fullLength;
}
for (int n=0; n < deviceCount; n++) {
if (n != 0) { ImGui::SameLine(); }
ImGui::Checkbox(pDevices[n]->name,&pDevices[n]->visible);
}
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImGuiIO io = ImGui::GetIO();
// io.MouseWheel -6..+6 , normal is -1..+1
//
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
else
ImGui::Text("Mouse Position: <invalid>");
bool leftDown = io.MouseDown[0];
bool rightDown= io.MouseDown[1];
ImVec2 RenderSize = ImGui::GetWindowSize();
// Time Display
const float TIMESCALE_H = 50.0f;
float totalHeight = TIMESCALE_H;
for (int n=0; n < deviceCount; n++) {
if (pDevices[n]->visible) {
totalHeight += pDevices[n]->height;
}
}
//
ImVec2 p = ImGui::GetCursorScreenPos();
float mouseWheel = io.MouseWheel;
float posZoom = (io.MousePos.x - (p.x + DEVICE_TITLE_W));
float zoom = 1.0f;
if (mouseWheel > 0.0f) {
zoom = 1.05f;
}
if (mouseWheel < 0.0f) {
zoom = 0.95f;
}
static bool dragActive = false;
static float dragStart;
static float dragST, dragET;
bool validPosZoom = (posZoom>=0) && (posZoom <= RenderSize.x);
if (zoom != 1.0f && validPosZoom) {
float zoomTime = timeScale.PixelToTime(posZoom);
float distTimeL= zoomTime - startTime;
float distTimeR= endTime - zoomTime;
float distTimeZL= distTimeL * (zoom - 1.0f);
float distTimeZR= distTimeR * (zoom - 1.0f);
float zoomTimeS= zoomTime * zoom;
float dL = zoom * 1000.0f;
if ((distTimeZL > 0.0f) || ((distTimeZL < 0.0f) && (startTime >= distTimeZL))) {
distTimeZL += startTime;
if (distTimeZL < 0.0f) {
distTimeZL = 0.0f;
}
startTime = (u64)distTimeZL;
}
if (((distTimeZR > 0.0f) && (endTime >= distTimeZR)) || ((distTimeZR < 0.0f))) {
distTimeZR = (float)endTime - distTimeZR;
if (distTimeZR > fullLength) {
distTimeZR = fullLength;
}
endTime = (u64)distTimeZR;
}
}
timeScale.setDisplaySize(RenderSize.x);
timeScale.setClock(30000000);
timeScale.setTime(startTime,endTime);
// draw_list->PushClipRect(ImVec2(p.x,p.y),ImVec2(p.x+RenderSize.x,p.y+totalHeight));
DrawTimeLine(draw_list,p.x,p.y);
DrawDevices(draw_list,startTime,endTime, p.x,p.y + TIMESCALE_H);
// draw_list->PopClipRect();
static bool selectActive = false;
static double startSelectionTime = 0.0f;
static double startPosSelect = 0.0f;
static float endSelectionTime = 0.0f;
static float endPosSelect = 0.0f;
bool computeSelection = false;
// End Drag
if (!leftDown) {
dragActive = false;
}
if (!rightDown && selectActive) {
selectActive = false;
// Update / Recompute Display selection...
computeSelection = true;
}
// --------------------------------
// Display Selection on timeline
// --------------------------------
float displayXS = timeScale.TimeToPixel(startSelectionTime);
float displayXE = timeScale.TimeToPixel(endSelectionTime);
if (displayXS == displayXE) {
displayXE += 1.0f;
}
draw_list->AddRectFilled(
ImVec2((p.x + DEVICE_TITLE_W) + displayXS,p.y),
ImVec2((p.x + DEVICE_TITLE_W) + displayXE,p.y+totalHeight),
0x80808080
);
ImGui::InvisibleButton("##game", ImVec2(4096, totalHeight));
if (rightDown && selectActive) {
endSelectionTime = timeScale.PixelToTime(posZoom);
endPosSelect = posZoom;
}
if (ImGui::IsItemActive() && validPosZoom) {
// Drag
if (leftDown && dragActive) {
float dragPixel = posZoom - dragStart;
float timeDrag = timeScale.PixelToTimeDistance(dragPixel);
if (timeDrag > dragST) {
timeDrag = dragST;
}
if (dragET - timeDrag > fullLength) {
timeDrag = fullLength - dragET;
}
float newStartTime = dragST - timeDrag;
if (newStartTime < 0.0f) { newStartTime = 0.0f; }
if (newStartTime > fullLength) { newStartTime = fullLength; }
float newEndTime = dragET - timeDrag;
if (newEndTime < 0.0f) { newEndTime = 0.0f; }
if (newEndTime > fullLength) {
newEndTime = fullLength;
}
startTime = newStartTime;
endTime = newEndTime;
}
}
// Start Drag
if (validPosZoom) {
if (leftDown) {
dragActive = true;
dragStart = posZoom;
dragST = startTime;
dragET = endTime;
}
if (rightDown && !selectActive) {
selectActive = true;
startPosSelect = posZoom;
startSelectionTime = timeScale.PixelToTime(posZoom);
}
}
// ImGui::Dummy();
ImGui::LabelText("Label","Start:%i End:%i",(int)startTime,(int)endTime);
UIFilterList();
ImGui::End();
UIMemoryEditorWindow();
static u32 selectAdr = -1;
static u32 selectValue = -1;
SelectionWindow(computeSelection, startSelectionTime, endSelectionTime, &selectedEvent);
UIMemoryIOWindow(selectedEvent);
VRAMWindow(startSelectionTime);
cpu.cbRead = ReadCallBack;
debuggerWindow(&cpu);
}
// Main code
int main(int, char**)
{
createDevices();
// After create device, register the register map.
CreateMap();
/*
u32 devCount;
Device** pDevices = getDevices(devCount);
for (int n = 0; n < 10000; n++) {
((DeviceSingleOp*)pDevices[0])->Write(n * n, 0,0,0xF);
((DeviceSingleOp*)pDevices[0])->Read (n * n + 50, 0,0,0xF);
}
lastTime = 10001 * 100;
*/
// parserSIMLOG("sim-82.txt", &lastTime);
// Default reset.
ApplyFilters();
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX10_Init(g_pd3dDevice);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL);
// Our state
bool show_demo_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
// Poll and handle messages (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX10_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
displayThings();
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
#if 0
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
#endif
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
// Rendering
ImGui::Render();
g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync
//g_pSwapChain->Present(0, 0); // Present without vsync
}
ImGui_ImplDX10_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
if (D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK)
return false;
CreateRenderTarget();
return true;
}
void CleanupDeviceD3D()
{
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}
void CreateRenderTarget()
{
ID3D10Texture2D* pBackBuffer;
g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
pBackBuffer->Release();
}
void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
| 32.248491 | 198 | 0.568757 | [
"render",
"vector"
] |
2b16a6eff0fab4f4dcc1f635ef281309bfbeabb2 | 1,867 | cpp | C++ | loot/loot_data_container.cpp | blockspacer/entity_spell_system | 6b2c97df9a7a9f1d7c8ecb9f80006b0c471cb80d | [
"MIT"
] | null | null | null | loot/loot_data_container.cpp | blockspacer/entity_spell_system | 6b2c97df9a7a9f1d7c8ecb9f80006b0c471cb80d | [
"MIT"
] | null | null | null | loot/loot_data_container.cpp | blockspacer/entity_spell_system | 6b2c97df9a7a9f1d7c8ecb9f80006b0c471cb80d | [
"MIT"
] | 1 | 2020-01-08T12:55:20.000Z | 2020-01-08T12:55:20.000Z | #include "loot_data_container.h"
int LootDataContainter::get_num_entries() const {
return _entries.size();
}
Ref<LootDataBase> LootDataContainter::get_entry(int index) const {
ERR_FAIL_INDEX_V(index, _entries.size(), Ref<LootDataBase>(NULL));
return _entries.get(index);
}
void LootDataContainter::set_entry(const int index, const Ref<LootDataBase> ldb) {
ERR_FAIL_INDEX(index, _entries.size());
_entries.set(index, ldb);
}
void LootDataContainter::_get_loot(Array into) {
for (int i = 0; i < _entries.size(); ++i) {
if (_entries[i].is_valid()) {
_entries.get(i)->get_loot(into);
}
}
}
Vector<Variant> LootDataContainter::get_entries() {
Vector<Variant> r;
for (int i = 0; i < _entries.size(); i++) {
r.push_back(_entries[i].get_ref_ptr());
}
return r;
}
void LootDataContainter::set_entries(const Vector<Variant> &entries) {
_entries.clear();
for (int i = 0; i < entries.size(); i++) {
Ref<LootDataBase> entry = Ref<LootDataBase>(entries[i]);
_entries.push_back(entry);
}
}
LootDataContainter::LootDataContainter() {
}
LootDataContainter::~LootDataContainter() {
_entries.clear();
}
void LootDataContainter::_bind_methods() {
ClassDB::bind_method(D_METHOD("_get_loot", "into"), &LootDataContainter::_get_loot);
ClassDB::bind_method(D_METHOD("get_num_entries"), &LootDataContainter::get_num_entries);
ClassDB::bind_method(D_METHOD("get_entry", "index"), &LootDataContainter::get_entry);
ClassDB::bind_method(D_METHOD("set_entry", "index", "ldb"), &LootDataContainter::set_entry);
ClassDB::bind_method(D_METHOD("get_entries"), &LootDataContainter::get_entries);
ClassDB::bind_method(D_METHOD("set_entries", "auras"), &LootDataContainter::set_entries);
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "entries", PROPERTY_HINT_NONE, "17/17:LootDataBase", PROPERTY_USAGE_DEFAULT, "LootDataBase"), "set_entries", "get_entries");
}
| 31.116667 | 167 | 0.737011 | [
"vector"
] |
2b19f720ddfacf1c096fd0c5b9c71bbb3df24ac7 | 1,987 | cpp | C++ | kgl_genomics/kgl_parser/kgl_variant_factory_readvcf_impl.cpp | kellerberrin/OSM_Gene_Cpp | 4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4 | [
"MIT"
] | 1 | 2021-04-09T16:24:06.000Z | 2021-04-09T16:24:06.000Z | kgl_genomics/kgl_parser/kgl_variant_factory_readvcf_impl.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | kgl_genomics/kgl_parser/kgl_variant_factory_readvcf_impl.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | //
// Created by kellerberrin on 16/4/20.
//
#include "kgl_variant_factory_readvcf_impl.h"
namespace kgl = kellerberrin::genome;
void kgl::VCFReaderMT::readHeader(const std::string& file_name) {
if (not parseheader_.parseHeader(file_name)) {
ExecEnv::log().error("RecordVCFIO::VCFReadHeader, Problem parsing VCF header file: {}", file_name);
}
processVCFHeader(parseheader_.getHeaderInfo());
}
void kgl::VCFReaderMT::readVCFFile(const std::string& vcf_file_name) {
ExecEnv::log().info("Parse Header VCF file: {}", vcf_file_name);
readHeader(vcf_file_name);
ExecEnv::log().info("Begin processing VCF file: {}", vcf_file_name);
ExecEnv::log().info("Spawning: {} Consumer threads to process the VCF file", parser_threads_.threadCount());
// Queue the worker thread tasks.
std::vector<std::future<void>> thread_futures;
for (size_t index = 0; index < parser_threads_.threadCount(); ++index) {
thread_futures.push_back(parser_threads_.enqueueTask(&VCFReaderMT::VCFConsumer, this));
}
// start reading records asynchronously.
vcf_io_.commenceVCFIO(vcf_file_name);
// Wait until processing is complete.
for (auto const& future : thread_futures) {
future.wait();
}
}
void kgl::VCFReaderMT::VCFConsumer() {
// Loop until EOF.
size_t final_count = 0;
while (true) {
// Dequeue the vcf record.
QueuedVCFRecord vcf_record = vcf_io_.readVCFRecord();
// Terminate on EOF
if (not vcf_record) {
vcf_io_.enqueueEOF();
break; // Eof encountered, terminate processing.
}
if (vcf_record.value().second->contig_id.empty()) {
ExecEnv::log().error("Empty VCF_record encountered; consumer thread terminates.");
break;
}
// Call the consumer object with the dequeued record.
ProcessVCFRecord(vcf_record.value().first, *vcf_record.value().second);
++final_count;
}
ExecEnv::log().info("Final; Consumer thread processed: {} VCF records", final_count);
}
| 21.835165 | 110 | 0.693005 | [
"object",
"vector"
] |
2b218d332c2df8b3375c9c660bdbd721cdb4df5b | 1,212 | cpp | C++ | grooking_patterns_cpp/1_sliding_window/1_9.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | 1 | 2021-09-19T16:41:58.000Z | 2021-09-19T16:41:58.000Z | grooking_patterns_cpp/1_sliding_window/1_9.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | grooking_patterns_cpp/1_sliding_window/1_9.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<int> perm_pattern_str_ind(string str, string pattern){
int win_start = 0, cnt1 = 0, cnt2 = 0;
vector<int> indices;
unordered_map<char, int> umap;
for(int i = 0; i < pattern.length(); ++i) umap[pattern[i]]++;
cnt1 = umap.size();
for(int i = 0; i < str.length(); ++i){
if(umap.find(str[i]) != umap.end())
if(--umap[str[i]] == 0) cnt2++;
if(cnt1 == cnt2) indices.push_back(win_start);
if(i >= pattern.length()-1)
if(umap.find(str[win_start++]) != umap.end())
if(umap[str[win_start-1]]++ == 0) cnt2--;
}
return indices;
}
int main(){
ios_base::sync_with_stdio(0);
cout.tie(0), cin.tie(0);
string str, pattern;
cin >> str >> pattern;
assert(str.length() >= pattern.length());
auto start = std::chrono::high_resolution_clock::now();
for(int i : perm_pattern_str_ind(str, pattern)) cout << i << " ";
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
cout << "\nTime took: " << duration.count()/1000.0 << " ms \n";
return 0;
}
| 29.560976 | 88 | 0.577558 | [
"vector"
] |
2b28df8dd4693b38579f89dd32168c4a4031aa92 | 1,833 | cpp | C++ | aws-cpp-sdk-iotevents/source/model/Input.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-iotevents/source/model/Input.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-iotevents/source/model/Input.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/iotevents/model/Input.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoTEvents
{
namespace Model
{
Input::Input() :
m_inputConfigurationHasBeenSet(false),
m_inputDefinitionHasBeenSet(false)
{
}
Input::Input(JsonView jsonValue) :
m_inputConfigurationHasBeenSet(false),
m_inputDefinitionHasBeenSet(false)
{
*this = jsonValue;
}
Input& Input::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("inputConfiguration"))
{
m_inputConfiguration = jsonValue.GetObject("inputConfiguration");
m_inputConfigurationHasBeenSet = true;
}
if(jsonValue.ValueExists("inputDefinition"))
{
m_inputDefinition = jsonValue.GetObject("inputDefinition");
m_inputDefinitionHasBeenSet = true;
}
return *this;
}
JsonValue Input::Jsonize() const
{
JsonValue payload;
if(m_inputConfigurationHasBeenSet)
{
payload.WithObject("inputConfiguration", m_inputConfiguration.Jsonize());
}
if(m_inputDefinitionHasBeenSet)
{
payload.WithObject("inputDefinition", m_inputDefinition.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace IoTEvents
} // namespace Aws
| 21.564706 | 78 | 0.740862 | [
"model"
] |
1a745446eb5f1a1bd94c92354e3f3fd1ba78a851 | 3,060 | cpp | C++ | exporttexturestablemodel.cpp | strattonbrazil/paintbug | a000554d85c156d90430987863a0ae623fa54e4b | [
"Apache-2.0"
] | 3 | 2020-03-05T18:07:05.000Z | 2020-08-26T08:32:17.000Z | exporttexturestablemodel.cpp | strattonbrazil/paintbug | a000554d85c156d90430987863a0ae623fa54e4b | [
"Apache-2.0"
] | null | null | null | exporttexturestablemodel.cpp | strattonbrazil/paintbug | a000554d85c156d90430987863a0ae623fa54e4b | [
"Apache-2.0"
] | 1 | 2021-10-02T21:21:22.000Z | 2021-10-02T21:21:22.000Z | #include "exporttexturestablemodel.h"
#include "project.h"
ExportTexturesTableModel::ExportTexturesTableModel(QObject *parent)
: QAbstractTableModel(parent)
{
QVectorIterator<Mesh*> meshes = Project::activeProject()->meshes();
while (meshes.hasNext()) {
Mesh* mesh = meshes.next();
_writeList.append(false);
_meshList.append(mesh);
}
}
QVariant ExportTexturesTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
QVariant headers[] = {
QVariant("Bake?"),
QVariant("Mesh Name"),
QVariant("Path")
};
return headers[section];
}
return QVariant("");
}
int ExportTexturesTableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return _writeList.count();
}
int ExportTexturesTableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return 3;
}
QVariant ExportTexturesTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::CheckStateRole && index.column() == 0) {
if (_writeList[index.row()])
return Qt::Checked;
else
return Qt::Unchecked;
}
if (role == Qt::DisplayRole || role == Qt::EditRole) {
if (index.column() == 1) {
return _meshList[index.row()]->meshName();
} else if (index.column() == 2) {
return _meshList[index.row()]->texturePath();
}
}
return QVariant();
}
bool ExportTexturesTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
if (role == Qt::CheckStateRole && index.column() == 0) {
_writeList[index.row()] = value.toBool();
emit dataChanged(index, index);
return true;
} else if (index.column() == 2) {
_meshList[index.row()]->setTexturePath(value.toString());
emit dataChanged(index, index);
return true;
}
return false;
}
Qt::ItemFlags ExportTexturesTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
return QAbstractTableModel::flags(index) | Qt::ItemIsEnabled;
}
if (index.column() == 0) {
return QAbstractTableModel::flags(index) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
} else if (index.column() == 1) {
return QAbstractTableModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsEnabled;
} else if (index.column() == 2) {
return QAbstractTableModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsEnabled;;
}
return QAbstractTableModel::flags(index) | Qt::ItemIsEnabled;
}
bool ExportTexturesTableModel::exportTexture(const int meshIndex)
{
return _writeList[meshIndex];
}
Mesh* ExportTexturesTableModel::mesh(const int meshIndex)
{
return _meshList[meshIndex];
}
| 26.153846 | 103 | 0.629412 | [
"mesh"
] |
1a78b882d8cdb75a6b8de7a971061ce93d68c238 | 2,401 | cpp | C++ | coffeeDBR/src/cml_ncgm/cml_ncgm.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | coffeeDBR/src/cml_ncgm/cml_ncgm.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | coffeeDBR/src/cml_ncgm/cml_ncgm.cpp | CoFFeeMaN11/CoffeeDBR | 1c4fb0683263ada1a8a931cc78bb7cbe728e9d4b | [
"Apache-2.0"
] | null | null | null | #include "cml_ncgm.h"
#include <cstdio>
int oneDFunction(long double alpha, void* params, long double& result)
{
ConjugeteGradientSolve *cgs = (ConjugeteGradientSolve*)params;
cml::Vector<long double, 2> t = (cgs->GetStep() * alpha);
cgs->func(cgs->GetX() + t, cgs->params, result);
return 0;
}
ConjugeteGradientSolve::ConjugeteGradientSolve(size_t xSize) : params(0), xvector(), func(0),
gradientStep(1e-11), lastDir(), currDir(),step(), n(2), betaF(0), minFinder(0)
{
}
const long double ConjugeteGradientSolve::GetMinValue() const
{
long double result;
func(xvector, params, result);
return result;
}
ConjugeteGradientSolve::~ConjugeteGradientSolve()
{
if (betaF)
{
delete betaF;
betaF = 0;
}
if (minFinder)
{
delete minFinder;
minFinder = 0;
}
}
void ConjugeteGradientSolve::StartSolve(cml::Vector<long double, 2> _startPoint)
{
if(!betaF)
betaF = new Fletcher();
if(!minFinder)
minFinder = new GoldenSec();
cml::Vector<long double, 2> direction = this->Gradient(_startPoint)* -1.L;
lastDir = direction;
step = direction;
minFinder->SetFuction(oneDFunction);
minFinder->SetParams(this);
minFinder->InitMethod(0L);
int n = 0;
do
{
minFinder->Iterate();
} while (minFinder->NotEnough() && ++n <1000);
assert(n < 1000);
long double mini = minFinder->GetMin();
this->xvector = _startPoint + direction * mini;
}
void ConjugeteGradientSolve::Iteration()
{
cml::Vector<long double, 2> currDir = this->Gradient(this->xvector)* -1.L;
betaInput[0] = currDir;
betaInput[1] = lastDir;
betaInput[2] = step;
this->betaF->UpdateData(betaInput, 3);
long double beta = betaF->Calc();
step = currDir + (step * beta);
int n = 0;
minFinder->InitMethod(0L);
do
{
minFinder->Iterate();
} while (minFinder->NotEnough() && ++n < 1000 );
assert(n < 1000);
xvector = xvector + step * minFinder->GetMin();
}
cml::Vector<long double, 2> ConjugeteGradientSolve::Gradient(cml::Vector<long double, 2> point)
{
cml::Vector<long double, 2> result;
for (int i = 0; i < 2; i++)
result[i] = Partial(cml::Vector<long double, 2>::Unit(i), point);
return result;
}
long double ConjugeteGradientSolve::Partial(cml::Vector<long double, 2> dir, cml::Vector<long double, 2> point)
{
assert(func);
long double f1, f2;
assert(!func(point + (dir * gradientStep), params, f1));
assert(!func(point,params, f2));
return (f1 - f2)/(gradientStep);
}
| 24.252525 | 111 | 0.68055 | [
"vector"
] |
1a839591381234c85f0db44aba91ba8a76ce210f | 3,911 | hpp | C++ | lib/include/General.hpp | Werni2A/OAP | 5fb7ec4cd3161f5686df8707eae73c51d27fd134 | [
"MIT"
] | 10 | 2021-10-01T06:48:13.000Z | 2022-03-21T10:11:25.000Z | lib/include/General.hpp | Werni2A/OAP | 5fb7ec4cd3161f5686df8707eae73c51d27fd134 | [
"MIT"
] | 5 | 2021-09-26T19:55:37.000Z | 2022-03-19T20:31:03.000Z | lib/include/General.hpp | Werni2A/OAP | 5fb7ec4cd3161f5686df8707eae73c51d27fd134 | [
"MIT"
] | 1 | 2022-01-05T19:23:34.000Z | 2022-01-05T19:23:34.000Z | #ifndef GENERAL_H
#define GENERAL_H
#include <algorithm>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
#include <magic_enum.hpp>
#include "Exception.hpp"
/**
* @brief Version of the file format.
*/
enum class FileFormatVersion
{
Unknown,
V17_4_S012 // 10/18/2020 - pad3898010/18
};
enum class FileType
{
brd, // Board database
mdd, // Module definition
dra, // Drawing
psm, // Package symbol
ssm, // Shape symbol
fsm, // Flash symbol
osm, // Format symbol
bsm, // Mechanical symbol
pad // Padstack
};
template<typename T>
[[maybe_unused]] static std::string ToHex(T val, size_t digits)
{
// @todo Use fmt lib!
char hex[16];
std::string format = "%0" + std::to_string(digits) + "x";
std::sprintf(hex, format.c_str(), static_cast<unsigned int>(val));
return std::string(hex);
}
[[maybe_unused]]
static void expectStr(const std::string& str, const std::string& ref)
{
if(str != ref)
{
throw std::runtime_error("Exptected string '" + ref + "' but got '" + str + "'!");
}
}
[[maybe_unused]]
static std::string DateTimeToStr(const time_t& unixts)
{
return std::string(std::ctime(&unixts));
}
[[maybe_unused]]
static std::time_t ToTime(uint32_t aTime)
{
std::time_t time = static_cast<time_t>(aTime);
// Cadence Systems was founded in 1988, therefore all files
// can not date back to earlier years.
std::tm tm{}; // Zero initialise
tm.tm_year = 1988 - 1900; // 1960
std::time_t earliestTime = std::mktime(&tm);
std::time_t latestTime = std::time(nullptr);
if(time < earliestTime || time > latestTime)
{
throw std::runtime_error("Time musst be in between "
+ DateTimeToStr(earliestTime) + " <= " + DateTimeToStr(time) + " <= " + DateTimeToStr(latestTime) + "!");
}
return time;
}
/**
* @brief Convert fix point coordinate to floating point.
* @note Allegro stores floating point values as fixed point value
* instead of the actual floating point representation.
*
* @param point Fix point coordiante.
* @return double Floating point coordinate.
*/
template<typename T>
static double ToFP(T point)
{
return static_cast<double>(point) / 100.0;
}
[[maybe_unused]]
static std::string newLine()
{
return "\n";
}
[[maybe_unused]]
static std::string indent(std::string str, size_t level)
{
const std::string indent = " ";
const std::string delimiter = newLine();
std::vector<std::string> lines;
size_t pos = 0;
std::string token;
while ((pos = str.find(delimiter)) != std::string::npos)
{
token = str.substr(0, pos);
lines.push_back(std::move(token) + newLine());
str.erase(0, pos + delimiter.length());
}
lines.push_back(std::move(str));
std::string indentedStr;
for(auto&& line : lines)
{
if(!line.empty())
{
for(size_t i = 0u; i < level; ++i)
{
indentedStr += indent;
}
indentedStr += line;
}
}
return indentedStr;
}
[[maybe_unused]]
static std::string indent(size_t level)
{
const std::string indent = " ";
std::string retIndent;
for(size_t i = 0u; i < level; ++i)
{
retIndent += indent;
}
return retIndent;
}
[[maybe_unused]]
static std::string to_lower(const std::string& aStr)
{
std::string retVal{aStr};
std::transform(retVal.begin(), retVal.end(), retVal.begin(),
[] (unsigned char c) { return std::tolower(c); });
return retVal;
}
template<typename TEnum, typename TVal>
static constexpr TEnum ToEnum(TVal aVal)
{
const auto enumEntry = magic_enum::enum_cast<TEnum>(aVal);
if(!enumEntry.has_value())
{
throw InvalidEnumEntry<TEnum, TVal>(aVal);
}
return enumEntry.value();
}
#endif // GENERAL_H | 20.47644 | 118 | 0.617233 | [
"shape",
"vector",
"transform"
] |
1a9600a3389c6236633c71de3a5fa8dfb71e55a0 | 2,986 | cpp | C++ | lib/poplibs_support/ContiguousRegionsByTile.cpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 95 | 2020-07-06T17:11:23.000Z | 2022-03-12T14:42:28.000Z | lib/poplibs_support/ContiguousRegionsByTile.cpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | lib/poplibs_support/ContiguousRegionsByTile.cpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | 14 | 2020-07-15T12:32:57.000Z | 2022-01-26T14:58:45.000Z | // Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#include "poplibs_support/ContiguousRegionsByTile.hpp"
#include <cassert>
#if defined(ALTERNATE_IMPLEMENTATION__)
#include <boost/icl/interval_map.hpp>
#include <boost/optional.hpp>
#endif
namespace poplibs {
#if defined(ALTERNATE_IMPLEMENTATION__)
std::vector<std::vector<std::vector<poplar::Interval>>>
getSortedContiguousRegionsByTile(
const poplar::Graph &graph, const poplar::Tensor &A,
const poplar::Graph::TileToTensorMapping &mapping) {
// Get the sorted contiguous regions up-front.
const auto scrs = graph.getSortedContiguousRegions(A, {{0, A.numElements()}});
// Convert the mapping to boost ICL format.
auto mappingIcl = tileMappingToIntervalMap(mapping);
// Make sure that the mapping is complete. This should always be the case
// since getTileMapping() throws an exception if it isn't (by default).
assert(mappingIcl.size() == A.numElements());
// The result - a set of sorted contiguous regions for each tile.
std::vector<std::vector<std::vector<poplar::Interval>>> out(mapping.size());
// For each sorted contiguous region:
for (const auto &scr : scrs) {
if (scr.empty())
continue;
// The tile that the last bit of this contiguous region was mapped to.
boost::optional<unsigned> lastTile;
// For each tensor region in this contiguous variable region:
for (const auto &re : scr) {
if (re.size() == 0)
continue;
// Find the parts of this region that are mapped to different tiles.
// It is possible to iterate through `mappingIcl & re` but that is slow.
auto begin = mappingIcl.find(re.begin());
auto end = mappingIcl.find(re.end());
// For each part on a different tile:
for (auto it = begin; it != end; ++it) {
// Get the region.
auto lower = std::max(it->first.lower(), re.begin());
auto upper = std::min(it->first.upper(), re.end());
// The tile that this part is mapped to.
const auto &tile = it->second;
// If it is the first part of this contiguous region, or if the
// last part was on a different tile, start a new contiguous region
// on this tile.
if (!lastTile || tile != lastTile) {
lastTile = tile;
out[tile].emplace_back();
}
// And append it to the current contiguous region.
out[tile].back().emplace_back(lower, upper);
}
}
}
return out;
}
#else
std::vector<std::vector<std::vector<poplar::Interval>>>
getSortedContiguousRegionsByTile(
const poplar::Graph &graph, const poplar::Tensor &A,
const poplar::Graph::TileToTensorMapping &mapping) {
std::vector<std::vector<std::vector<poplar::Interval>>>
contiguousRegionsByTile;
for (const auto &m : mapping) {
contiguousRegionsByTile.emplace_back(
graph.getSortedContiguousRegions(A, m));
}
return contiguousRegionsByTile;
}
#endif
} // namespace poplibs
| 30.161616 | 80 | 0.667783 | [
"vector"
] |
1a96333b3f7406cda411a696f67318881cd6721c | 8,316 | hpp | C++ | benchmark/benchmark_common.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 26 | 2020-05-12T10:55:48.000Z | 2022-03-07T10:57:37.000Z | benchmark/benchmark_common.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 3 | 2021-08-04T18:27:03.000Z | 2022-02-08T11:22:53.000Z | benchmark/benchmark_common.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 3 | 2020-05-24T08:07:29.000Z | 2021-07-19T09:59:56.000Z | #pragma once
#include "../external/cmd_line_parser/include/parser.hpp"
#include "probe.hpp"
namespace autocomplete {
namespace benchmarking {
static const uint32_t runs = 5;
}
// void tolower(std::string& str) {
// std::transform(str.begin(), str.end(), str.begin(),
// [](unsigned char c) { return std::tolower(c); });
// }
size_t load_queries(std::vector<std::string>& queries, uint32_t max_num_queries,
float percentage, std::istream& is = std::cin) {
assert(percentage >= 0.0 and percentage <= 1.0);
std::string query;
queries.reserve(max_num_queries);
for (uint32_t i = 0; i != max_num_queries; ++i) {
if (!std::getline(is, query)) break;
assert(query.size() > 0);
size_t size = query.size() - 1;
while (size > 0 and query[size] != ' ') --size;
size_t last_token_size = query.size() - size;
size_t end = size + std::ceil(last_token_size * percentage) + 1 +
1; // retain at least one char
for (size = query.size(); size > end; --size) query.pop_back();
// tolower(query);
queries.push_back(query);
}
return queries.size();
}
void configure_parser_for_benchmarking(cmd_line_parser::parser& parser) {
parser.add("type", "Index type.");
parser.add("k", "top-k value.");
parser.add("index_filename", "Index filename.");
parser.add("num_terms_per_query", "Number of terms per query.");
parser.add("max_num_queries", "Maximum number of queries to execute.");
parser.add("percentage",
"A float in [0,1] specifying how much we keep of the last token "
"in a query: n x 100 <=> n%, for n in [0,1].");
}
#define BENCHMARK(what) \
template <typename Index> \
void benchmark(std::string const& index_filename, uint32_t k, \
uint32_t max_num_queries, float keep, \
essentials::json_lines& breakdowns) { \
Index index; \
essentials::load(index, index_filename.c_str()); \
\
std::vector<std::string> queries; \
uint32_t num_queries = \
load_queries(queries, max_num_queries, keep, std::cin); \
\
uint64_t reported_strings = 0; \
auto musec_per_query = [&](double time) { \
return time / (benchmarking::runs * num_queries); \
}; \
\
breakdowns.add("num_queries", std::to_string(num_queries)); \
\
timer_probe probe(3); \
for (uint32_t run = 0; run != benchmarking::runs; ++run) { \
for (auto const& query : queries) { \
auto it = index.what##topk(query, k, probe); \
reported_strings += it.size(); \
} \
} \
std::cout << "#ignore: " << reported_strings << std::endl; \
\
breakdowns.add("reported_strings", \
std::to_string(reported_strings / benchmarking::runs)); \
breakdowns.add( \
"parsing_musec_per_query", \
std::to_string(musec_per_query(probe.get(0).elapsed()))); \
breakdowns.add( \
std::string(#what) + "search_musec_per_query", \
std::to_string(musec_per_query(probe.get(1).elapsed()))); \
breakdowns.add( \
"reporting_musec_per_query", \
std::to_string(musec_per_query(probe.get(2).elapsed()))); \
breakdowns.add( \
"total_musec_per_query", \
std::to_string(musec_per_query(probe.get(0).elapsed()) + \
musec_per_query(probe.get(1).elapsed()) + \
musec_per_query(probe.get(2).elapsed()))); \
} \
\
int main(int argc, char** argv) { \
cmd_line_parser::parser parser(argc, argv); \
configure_parser_for_benchmarking(parser); \
if (!parser.parse()) return 1; \
\
auto type = parser.get<std::string>("type"); \
auto k = parser.get<uint32_t>("k"); \
auto index_filename = parser.get<std::string>("index_filename"); \
auto max_num_queries = parser.get<uint32_t>("max_num_queries"); \
auto keep = parser.get<float>("percentage"); \
\
essentials::json_lines breakdowns; \
breakdowns.new_line(); \
breakdowns.add("num_terms_per_query", \
parser.get<std::string>("num_terms_per_query")); \
breakdowns.add("percentage", std::to_string(keep)); \
\
if (type == "ef_type1") { \
benchmark<ef_autocomplete_type1>( \
index_filename, k, max_num_queries, keep, breakdowns); \
} else if (type == "ef_type2") { \
benchmark<ef_autocomplete_type2>( \
index_filename, k, max_num_queries, keep, breakdowns); \
} else if (type == "ef_type3") { \
benchmark<ef_autocomplete_type3>( \
index_filename, k, max_num_queries, keep, breakdowns); \
} else if (type == "ef_type4") { \
benchmark<ef_autocomplete_type4>( \
index_filename, k, max_num_queries, keep, breakdowns); \
} else { \
return 1; \
} \
\
breakdowns.print(); \
return 0; \
}
} // namespace autocomplete | 63.480916 | 80 | 0.357143 | [
"vector",
"transform"
] |
1a9b914f74b7c4a5fce04d95fad2017e6f611d40 | 2,475 | cpp | C++ | thirdparty/spline/spline/spline.cpp | jpcima/spectacle | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 44 | 2020-04-16T19:20:00.000Z | 2022-02-27T00:10:13.000Z | thirdparty/spline/spline/spline.cpp | jpcima/spectacle | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 18 | 2020-04-16T03:28:55.000Z | 2021-11-15T19:49:12.000Z | thirdparty/spline/spline/spline.cpp | jpcima/spectral | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 3 | 2020-04-16T01:22:48.000Z | 2021-08-10T20:34:30.000Z | /*==============================================================================
Copyright 2018 by Roland Rabien, Devin Lane
For more information visit www.rabiensoftware.com
==============================================================================*/
/* "THE BEER-WARE LICENSE" (Revision 42): Devin Lane wrote this file. As long as you retain
* this notice you can do whatever you want with this stuff. If we meet some day, and you
* think this stuff is worth it, you can buy me a beer in return. */
#include "spline.h"
#include <cstdio>
#include <cassert>
void Spline::setup (const float *pointsX, const float *pointsY, int numPoints)
{
assert (numPoints >= 3); // "Must have at least three points for interpolation"
int n = numPoints - 1;
std::vector<double> b, d, a, c, l, u, z, h;
elements.resize (n + 1);
a.resize (n);
b.resize (n);
c.resize (n + 1);
d.resize (n);
h.resize (n + 1);
l.resize (n + 1);
u.resize (n + 1);
z.resize (n + 1);
l[0] = 1.0;
u[0] = 0.0;
z[0] = 0.0;
h[0] = pointsX[1] - pointsX[0];
for (int i = 1; i < n; i++)
{
h[i] = pointsX[i+1] - pointsX[i];
l[i] = (2 * (pointsX[i+1] - pointsX[i-1])) - (h[i-1]) * u[i-1];
u[i] = (h[i]) / l[i];
a[i] = (3.0 / (h[i])) * (pointsY[i+1] - pointsY[i]) - (3.0 / (h[i-1])) * (pointsY[i] - pointsY[i-1]);
z[i] = (a[i] - (h[i-1]) * z[i-1]) / l[i];
}
l[n] = 1.0;
z[n] = 0.0;
c[n] = 0.0;
for (int j = n - 1; j >= 0; j--)
{
c[j] = z[j] - u[j] * c[j+1];
b[j] = (pointsY[j+1] - pointsY[j]) / (h[j]) - ((h[j]) * (c[j+1] + 2.0 * c[j])) / 3.0;
d[j] = (c[j+1] - c[j]) / (3.0 * h[j]);
}
for (int i = 0; i < n; i++)
elements[i] = Element (pointsX[i], pointsY[i], b[i], c[i], d[i]);
elements[n] = Element (pointsX[n], pointsY[n], 0.0, 0.0, 0.0);
}
double Spline::interpolate (double x) const noexcept
{
int i = findElement (x);
return elements[i].eval (x);
}
int Spline::findElement (double x) const noexcept
{
int i;
int n = static_cast<int> (elements.size () - 1);
#if 0
for (i = 0; i < n; i++)
{
if (! (elements[i].x < x))
break;
}
#else
{
auto it = std::lower_bound (&elements[0], &elements[n], x);
if (it != &elements[n])
i = int (it - &elements[0]);
else
i = n;
}
#endif
i = std::max(0, i - 1);
return i;
}
| 26.612903 | 109 | 0.459394 | [
"vector"
] |
1aad021fd013504775499d659ff64f9f57df5203 | 12,367 | cc | C++ | docker_containers/docker-click-fsm/gateway.cc | brytul/IoT_Sec_Gateway | f4fbb622c2c0556ee1c8b0d4661c1cb82b8bfb8f | [
"MIT"
] | 8 | 2018-08-08T14:42:01.000Z | 2020-09-24T15:53:32.000Z | docker_containers/docker-click-fsm/gateway.cc | brytul/IoT_Sec_Gateway | f4fbb622c2c0556ee1c8b0d4661c1cb82b8bfb8f | [
"MIT"
] | 1 | 2020-06-02T19:01:21.000Z | 2020-06-02T19:01:21.000Z | docker_containers/docker-click-fsm/gateway.cc | brytul/IoT_Sec_Gateway | f4fbb622c2c0556ee1c8b0d4661c1cb82b8bfb8f | [
"MIT"
] | 9 | 2018-01-29T00:54:33.000Z | 2020-05-31T20:32:51.000Z | #include <click/config.h>
#include <click/confparse.hh>
#include <map>
#include "gateway.hh"
/* Add header files as required */
CLICK_DECLS
using namespace std;
// Fills lps[] for given patttern pat[0..M-1]
void computeLPSArray(char *pat, int M, int *lps)
{
// length of the previous longest prefix suffix
int len = 0;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
int i = 1;
while (i < M)
{
if (pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0)
{
len = lps[len-1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}
// Prints occurrences of txt[] in pat[]
bool KMPSearch(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);
// create lps[] that will hold the longest prefix suffix
// values for pattern
int lps[M];
// Preprocess the pattern (calculate lps[] array)
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
int j = 0; // index for pat[]
while (i < N)
{
if (pat[j] == txt[i])
{
j++;
i++;
}
if (j == M)
{
j = lps[j-1];
return true;
}
// mismatch after j matches
else if (i < N && pat[j] != txt[i])
{
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j-1];
else
i = i+1;
}
}
return false;
}
Graph::Graph(){
this->number_vertices = 0;
}
Graph::Graph(int number_vertices){
this->number_vertices = number_vertices;
}
Graph::~Graph(){
}
void Graph::addTransition(int current, int next, String content){
size_t len = content.length();
edges[current][next].val = 1;
edges[current][next].rule = new char[len];
strncpy(edges[current][next].rule, content.c_str(), len);
}
int getTypeSNMP(char* rule){
char* copy_rule = new char[strlen(rule)];
const char* delim = "_1";
char* token, *st;
strncpy(copy_rule, rule, strlen(rule));
st = copy_rule;
token = strsep(©_rule, delim);
token = strsep(©_rule, delim);
token = strsep(©_rule, delim);
if(strcmp(token, "request") == 0){
delete(st);
return 0xA0;
}
else if(strcmp(token, "response") == 0){
delete(st);
return 0xA2;
}
else {
delete(st);
return -1;
}
}
/*
* Type means whether the type of snmp is request or response
*/
int compare_objectId(char* content, char* rule){
char* token;
char* copy_rule = new char[strlen(rule)];
char* st = copy_rule;
strncpy(copy_rule, rule, strlen(rule));
token = strsep(©_rule, "1");
//This means that it starts with 1.3.
if((content[20] & 0xFF) == 0x2b){
copy_rule = copy_rule + 3; //Now rule starts pointing with 6
content = content + 21;//content also starts with object id
token = strsep(©_rule, ".");
while((*content & 0xFF) != 0x00 && token != NULL){
if((*content & 0xFF) == atoi(token)){
content++;
token = strsep(©_rule, ".");
}
else{
delete(st);
return false;
}
}
delete(st);
return true;
}
delete(st);
return false;
}
//Currently only supporting ASN.1 header
bool Graph::transition_snmp(char* content){
int type_snmp_content;
int length_community_name;
//click_chatter("Content is %x", *content);
//click_chatter("Number of vertices are %d", number_vertices);
for(int i=0; i<number_vertices;i++){
char* rule = edges[current_state][i].rule;
if(rule == NULL){
continue;
}
//click_chatter("Rule is %s", rule);
length_community_name = (int)content[6];
if((content[length_community_name+7] & 0xFF) != 0xa0 && ((content[length_community_name+7] & 0xFF) != 0xa2)){
length_community_name = (int)content[8]+2;
}
//click_chatter("The length of community rule is %d", length_community_name);
if((content[length_community_name + 7] & 0xFF) == getTypeSNMP(rule)){
if(compare_objectId(&content[length_community_name+7], rule)){
current_state = i;
return true;
}
}
}
return false;
}
//Type of get is same
/*If it doesn't contain a rule for that, then it will return false*/
bool Graph::transition(char* content){
if(proto == SNMP){
//click_chatter("Checking SNMP protocol");
return transition_snmp(content);
}
for(int i=0;i<number_vertices;i++){
if(KMPSearch(edges[current_state][i].rule, content)){
current_state = i;
return true;
}
}
return false;
}
void Graph::setCurrentState(int current_state){
this->current_state = current_state;
}
void Graph::addState(){
Edge e;
e.val = 0;
e.rule = NULL;
vector<Edge> temp(number_vertices, e);
this->number_vertices++;
this->edges.push_back(temp);
for(std::vector<vector<Edge> >::iterator it = edges.begin(); it != edges.end();
++it){
(*it).push_back(e);
}
}
void Graph::addHash(String key, String value){
this->hash_map.insert(pair<String, String>(key, value));
}
String Graph::getHash(String key){
if(hash_map.find(key) == hash_map.end()){
return NULL;
}
else{
return hash_map.find(key)->second;
}
}
void Graph::setProto(Protocol proto){
this->proto = proto;
}
Protocol Graph::getProto(){
return this->proto;
}
void Graph::printHashes(){
for(map<String, String>::iterator it = hash_map.begin(); it!= hash_map.end(); it++){
//click_chatter("Hash %s %s\n", (*it).first.c_str(), (*it).second.c_str());
}
}
/*Support for accepting not added yet*/
void Gateway::parseFSM(FILE* fp, int protocol){
char* line = NULL;
size_t size = 0;
int read;
bool start_reading_states = false;
bool start_reading_hashes = false;
bool start_reading_initial_states = false;
bool start_reading_transitions = false;
bool start_reading_alphabets = false;
size_t size_line;
int counter = 0; //counter for states
//Setting the protocol for transition functions
g->setProto((Protocol)protocol);
while((read = getline(&line,&size, fp)) != -1){
size_line = strlen(line);
//The only possible reason for the size of line to be 1 is only if its a
//new line character
if(strlen(line) == 1){
continue;
}
if(line[size_line-1] == '\n'){
line[size_line-1] = '\0';
}
if(strcmp(line, "#states") == 0){
start_reading_states = true;
start_reading_transitions = false;
start_reading_alphabets = false;
start_reading_initial_states = false;
start_reading_hashes = false;
continue;
}
if(strcmp(line, "#accepting") == 0){
start_reading_states = false;
start_reading_transitions = false;
start_reading_alphabets = true;
start_reading_initial_states = false;
start_reading_hashes = false;
continue;
}
if(strcmp(line, "#transitions") == 0){
start_reading_states = false;
start_reading_transitions = true;
start_reading_alphabets = false;
start_reading_initial_states = false;
start_reading_hashes = false;
continue;
}
if(strcmp(line, "#alphabets") == 0){
start_reading_alphabets = true;
start_reading_states = false;
start_reading_transitions = false;
start_reading_initial_states = false;
start_reading_hashes = false;
continue;
}
if(strcmp(line, "#initial") == 0){
start_reading_alphabets = false;
start_reading_transitions = false;
start_reading_states = false;
start_reading_initial_states = true;
start_reading_hashes = false;
continue;
}
if(strcmp(line, "#hashes") == 0){
start_reading_hashes = true;
start_reading_alphabets = false;
start_reading_transitions = false;
start_reading_states = false;
start_reading_initial_states = false;
continue;
}
if(start_reading_states){
g->map_states.insert(pair<String,int>(String(line), counter++));
g->map_states.insert(pair<String,int>(String(strcat(line, "t")), counter++));
g->addState();
g->addState();
continue;
}
if(start_reading_transitions){
/* for(map<String, int>::iterator it = map_states.begin(); it!= map_states.end();
++it){
//click_chatter("Key %s val %d ", it->first.c_str(), it->second);
}*/
int start, target, temp;
const char* delim = ":/>";
char* token1, *token2, *target_state;
String hash;
token1 = strsep(&line, delim); //starting
start = g->map_states.find(String(token1))->second;
token2 = strsep(&line, "/");//first transition
//click_chatter("Token2 is %s", token2);
hash = g->getHash(String(token2));
temp = g->map_states.find(String(strcat(token1, "t")))->second;
g->addTransition(start, temp, hash);
token2 = strsep(&line, delim);//second transition
target_state = strsep(&line, delim);//final state
target = g->map_states.find(String(target_state))->second;
start = g->map_states.find(String(token1))->second;
g->addTransition(start, target, g->getHash(String(token2)));
continue;
}
if(start_reading_alphabets){
//Don't know what to do
continue;
}
if(start_reading_initial_states){
g->setCurrentState(g->map_states.find(String(line))->second);
continue;
}
if(start_reading_hashes){
const char* delim = ":";
char* token1;
token1 = strsep(&line, delim);
line = line+1;//For the space that follows the colon
g->addHash(String(token1), String(line));
}
}
}
Gateway::Gateway(){
g = new Graph();
}
Gateway::~Gateway(){
delete(g);
}
int Gateway::configure(Vector<String> &conf, ErrorHandler *errh){
String path;
int protocol;
FILE* fp;
if(Args(this, errh).bind(conf).read("FSMFILE", path).read("PROTOCOL", protocol).
complete() < 0){
//click_chatter("Error: Cannot read fsm from the file");
}
fp = fopen(path.c_str(), "r");
parseFSM(fp, protocol);
}
void Gateway::push(int port, Packet* p){
//assert(p->has_network_header());
const click_ip *iph = p->ip_header();
const click_udp *udph = p->udp_header();
char* content;
//click_chatter("proto is %d", iph->ip_p);
if(!udph){
//click_chatter("here");
output(0).push(p);
return;
}
//click_chatter("udph is %x", udph);
//click_chatter("length of udph is %d", ntohs(udph->uh_ulen));
content = (char*)((char*)udph + sizeof(click_udp));
//click_chatter("content is %x", content);
//click_chatter("Value at content is %x", *content);
//click_chatter("value at udph is %x", *udph);
if(!this->g->transition(content)){
output(0).push(p);
}
else{
output(1).push(p);
}
}
CLICK_ENDDECLS
EXPORT_ELEMENT(Gateway)
| 26.481799 | 117 | 0.545646 | [
"object",
"vector"
] |
1aad58c79457ab932253f01907443d1af6b98365 | 685 | cpp | C++ | LeetCode/806.cpp | realvadim/from-software-developer-to-engineer | fa2abfdc3b13ca98db1b525ec67ac921c92e2d6a | [
"MIT"
] | 16 | 2018-10-29T06:42:57.000Z | 2022-01-08T02:42:17.000Z | LeetCode/806.cpp | realvadim/from-software-developer-to-engineer | fa2abfdc3b13ca98db1b525ec67ac921c92e2d6a | [
"MIT"
] | null | null | null | LeetCode/806.cpp | realvadim/from-software-developer-to-engineer | fa2abfdc3b13ca98db1b525ec67ac921c92e2d6a | [
"MIT"
] | 2 | 2019-05-22T02:41:24.000Z | 2019-06-12T15:38:58.000Z | class Solution {
public:
vector<int> numberOfLines(vector<int>& widths, string S) {
vector<int> result;
int numberOfCharactersInCurrentLine = 0;
int numberOfLines = 1;
for(int i = 0; i < S.length(); i++) {
int width = widths[S[i] - 'a'];
if (numberOfCharactersInCurrentLine + width <= 100) {
numberOfCharactersInCurrentLine += width;
} else {
numberOfLines += 1;
numberOfCharactersInCurrentLine = width;
}
}
result.push_back(numberOfLines);
result.push_back(numberOfCharactersInCurrentLine);
return result;
}
};
| 26.346154 | 65 | 0.556204 | [
"vector"
] |
1ac377e1808ccc61265dbdf2ae67185380b9bcf4 | 12,464 | cpp | C++ | VirtualStage/KinectMaskGenerator/main.cpp | nicolasdeory/ailab | 3b41352946a1189e6cd7b576613d44ab90c003f5 | [
"MIT"
] | 4,537 | 2018-08-23T19:37:17.000Z | 2019-05-06T12:48:19.000Z | VirtualStage/KinectMaskGenerator/main.cpp | admariner/ailab | 3bfc475eef00232fce655d94199cc20c7a53d573 | [
"MIT"
] | 37 | 2018-08-30T07:33:36.000Z | 2019-05-03T22:23:59.000Z | VirtualStage/KinectMaskGenerator/main.cpp | admariner/ailab | 3bfc475eef00232fce655d94199cc20c7a53d573 | [
"MIT"
] | 732 | 2018-08-23T17:25:33.000Z | 2019-05-06T13:29:40.000Z | #pragma comment(lib, "k4a.lib")
#define IMG_OFFSET 0
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <k4a/k4a.h>
#include <k4arecord/playback.h>
#include <k4abt.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <fstream>
using namespace cv;
struct stat info;
#define VERIFY(result, error) \
if (result != K4A_RESULT_SUCCEEDED) \
{ \
printf("%s \n - (File: %s, Function: %s, Line: %d)\n", error, __FILE__, __FUNCTION__, __LINE__); \
exit(1); \
}
#define WAIT_VERIFY(result, error) \
if (result != K4A_WAIT_RESULT_SUCCEEDED) \
{ \
printf("%s \n - (File: %s, Function: %s, Line: %d)\n", error, __FILE__, __FUNCTION__, __LINE__); \
exit(1); \
}
static cv::Mat color_to_opencv(const k4a_image_t &im);
static cv::Mat depth_to_opencv(const k4a_image_t &im);
static cv::Mat index_to_opencv(const k4a_image_t &im);
const uint64_t default_interval = 66666;
uint64_t last_duration;
uint64_t current_interval;
struct SyncronizationFileWriter
{
std::ofstream timestampFile;
void init(std::string outputFolder)
{
std::stringstream filename;
filename << outputFolder << "/timestampfile.txt";
timestampFile.open(filename.str().c_str());
}
void writeStamp(int frame_count)
{
std::stringstream ssaux;
ssaux << std::setfill('0') << std::setw(4) << frame_count << "_out.png";
timestampFile << "file " << ssaux.str() << std::endl;
timestampFile << "duration " << current_interval / 1e6 << std::endl;
}
void close()
{
timestampFile.close();
}
};
int main(int argc, char *argv[])
{
if (argc < 5)
{
printf("USAGE: VIDEO_INPUT_PATH MASK_OUTPUT_PATH START DURATION [COLOR_IMG_SUFFIX]");
exit(1);
}
char *INPUT = argv[1];
char *OUTPUT = argv[2];
uint64_t timestamp_start_us = (uint64_t)std::stoi(argv[3]) * (uint64_t)1e6;
printf("Starting at second %f\n", timestamp_start_us / 1e6);
int duration = std::stoi(argv[4]);
uint64_t timestamp_end_us = 0;
if (duration > 0)
{
timestamp_end_us = (uint64_t)std::stoi(argv[4]) * (uint64_t)1e6 + timestamp_start_us;
printf("Finishing at second %f\n", timestamp_end_us / 1e6);
}
bool write_color = false;
char *color_img_suffix = "";
if (argc >= 6)
{
write_color = true;
color_img_suffix = argv[5];
}
SyncronizationFileWriter syncFileWriter;
syncFileWriter.init(OUTPUT);
k4a_playback_t playback_handle = NULL;
VERIFY(k4a_playback_open(INPUT, &playback_handle), "Failed to open recording\n");
uint64_t recording_length = k4a_playback_get_recording_length_usec(playback_handle);
printf("Recording is %lld seconds long\n", recording_length / 1000000);
k4a_calibration_t sensor_calibration;
VERIFY(k4a_playback_get_calibration(playback_handle, &sensor_calibration),
"Get camera calibration failed!");
k4a_playback_set_color_conversion(playback_handle,
K4A_IMAGE_FORMAT_COLOR_BGRA32);
// Create the tracker
k4abt_tracker_t tracker = NULL;
k4abt_tracker_configuration_t tracker_config = K4ABT_TRACKER_CONFIG_DEFAULT;
VERIFY(k4abt_tracker_create(&sensor_calibration, tracker_config, &tracker), "Body tracker initialization failed!");
int frame_count = 0;
char buffer[120];
int color_image_width_pixels = sensor_calibration.color_camera_calibration.resolution_width;
int color_image_height_pixels = sensor_calibration.color_camera_calibration.resolution_height;
int depth_image_width_pixels = sensor_calibration.depth_camera_calibration.resolution_width;
int depth_image_height_pixels = sensor_calibration.depth_camera_calibration.resolution_height;
k4a_image_t mask_image = NULL;
k4a_image_t transformed_mask_image = NULL;
k4a_image_t transformed_depth_image = NULL;
// transform depth camera into color camera geometry
VERIFY(k4a_image_create(K4A_IMAGE_FORMAT_CUSTOM8,
color_image_width_pixels,
color_image_height_pixels,
color_image_width_pixels * (int)sizeof(uint8_t),
&transformed_mask_image),
"Could not create image for mask transformation!");
VERIFY(k4a_image_create(K4A_IMAGE_FORMAT_DEPTH16,
color_image_width_pixels,
color_image_height_pixels,
color_image_width_pixels * (int)sizeof(uint16_t),
&transformed_depth_image),
"Could not create image for depth transformation!");
k4a_transformation_t transformation = k4a_transformation_create(&sensor_calibration);
Mat last_mask = cv::Mat::zeros(cv::Size(1920, 1080), CV_8U);
bool writing = false;
uint64_t initial_duration = 0;
while (true)
{
frame_count++;
// Get a capture
k4a_capture_t sensor_capture;
k4a_stream_result_t get_capture_result = k4a_playback_get_next_capture(playback_handle, &sensor_capture);
if (get_capture_result == K4A_STREAM_RESULT_EOF)
{
break;
}
else if (get_capture_result != K4A_STREAM_RESULT_SUCCEEDED)
{
if (writing)
{
// If the frame is corrupt, we write last interval timestamp and last mask
printf("Warning: Get capture returned error %d on frame %d\n", get_capture_result, frame_count);
snprintf(buffer, 128, "%s/%04d_masksAK.png", OUTPUT, frame_count);
cv::imwrite(buffer, last_mask);
syncFileWriter.writeStamp(frame_count);
}
continue;
}
// if there is no color image, we just consider that frame didn't exist
k4a_image_t color_image = k4a_capture_get_color_image(sensor_capture);
if (color_image == 0)
{
printf("Warning: No color image %d on frame %d, dropped\n", get_capture_result, frame_count);
frame_count--;
k4a_capture_release(sensor_capture);
continue;
}
// write color image
if (writing && write_color)
{
Mat color = color_to_opencv(color_image);
snprintf(buffer, 128, "%s/%04d_%s.png", OUTPUT, frame_count, color_img_suffix);
cv::imwrite(buffer, color);
}
// get frame timestamp information
uint64_t duration_us = k4a_image_get_device_timestamp_usec(color_image);
k4a_image_release(color_image);
if (initial_duration == 0)
{ // get the first duration to compare with the rest
initial_duration = duration_us;
}
current_interval = duration_us - last_duration;
last_duration = duration_us;
// sometimes first timestamp is wrong, in that case we use default
if (current_interval / 1e6 > 5)
{
current_interval = default_interval;
}
// check if we are in the interested piece of video
if (!writing && (duration_us - initial_duration) >= timestamp_start_us)
{
writing = true; // start writing
frame_count = 1;
}
else if (writing && duration > 0 && (duration_us - initial_duration) >= timestamp_end_us)
{
break; // done
}
// don't queue if we are to too far from the start
if (!writing && (duration_us - initial_duration) < (timestamp_start_us - int(1e6)))
{
k4a_capture_release(sensor_capture);
continue;
}
// queque capture
k4a_wait_result_t queue_capture_result = k4abt_tracker_enqueue_capture(tracker, sensor_capture, K4A_WAIT_INFINITE);
k4a_capture_release(sensor_capture);
if (queue_capture_result == K4A_WAIT_RESULT_TIMEOUT)
{
// It should never hit timeout when K4A_WAIT_INFINITE is set.
printf("Error! Add capture to tracker process queue timeout!\n");
exit(1);
}
else if (queue_capture_result == K4A_WAIT_RESULT_FAILED)
{
if (writing)
{
// If for some reason (probably there is no depth information) we don't have a mask for
// this frame, we use the last one
printf("Warning! Add capture to tracker process queue failed! Frame: %d\n", frame_count);
snprintf(buffer, 128, "%s/%04d_masksAK.png", OUTPUT, frame_count);
cv::imwrite(buffer, last_mask);
syncFileWriter.writeStamp(frame_count);
}
continue;
}
// get capture for body tracker
k4abt_frame_t body_frame = NULL;
k4a_wait_result_t pop_frame_result = k4abt_tracker_pop_result(tracker, &body_frame, K4A_WAIT_INFINITE);
if (pop_frame_result == K4A_WAIT_RESULT_TIMEOUT)
{
// It should never hit timeout when K4A_WAIT_INFINITE is set.
printf("Error! Pop body frame result timeout!\n");
exit(1);
}
else if (pop_frame_result != K4A_WAIT_RESULT_SUCCEEDED)
{
printf("Pop body frame result failed!\n");
exit(1);
}
// go to next iteration if we are not writing
if (!writing)
{
k4abt_frame_release(body_frame);
continue;
}
// Process and write mask
k4a_image_t body_index_map = k4abt_frame_get_body_index_map(body_frame);
k4a_capture_t input_capture = k4abt_frame_get_capture(body_frame);
k4a_image_t depth_image = k4a_capture_get_depth_image(input_capture);
// transform body index into mask
Mat depth_mask = index_to_opencv(body_index_map);
cv::bitwise_not(depth_mask, depth_mask);
VERIFY(k4a_image_create_from_buffer(
K4A_IMAGE_FORMAT_CUSTOM8,
depth_image_width_pixels,
depth_image_height_pixels,
depth_image_width_pixels * (int)sizeof(uint8_t),
depth_mask.data,
(size_t)(depth_mask.total() * depth_mask.elemSize()),
NULL,
NULL,
&mask_image),
"Could not create image from buffer!");
VERIFY(k4a_transformation_depth_image_to_color_camera_custom(
transformation,
depth_image,
mask_image,
transformed_depth_image,
transformed_mask_image,
K4A_TRANSFORMATION_INTERPOLATION_TYPE_NEAREST,
0),
"Coud not transform depth image!");
// Get mask, depth and color images
Mat mask = index_to_opencv(transformed_mask_image);
Mat rs_mask;
cv::resize(mask, rs_mask, cv::Size(1920, 1080));
snprintf(buffer, 128, "%s/%04d_masksAK.png", OUTPUT, frame_count);
last_mask = rs_mask;
cv::imwrite(buffer, rs_mask);
syncFileWriter.writeStamp(frame_count);
//imshow("BodyTracking", mask);
//waitKey(1);
k4a_image_release(mask_image);
k4a_image_release(depth_image);
k4a_image_release(body_index_map);
k4a_capture_release(input_capture);
k4abt_frame_release(body_frame);
}
printf("Finished body tracking processing!\n");
// Clean up body tracker
k4abt_tracker_shutdown(tracker);
k4abt_tracker_destroy(tracker);
k4a_playback_close(playback_handle);
syncFileWriter.close();
return 0;
}
static cv::Mat color_to_opencv(const k4a_image_t &im)
{
cv::Mat cv_image_with_alpha(k4a_image_get_height_pixels(im), k4a_image_get_width_pixels(im), CV_8UC4, (void *)k4a_image_get_buffer(im));
cv::Mat cv_image_no_alpha;
cv::cvtColor(cv_image_with_alpha, cv_image_with_alpha, cv::COLOR_BGRA2BGR);
return cv_image_with_alpha;
}
static cv::Mat depth_to_opencv(const k4a_image_t &im)
{
return cv::Mat(k4a_image_get_height_pixels(im),
k4a_image_get_width_pixels(im),
CV_16U,
(void *)k4a_image_get_buffer(im),
static_cast<size_t>(k4a_image_get_stride_bytes(im)));
}
static cv::Mat index_to_opencv(const k4a_image_t &im)
{
return cv::Mat(k4a_image_get_height_pixels(im),
k4a_image_get_width_pixels(im),
CV_8U,
(void *)k4a_image_get_buffer(im),
static_cast<size_t>(k4a_image_get_stride_bytes(im)));
}
| 34.622222 | 138 | 0.648026 | [
"geometry",
"transform"
] |
1ac639805318056ff1edc9dd90685a8879455c91 | 3,454 | cpp | C++ | tests/test_utils.cpp | 6br/gbwtgraph | ecbdd672c17bfe267bbec6ee0cc21e4b5ba82d4a | [
"MIT"
] | null | null | null | tests/test_utils.cpp | 6br/gbwtgraph | ecbdd672c17bfe267bbec6ee0cc21e4b5ba82d4a | [
"MIT"
] | null | null | null | tests/test_utils.cpp | 6br/gbwtgraph | ecbdd672c17bfe267bbec6ee0cc21e4b5ba82d4a | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <gbwtgraph/utils.h>
#include "shared.h"
using namespace gbwtgraph;
namespace
{
//------------------------------------------------------------------------------
class SourceTest : public ::testing::Test
{
public:
void check_nodes(const SequenceSource& source, const std::vector<node_type>& truth) const
{
ASSERT_EQ(source.get_node_count(), truth.size()) << "Incorrect number of nodes";
for(const node_type& node : truth)
{
ASSERT_TRUE(source.has_node(node.first)) << "Node id " << node.first << " is missing from the sequence source";
handle_t handle = source.get_handle(node.first, false);
EXPECT_EQ(source.get_length(handle), node.second.length()) << "Invalid sequence length for node " << node.first;
EXPECT_EQ(source.get_sequence(handle), node.second) << "Invalid sequence for node " << node.first;
view_type view = source.get_sequence_view(handle);
EXPECT_EQ(std::string(view.first, view.second), node.second) << "Invalid sequence view for node " << node.first;
}
}
void check_translation(const SequenceSource& source, const std::vector<translation_type>& truth) const
{
ASSERT_EQ(source.uses_translation(), !(truth.empty())) << "Segment translation is not used as expected";
if(!(source.uses_translation())) { return; }
ASSERT_EQ(source.segment_translation.size(), truth.size()) << "Invalid number of segments";
for(const translation_type& translation : truth)
{
EXPECT_EQ(source.get_translation(translation.first), translation.second) << "Invalid translation for " << translation.first;
}
}
};
TEST_F(SourceTest, EmptySource)
{
SequenceSource source;
std::vector<node_type> nodes;
std::vector<translation_type> translation;
this->check_nodes(source, nodes);
this->check_translation(source, translation);
}
TEST_F(SourceTest, AddNodes)
{
SequenceSource source;
build_source(source);
std::vector<node_type> nodes =
{
{ nid_t(1), "G" },
{ nid_t(2), "A" },
{ nid_t(3), "T" },
{ nid_t(4), "GGG" },
{ nid_t(5), "T" },
{ nid_t(6), "A" },
{ nid_t(7), "C" },
{ nid_t(8), "A" },
{ nid_t(9), "A" },
};
std::vector<translation_type> translation;
this->check_nodes(source, nodes);
this->check_translation(source, translation);
}
TEST_F(SourceTest, TranslateSegments)
{
SequenceSource source;
std::vector<std::pair<std::string, std::string>> segments =
{
{ "s1", "G" },
{ "s2", "A" },
{ "s3", "T" },
{ "s4", "GGGT" },
{ "s6", "A" },
{ "s7", "C" },
{ "s8", "A" },
{ "s9", "A" },
};
for(const std::pair<std::string, std::string>& segment : segments)
{
source.translate_segment(segment.first, get_view(segment.second), 3);
}
std::vector<node_type> nodes =
{
{ nid_t(1), "G" },
{ nid_t(2), "A" },
{ nid_t(3), "T" },
{ nid_t(4), "GGG" },
{ nid_t(5), "T" },
{ nid_t(6), "A" },
{ nid_t(7), "C" },
{ nid_t(8), "A" },
{ nid_t(9), "A" },
};
std::vector<translation_type> translation =
{
{ "s1", { 1, 2 } },
{ "s2", { 2, 3 } },
{ "s3", { 3, 4 } },
{ "s4", { 4, 6 } },
{ "s6", { 6, 7 } },
{ "s7", { 7, 8 } },
{ "s8", { 8, 9 } },
{ "s9", { 9, 10 } },
};
this->check_nodes(source, nodes);
this->check_translation(source, translation);
}
//------------------------------------------------------------------------------
} // namespace
| 27.412698 | 130 | 0.570064 | [
"vector"
] |
1ad8703b25f8bb2eafabbc5db81f6171043d6604 | 2,255 | hpp | C++ | test/testclass.hpp | Ammeraal/Traffic-Sign-Recognition-for-Autonomous-Cars | 6c7e3e61cd301ed8777657322af8709b8249c47e | [
"MIT"
] | 18 | 2018-02-17T20:55:01.000Z | 2022-03-23T11:32:53.000Z | test/testclass.hpp | Ammeraal/Traffic-Sign-Recognition-for-Autonomous-Cars | 6c7e3e61cd301ed8777657322af8709b8249c47e | [
"MIT"
] | 1 | 2019-06-12T12:58:56.000Z | 2019-06-12T12:58:56.000Z | test/testclass.hpp | Ammeraal/Traffic-Sign-Recognition-for-Autonomous-Cars | 6c7e3e61cd301ed8777657322af8709b8249c47e | [
"MIT"
] | 10 | 2018-04-29T19:34:56.000Z | 2022-01-20T10:27:47.000Z | /** MIT License
Copyright (c) 2017 Miguel Maestre Trueba
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.
*
*
*@copyright Copyright 2017 Miguel Maestre Trueba
*@file testclass.hpp
*@author Miguel Maestre Trueba
*@brief Definition for class testclass
*/
#pragma once
#include <cv_bridge/cv_bridge.h>
#include <geometry_msgs/Twist.h>
#include <vector>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/opencv.hpp"
#include "ros/ros.h"
#include "traffic_sign_recognition/sign.h"
/**
*@brief Definition of the testclass class. It contains mock callbacks to test publishers and subscribers.
*/
class testclass {
public:
double area; /// Area of the sign detection
float type; /// Type of sign detected
double vel; /// Velocity given to test subscriber
/**
*@brief Callback used in tests to check if traffic topic is published correctly
*@param msg is the custom message of type sign with traffic sign information
*@return none
*/
void signCallback(traffic_sign_recognition::sign msg);
/**
*@brief Callback used in tests to check if velocity is being published correctly
*@param msg is Twist message with velocity type information
*@return none
*/
void velCallback(geometry_msgs::Twist msg);
};
| 38.87931 | 107 | 0.758758 | [
"vector"
] |
1ad8920d3ff39ccf2de2329a4fd7bcaa4c94f590 | 4,489 | cpp | C++ | examples_glfwnew/30_cadmsh2d/main.cpp | fixedchaos/delfem2 | c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade | [
"MIT"
] | null | null | null | examples_glfwnew/30_cadmsh2d/main.cpp | fixedchaos/delfem2 | c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade | [
"MIT"
] | null | null | null | examples_glfwnew/30_cadmsh2d/main.cpp | fixedchaos/delfem2 | c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <iostream>
#include <math.h>
#include "delfem2/vec3.h"
//
#include "delfem2/cad2_dtri2.h"
// ----
#if defined(_MSC_VER)
# include <windows.h>
#endif
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#ifdef EMSCRIPTEN
# include <emscripten/emscripten.h>
# define GLFW_INCLUDE_ES3
#endif
#include "delfem2/opengl/gl_funcs.h"
#include "delfem2/opengl/glnew_funcs.h"
#include "delfem2/opengl/glnew_v23dtricad.h"
//
#include "delfem2/opengl/glfw/cam_glfw.h"
#include "delfem2/opengl/glfw/viewer_glfw.h"
namespace dfm2 = delfem2;
// -------------------------------------
class CCadDtri_Viewer : public delfem2::opengl::CViewer_GLFW {
public:
CCadDtri_Viewer(){
{
std::vector<double> aXY = {-1,-1, +1,-1, +1,+1, -1,+1};
cad.AddPolygon(aXY);
}
}
void InitGL(){
shdr_cad.Compile();
shdr_dmsh.Compile();
{
shdr_cad.MakeBuffer(cad);
{
std::vector<int> aFlgPnt, aFlgTri;
delfem2::CMesher_Cad2D mesher;
mesher.edge_length = 0.08;
mesher.Meshing(dmsh, cad);
shdr_dmsh.MakeBuffer(dmsh.aVec2, dmsh.aETri);
}
{
std::vector<double> aXYVtx = cad.XY_VtxCtrl_Face(0);
const int nxy = dmsh.aVec2.size();
const int nv = aXYVtx.size()/2;
aW.resize(nxy*nv);
for(int ixy=0;ixy<nxy;++ixy){
dfm2::MeanValueCoordinate2D(aW.data()+nv*ixy,
dmsh.aVec2[ixy].x(), dmsh.aVec2[ixy].y(),
aXYVtx.data(), aXYVtx.size()/2);
double sum = 0.0;
for(int iv=0;iv<nv;++iv){
sum += aW[nv*ixy+iv];
}
assert( fabs(sum-1)<1.0e-10 );
}
}
}
shdr_cad.is_show_face = false;
nav.camera.view_height = 1.5;
nav.camera.camera_rot_mode = delfem2::CCamera<double>::CAMERA_ROT_MODE::TBALL;
}
virtual void mouse_press(const float src[3], const float dir[3]) {
float px, py; nav.PosMouse2D(px, py, window);
cad.Pick(px, py, nav.camera.view_height);
}
virtual void mouse_drag(const float src0[3], const float src1[3], const float dir[3]) {
if( nav.ibutton == 0 ){
float px0,py0, px1,py1; nav.PosMove2D(px0,py0, px1,py1, window);
cad.DragPicked(px1,py1, px0,py0);
shdr_cad.MakeBuffer(cad);
// --
std::vector<double> aXYVtx = cad.XY_VtxCtrl_Face(0);
int nv = aXYVtx.size()/2;
int np = dmsh.aVec2.size();
for(int ip=0;ip<np;++ip){
dmsh.aVec2[ip].p[0] = 0.0;
dmsh.aVec2[ip].p[1] = 0.0;
for(int iv=0;iv<nv;++iv){
dmsh.aVec2[ip].p[0] += aW[ip*nv+iv]*aXYVtx[iv*2+0];
dmsh.aVec2[ip].p[1] += aW[ip*nv+iv]*aXYVtx[iv*2+1];
}
}
shdr_dmsh.MakeBuffer(dmsh.aVec2, dmsh.aETri);
}
}
public:
delfem2::CCad2D cad;
delfem2::CMeshDynTri2D dmsh;
std::vector<double> aW;
delfem2::opengl::CShader_Cad2D shdr_cad;
delfem2::opengl::CShader_MeshDTri2D shdr_dmsh;
};
CCadDtri_Viewer viewer;
// -----------------------------------
void draw(GLFWwindow* window)
{
::glClearColor(0.8, 1.0, 1.0, 1.0);
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
::glEnable(GL_DEPTH_TEST);
::glDepthFunc(GL_LESS);
::glEnable(GL_POLYGON_OFFSET_FILL );
::glPolygonOffset( 1.1f, 4.0f );
float mMV[16], mP[16]; viewer.nav.Matrix_MVP(mMV, mP, window);
viewer.shdr_cad.Draw(mP, mMV, viewer.cad);
viewer.shdr_dmsh.Draw(mP, mMV);
glfwSwapBuffers(window);
glfwPollEvents();
}
void callback_key(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void callback_resize(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(void)
{
viewer.Init_newGL();
// glad: load all OpenGL function pointers
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
viewer.InitGL();
#ifdef EMSCRIPTEN
emscripten_set_main_loop_arg((em_arg_callback_func) draw, viewer.window, 60, 1);
#else
while (!glfwWindowShouldClose(viewer.window)) { draw(viewer.window); }
#endif
glfwDestroyWindow(viewer.window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| 25.947977 | 89 | 0.61595 | [
"cad",
"vector"
] |
1adac0536e7e77ce9462f41c0ac795f5f209527c | 28,099 | cpp | C++ | panorama.cpp | nitinmadhok/panorama | 8cc271bbbdbe5289d894ce564e452134168d5eb1 | [
"MIT"
] | null | null | null | panorama.cpp | nitinmadhok/panorama | 8cc271bbbdbe5289d894ce564e452134168d5eb1 | [
"MIT"
] | null | null | null | panorama.cpp | nitinmadhok/panorama | 8cc271bbbdbe5289d894ce564e452134168d5eb1 | [
"MIT"
] | null | null | null | /*
Description: Program to create a panorama from two input images, display it using OpenGL, optionally write it using OpenImageIO.
Name: Nitin Madhok
Date: December 4, 2013
Email: nmadhok@clemson.edu
*/
#ifdef __APPLE__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include <cstdio>
#include <cstring>
#include <cmath>
#include "panorama.h"
#include <OpenImageIO/imageio.h>
OIIO_NAMESPACE_USING
using namespace std;
// Function to return the maximum of eight integers
int maximum(int a, int b, int c, int d, int e, int f, int g, int h) {
int num[8] = {a, b, c, d, e, f, g, h};
int max=num[0];
for(int i=1; i<8; i++) {
if(num[i]>max)
max=num[i];
}
return max;
}
// Function to return the minimum of eight integers
int minimum(int a, int b, int c, int d, int e, int f, int g, int h) {
int num[8] = {a, b, c, d, e, f, g, h};
int min=num[0];
for(int i=1; i<8; i++) {
if(num[i]<min)
min=num[i];
}
return min;
}
// Function to display input image1 using OpenGL.
void display1(){
glClear(GL_COLOR_BUFFER_BIT);
// Define the Drawing Coordinate system on the viewport
// Lower left is (0, 0), Upper right is (width, height)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, xres1, 0, yres1);
// Specifies the raster position for pixel operations
glRasterPos2i(0,0);
// Writes a block of pixels to the framebuffer
glDrawPixels(xres1,yres1,GL_RGBA,GL_UNSIGNED_BYTE, data1);
// To Force execution of GL commands in finite time
glFlush();
}
// Function to display input image2 using OpenGL.
void display2(){
glClear(GL_COLOR_BUFFER_BIT);
// Define the Drawing Coordinate system on the viewport
// Lower left is (0, 0), Upper right is (width, height)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, xres2, 0, yres2);
// Specifies the raster position for pixel operations
glRasterPos2i(0,0);
// Writes a block of pixels to the framebuffer
glDrawPixels(xres2,yres2,GL_RGBA,GL_UNSIGNED_BYTE, data2);
// To Force execution of GL commands in finite time
glFlush();
}
// Function to display panorama using OpenGL.
void display3(){
glClear(GL_COLOR_BUFFER_BIT);
// Define the Drawing Coordinate system on the viewport
// Lower left is (0, 0), Upper right is (width, height)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, xresWarped, 0, yresWarped);
// Specifies the raster position for pixel operations
glRasterPos2i(0,0);
// Writes a block of pixels to the framebuffer
glDrawPixels(xresWarped,yresWarped,GL_RGBA,GL_UNSIGNED_BYTE, dataWarped);
// To Force execution of GL commands in finite time
glFlush();
}
// Function to draw maximum four points on each input image upon mouse click
void drawSquare(int x, int y, int win) {
// Set Point size
glPointSize(7);
// Enable GL_POINT_SMOOTH so that the point is not a square but a circle
glEnable(GL_POINT_SMOOTH);
// If points clicked on Input Image1 then draw points on it
if(win==1) {
y = yres1-y;
switch(counter1) {
case 3:
point1_image1[0] = x;
point1_image1[1] = y;
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 2:
point2_image1[0] = x;
point2_image1[1] = y;
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 1:
point3_image1[0] = x;
point3_image1[1] = y;
glColor3f(0.0f, 1.0f, 0.0f);
break;
case 0:
point4_image1[0] = x;
point4_image1[1] = y;
glColor3f(1.0f, 1.0f, 0.0f);
break;
}
}
// If points clicked on Input Image2 then draw points on it
else if(win==2) {
y = yres2-y;
switch(counter2) {
case 3:
point1_image2[0] = x;
point1_image2[1] = y;
b[0]=x;
b[1]=y;
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 2:
point2_image2[0] = x;
point2_image2[1] = y;
b[2]=x;
b[3]=y;
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 1:
point3_image2[0] = x;
point3_image2[1] = y;
b[4]=x;
b[5]=y;
glColor3f(0.0f, 1.0f, 0.0f);
break;
case 0:
point4_image2[0] = x;
point4_image2[1] = y;
b[6]=x;
b[7]=y;
glColor3f(1.0f, 1.0f, 0.0f);
break;
}
}
glBegin(GL_POINTS);
glVertex2f(x , y);
glEnd();
glutSwapBuffers();
// If all 4 points on each input image have been clicked then compute the homography and create the panorama
if(counter1==0 && counter2==0) {
computeHomographyMatrix();
if(numberOfArguments==4) {
writeImage();
cout<<"File: "<<outfilename<<" written successfully!"<<endl;
}
}
}
// Function to write an image using OpenImageIO that reads and stores the pixel bein g displayed on screen using OpenGL
void writeImage() {
// Store the Output File Type in outfiletype, example .ppm or .jpg
string outfiletype = outfilename.substr(outfilename.find("."));
// Create ImageOutput instance using the outfilename & exit if error in creating
ImageOutput *out = ImageOutput::create(outfilename);
if (!out) {
cerr << "Could not create an ImageOutput for "
<< outfilename << "\nError: "
<< geterror()<<endl;
exit(-1);
}
// Set outputchannels to 3 if outputfiletype is either ppm/pnm/pgm/pbm/hdr/rgbe else let it be equal to the number of channels of the input image (either 3 or 4)
int outputchannels = (outfiletype==".ppm" || outfiletype==".pnm" || outfiletype==".pgm" || outfiletype==".pbm" || outfiletype==".hdr" || outfiletype==".rgbe" ? 3 : channels1 );
// Allocate memory based on the number of channels
unsigned char *oiio_pixels = new unsigned char[xresWarped*yresWarped*outputchannels];
// Check if memory has been allocated successfully
if (oiio_pixels==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete out;
}
// If number of channels is 4 then read in RGBA format using GL_RGBA
if(outputchannels==4) {
for(int i=0, k=0; i<yresWarped && k<(xresWarped*yresWarped*outputchannels); i++) {
for(int j=0; j<xresWarped; j++, k+=4) {
oiio_pixels[k] = pixmapWarped[i][j].red;
oiio_pixels[k+1] = pixmapWarped[i][j].green;
oiio_pixels[k+2] = pixmapWarped[i][j].blue;
oiio_pixels[k+3] = pixmapWarped[i][j].alpha;
}
}
}
// If number of channels is 3 then read in RGB format using GL_RGB
else if(outputchannels==3) {
for(int i=0, k=0; i<yresWarped && k<(xresWarped*yresWarped*outputchannels); i++) {
for(int j=0; j<xresWarped; j++, k+=3) {
oiio_pixels[k] = pixmapWarped[i][j].red;
oiio_pixels[k+1] = pixmapWarped[i][j].green;
oiio_pixels[k+2] = pixmapWarped[i][j].blue;
}
}
}
// Create ImageSpec for the output image with name outfile
ImageSpec spec(xresWarped,yresWarped,outputchannels,TypeDesc::UINT8);
if (! out->open (outfilename, spec)) {
cerr << "Could not open "
<< outfilename << "\nError: "
<< out->geterror()<< endl;
delete out;
delete [] oiio_pixels;
exit(-1);
}
// This particular call to write flips the image for us
int scanlinesize = xresWarped * outputchannels * sizeof(oiio_pixels[0]);
if(! out->write_image (TypeDesc::UINT8, (unsigned char*)oiio_pixels+(yresWarped-1)*scanlinesize, AutoStride, -scanlinesize, AutoStride)) {
cerr << "Could not write pixels to "
<< outfilename << "\nError: "
<< out->geterror()<< endl;
delete out;
delete [] oiio_pixels;
exit(-1);
}
// Close the output file
if(! out->close ()) {
std::cerr << "Error closing "
<< outfilename << "\nError: "
<< out->geterror() << endl;
delete out;
delete [] oiio_pixels;
exit(-1);
}
delete out;
delete [] oiio_pixels;
}
// Keyboard Callback Routine:
// 'q' or 'Q' or ESC to quit
// This routine is called every time a key is pressed on the keyboard
void keyboard(unsigned char key, int x, int y){
switch(key){
// If 'q' or 'Q' or ESC key is pressed, then Exit
case 'q':
case 'Q':
case 27:
exit(0);
// If any other key is pressed then do nothing and ignore the key press
default:
return;
}
}
// Mouse Callback Routine:
// This routine is called every time a mouse click is encountered
void handleMouseClick1(int button, int state, int x, int y){
switch(button){
// If Left Click
case GLUT_LEFT_BUTTON:
// If click released and there are points left to be clicked on input image1
if(state == GLUT_DOWN && counter1>0){
counter1--;
drawSquare(x,y,1);
}
// If any other mouse click is encountered then do nothing and ignore the click
default:
return;
}
}
// Mouse Callback Routine:
// This routine is called every time a mouse click is encountered
void handleMouseClick2(int button, int state, int x, int y){
switch(button){
// If Left Click
case GLUT_LEFT_BUTTON:
// If click released and there are points left to be clicked on input image1
if(state == GLUT_DOWN && counter2>0){
counter2--;
drawSquare(x,y,2);
}
// If any other mouse click is encountered then do nothing and ignore the click
default:
return;
}
}
// Function to create the display window using OpenGL
void CreateGLWindow(int w, int h) {
// Create the Graphics Window, giving width & height & title text
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
// Window 2
glutInitWindowSize(xres2, yres2);
glutCreateWindow(filename2);
glutPositionWindow(w+10,0);
// Set up the callback routines to be called when glutMainLoop() detects an event
glutSetCursor(GLUT_CURSOR_INFO); // Set Cursor to Pointing Hand
glutDisplayFunc(display2); // Display callback
glutKeyboardFunc(keyboard); // Keyboard callback
glutMouseFunc(handleMouseClick2); // Mouse Click callback
// Window 1
glutInitWindowSize(xres1, yres1);
glutCreateWindow(filename1);
glutPositionWindow(0,0);
// Set up the callback routines to be called when glutMainLoop() detects an event
glutSetCursor(GLUT_CURSOR_INFO); // Set Cursor to Pointing Hand
glutDisplayFunc(display1); // Display callback
glutKeyboardFunc(keyboard); // Keyboard callback
glutMouseFunc(handleMouseClick1); // Mouse Click callback
}
// Function to compute the homography matrix, warp the second imput image using inverse warp and stitch it with the first input image. Magnifications artifacts are fixed by using Bilinear Interpolation.
void computeHomographyMatrix() {
// Compute 8x8 Matrix
A[0][0] = point1_image1[0];
A[0][1] = point1_image1[1];
A[0][2] = 1;
A[0][3] = 0;
A[0][4] = 0;
A[0][5] = 0;
A[0][6] = -(point1_image1[0] * point1_image2[0]);
A[0][7] = -(point1_image1[1] * point1_image2[0]);
A[1][0] = 0;
A[1][1] = 0;
A[1][2] = 0;
A[1][3] = point1_image1[0];
A[1][4] = point1_image1[1];
A[1][5] = 1;
A[1][6] = -(point1_image1[0] * point1_image2[1]);
A[1][7] = -(point1_image1[1] * point1_image2[1]);
A[2][0] = point2_image1[0];
A[2][1] = point2_image1[1];
A[2][2] = 1;
A[2][3] = 0;
A[2][4] = 0;
A[2][5] = 0;
A[2][6] = -(point2_image1[0] * point2_image2[0]);
A[2][7] = -(point2_image1[1] * point2_image2[0]);
A[3][0] = 0;
A[3][1] = 0;
A[3][2] = 0;
A[3][3] = point2_image1[0];
A[3][4] = point2_image1[1];
A[3][5] = 1;
A[3][6] = -(point2_image1[0] * point2_image2[1]);
A[3][7] = -(point2_image1[1] * point2_image2[1]);
A[4][0] = point3_image1[0];
A[4][1] = point3_image1[1];
A[4][2] = 1;
A[4][3] = 0;
A[4][4] = 0;
A[4][5] = 0;
A[4][6] = -(point3_image1[0] * point3_image2[0]);
A[4][7] = -(point3_image1[1] * point3_image2[0]);
A[5][0] = 0;
A[5][1] = 0;
A[5][2] = 0;
A[5][3] = point3_image1[0];
A[5][4] = point3_image1[1];
A[5][5] = 1;
A[5][6] = -(point3_image1[0] * point3_image2[1]);
A[5][7] = -(point3_image1[1] * point3_image2[1]);
A[6][0] = point4_image1[0];
A[6][1] = point4_image1[1];
A[6][2] = 1;
A[6][3] = 0;
A[6][4] = 0;
A[6][5] = 0;
A[6][6] = -(point4_image1[0] * point4_image2[0]);
A[6][7] = -(point4_image1[1] * point4_image2[0]);
A[7][0] = 0;
A[7][1] = 0;
A[7][2] = 0;
A[7][3] = point4_image1[0];
A[7][4] = point4_image1[1];
A[7][5] = 1;
A[7][6] = -(point4_image1[0] * point4_image2[1]);
A[7][7] = -(point4_image1[1] * point4_image2[1]);
// Computer Inverse of 8x8 matrix
invA = A.inv();
// Multiply the inverse of 8x8 matrix with the 1x8 vector having points from input image2 to get the 1x8 homography vector
h=invA*b;
// Create the homography matrix from the homography vector
M[0][0] = h[0]; // a
M[0][1] = h[1]; // b
M[0][2] = h[2]; // c
M[1][0] = h[3]; // d
M[1][1] = h[4]; // e
M[1][2] = h[5]; // f
M[2][0] = h[6]; // g
M[2][1] = h[7]; // h
M[2][2] = 1; // i
// Compute the inverse of homography matrix
invM=M.inv();
// Corner Points of input image1
Vector3d bottom_left1(0,0,1);
Vector3d bottom_right1(xres1,0,1);
Vector3d top_left1(0,yres1,1);
Vector3d top_right1(xres1,yres1,1);
// Corner Points of input image2
Vector3d bottom_left2(0,0,1);
Vector3d bottom_right2(xres2,0,1);
Vector3d top_left2(0,yres2,1);
Vector3d top_right2(xres2,yres2,1);
// Compute the mapping of corner points of input image2 upon warp
Vector3d new_bottom_left = invM * bottom_left2;
Vector3d new_bottom_right = invM * bottom_right2;
Vector3d new_top_left = invM * top_left2;
Vector3d new_top_right = invM * top_right2;
// Normalize the points
new_bottom_left[0] = new_bottom_left[0] / new_bottom_left[2];
new_bottom_left[1] = new_bottom_left[1] / new_bottom_left[2];
new_bottom_left[2] = new_bottom_left[2] / new_bottom_left[2];
new_bottom_right[0] = new_bottom_right[0] / new_bottom_right[2];
new_bottom_right[1] = new_bottom_right[1] / new_bottom_right[2];
new_bottom_right[2] = new_bottom_right[2] / new_bottom_right[2];
new_top_left[0] = new_top_left[0] / new_top_left[2];
new_top_left[1] = new_top_left[1] / new_top_left[2];
new_top_left[2] = new_top_left[2] / new_top_left[2];
new_top_right[0] = new_top_right[0] / new_top_right[2];
new_top_right[1] = new_top_right[1] / new_top_right[2];
new_top_right[2] = new_top_right[2] / new_top_right[2];
// Find the minimum and maximum x,y coordinates from taking all points from input image1 and input image2
min_x = minimum(new_bottom_left[0], new_bottom_right[0], new_top_left[0], new_top_right[0], bottom_left1[0], bottom_right1[0], top_left1[0], top_right1[0]);
min_y = minimum(new_bottom_left[1], new_bottom_right[1], new_top_left[1], new_top_right[1], bottom_left1[1], bottom_right1[1], top_left1[1], top_right1[1]);
max_x = maximum(new_bottom_left[0], new_bottom_right[0], new_top_left[0], new_top_right[0], bottom_left1[0], bottom_right1[0], top_left1[0], top_right1[0]);
max_y = maximum(new_bottom_left[1], new_bottom_right[1], new_top_left[1], new_top_right[1], bottom_left1[1], bottom_right1[1], top_left1[1], top_right1[1]);
// Compute the origin
Vector3d origin(min_x, min_y, 0);
// Compute the size of the panorama
xresWarped = max_x - min_x;
yresWarped = max_y - min_y;
cout<<"\n\nPanorama Specification:"<<endl;
cout<<"Image Width: "<<xresWarped<<endl;
cout<<"Image Height: "<<yresWarped<<endl;
cout<<"\nDisplaying Panorama"<<endl;
if(xresWarped == 0) {
xresWarped = 1;
}
if(yresWarped == 0) {
yresWarped = 1;
}
// Allocate memory of size equal to the height of the image to store pointers
//pixmapWarped = new pixel*[spec.height];
pixmapWarped = new pixel*[yresWarped];
// Check if memory has been allocated successfully
if (pixmapWarped==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
}
// Allocate memory to store all the RGBA data from the image of size=width*height! (Contiguous Allocation)
dataWarped = new pixel[yresWarped*xresWarped];
// Check if memory has been allocated successfully
if (dataWarped==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete[] pixmapWarped;
}
// Set the pointer present at 0th position of pixmap to the data
pixmapWarped[0] = dataWarped;
// Set the rest of the pointers to the different rows of the image. Notice it can be accessed like a 2D array
for (int y=1; y<yresWarped; y++) {
pixmapWarped[y] = pixmapWarped[y-1] + xresWarped;
}
for (int y = 0; y < yresWarped; y++) {
for (int x = 0; x < xresWarped; x++) {
//map the pixel coordinates
Vector3d pixel_out(x, y, 1);
pixel_out = pixel_out + origin;
Vector3d pixel_in = M * pixel_out;
//normalize the pixmap
float m = pixel_in[0] / pixel_in[2];
float n = pixel_in[1] / pixel_in[2];
// Use Bilinear Interpolation to fix magnification artifacts
int k = floor(m);
int j = floor(n);
float a = n - j;
float b = m - k;
int p = floor(pixel_out[0]);
int q = floor(pixel_out[1]);
// Take pixel from input image2
if((j>=0 && j<yres2-1) && (k>=0 && k<xres2-1)) {
pixmapWarped[y][x].red = (((1-b) * ((pixmap2[j][k].red * (1-a)) + (pixmap2[j+1][k].red * a))) + (b * ((pixmap2[j][k+1].red * (1-a)) + (pixmap2[j+1][k+1].red * a))));
pixmapWarped[y][x].green = (((1-b) * ((pixmap2[j][k].green * (1-a)) + (pixmap2[j+1][k].green * a))) + (b * ((pixmap2[j][k+1].green * (1-a)) + (pixmap2[j+1][k+1].green * a))));
pixmapWarped[y][x].blue = (((1-b) * ((pixmap2[j][k].blue * (1-a)) + (pixmap2[j+1][k].blue * a))) + (b * ((pixmap2[j][k+1].blue * (1 -a)) + (pixmap2[j+1][k+1].blue * a))));
pixmapWarped[y][x].alpha = (((1-b) * ((pixmap2[j][k].alpha * (1-a)) + (pixmap2[j+1][k].alpha * a))) + (b * ((pixmap2[j][k+1].alpha * (1-a)) + (pixmap2[j+1][k+1].alpha * a))));
}
// Take pixel from input image2
else if(j==yres2-1 && k==xres2-1) {
pixmapWarped[y][x] = pixmap2[j][k];
}
// Take pixel from input image1
else if (q>=0 && q<yres1 && p>=0 && p<xres1) {
pixmapWarped[y][x] = pixmap1[q][p];
}
else {
// Black pixel
}
}
}
// Window 3
glutInitWindowSize(xresWarped, yresWarped);
glutCreateWindow("Final Panorama");
// Set up the callback routines to be called when glutMainLoop() detects an event
glutDisplayFunc(display3); // Display callback
glutKeyboardFunc(keyboard); // Keyboard callback
}
// Main function
int main(int argc, char *argv[]) {
// Check for the number of arguments. Display message and exit if incorrect number of arguments
if((argc < 3) || (argc > 4)){
cerr<<"Usage: "<<argv[0]<<" inputimage1 inputimage2 "<<endl;
cerr<<" -OR-"<<endl;
cerr<<"Usage: "<<argv[0]<<" inputimage1 "<<"inputimage2 outputimage"<<endl;
return 1;
}
numberOfArguments = argc;
// If there are three command line arguments passed then store the fourth argument as output file name
if(argc==4) {
outfilename = argv[3];
}
// Set pointerd to the second and third command line argument (input file)
filename1 = argv[1];
filename2 = argv[2];
// Input file name is equal to the second and third command line argument
infilename1 = argv[1];
infilename2 = argv[2];
// Create an ImageInput for the input image and exit if error occurs
ImageInput *in1 = ImageInput::create(filename1);
if(!in1) {
cerr<<"Could not create an ImageInput for "
<<filename1<<"\nError: "
<<geterror()<<endl;
exit(-1);
}
// Create an ImageSpec and open the image. If error occurs then exit
ImageSpec spec1;
if (! in1->open (filename1, spec1)) {
cerr<<"Could not open "
<<filename1<<"\nError: "
<<in1->geterror()<<endl;
delete in1;
exit(-1);
}
// Create an ImageInput for the input image and exit if error occurs
ImageInput *in2 = ImageInput::create(filename2);
if(!in2) {
cerr<<"Could not create an ImageInput for "
<<filename2<<"\nError: "
<<geterror()<<endl;
exit(-1);
delete in1;
}
// Create an ImageSpec and open the image. If error occurs then exit
ImageSpec spec2;
if (! in2->open (filename2, spec2)) {
cerr<<"Could not open "
<<filename2<<"\nError: "
<<in2->geterror()<<endl;
delete in2;
delete in1;
exit(-1);
}
// Store the width, height, number of channels, names of channels and channel format in variables
cout<<"\nFirst Input Image Specification: "<<endl;
xres1 = spec1.width;
cout<<"Image Width: "<<xres1<<endl;
yres1 = spec1.height;
cout<<"Image Height: "<<yres1<<endl;
channels1 = spec1.nchannels;
cout<<"No. of Channels: "<<channels1<<endl;
cout<<"Channel Names: ";
for (int i = 0; i < spec1.nchannels; ++i)
cout<<spec1.channelnames[i] << " ";
cout<<"\n";
cout<<"Color Depth: "<<sizeof(spec1.format)*spec1.nchannels<<"bpp"<<endl;
// Store the width, height, number of channels, names of channels and channel format in variables
cout<<"\n\nSecond Input Image Specification: "<<endl;
xres2 = spec2.width;
cout<<"Image Width: "<<xres2<<endl;
yres2 = spec2.height;
cout<<"Image Height: "<<yres2<<endl;
channels2 = spec1.nchannels;
cout<<"No. of Channels: "<<channels2<<endl;
cout<<"Channel Names: ";
for (int i = 0; i < spec2.nchannels; ++i)
cout<<spec2.channelnames[i] << " ";
cout<<"\n";
cout<<"Color Depth: "<<sizeof(spec2.format)*spec2.nchannels<<"bpp"<<endl;
// Allocate memory to store image data read using OpenImageIO
pixels1 = new unsigned char [xres1*yres1*channels1];
pixels2 = new unsigned char [xres2*yres2*channels2];
// Obtain the size in bits of a single scanline
int scanlinesize1 = spec1.width * spec1.nchannels * sizeof(pixels1[0]);
int scanlinesize2 = spec2.width * spec2.nchannels * sizeof(pixels2[0]);
// Read the image and exit if error occurs. This also flips the image automatically for us
if(! in1->read_image (TypeDesc::UINT8, (char *)pixels1+(yres1-1)*scanlinesize1, AutoStride, -scanlinesize1, AutoStride)) {
cerr<<"Could not read pixels from "
<<filename1<<"\nError: "
<<in1->geterror()<<endl;
exit(-1);
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Read the image and exit if error occurs. This also flips the image automatically for us
if(! in2->read_image (TypeDesc::UINT8, (char *)pixels2+(yres2-1)*scanlinesize2, AutoStride, -scanlinesize2, AutoStride)) {
cerr<<"Could not read pixels from "
<<filename2<<"\nError: "
<<in2->geterror()<<endl;
exit(-1);
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Allocate memory of size equal to the height of the image to store pointers
pixmap1 = new pixel*[spec1.height];
// Check if memory has been allocated successfully
if (pixmap1==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Allocate memory to store all the RGBA data from the image of size=width*height! (Contiguous Allocation)
data1 = new pixel[spec1.height*spec1.width];
// Check if memory has been allocated successfully
if (data1==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Set the pointer present at 0th position of pixmap to the data
pixmap1[0] = data1;
// Set the rest of the pointers to the different rows of the image. Notice it can be accessed like a 2D array
for (int y=1; y<yres1; y++) {
pixmap1[y] = pixmap1[y-1] + xres1;
}
//If the input image has 3 channels
if(spec1.nchannels==3) {
// Read in all the RGB data and store it in data specifying value of alpha as 255
for (int j=0, i=0; j<(xres1*yres1*channels1) && i<(xres1*yres1); j+=3, i++) {
data1[i].red = pixels1[j];
data1[i].green = pixels1[j+1];
data1[i].blue = pixels1[j+2];
data1[i].alpha = 255;
}
}
//If the input image has 4 channels (Alpha)
else if(spec1.nchannels==4) {
// Read in all the RGBA data and store it in data
for (int j=0, i=0; j<(xres1*yres1*channels1) && i<(xres1*yres1); j+=4, i++) {
data1[i].red = pixels1[j];
data1[i].green = pixels1[j+1];
data1[i].blue = pixels1[j+2];
data1[i].alpha = pixels1[j+3];
}
}
// Allocate memory of size equal to the height of the image to store pointers
pixmap2 = new pixel*[spec2.height];
// Check if memory has been allocated successfully
if (pixmap2==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete[] data1;
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Allocate memory to store all the RGBA data from the image of size=width*height! (Contiguous Allocation)
data2 = new pixel[spec2.height*spec2.width];
// Check if memory has been allocated successfully
if (data2==0) {
// Memory not allocated successfully! Display message and Exit
cout<<"Couldn't allocate memory. Exiting!"<<endl;
exit(-1);
delete[] pixmap2;
delete[] data1;
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Set the pointer present at 0th position of pixmap to the data
pixmap2[0] = data2;
// Set the rest of the pointers to the different rows of the image. Notice it can be accessed like a 2D array
for (int y=1; y<yres2; y++) {
pixmap2[y] = pixmap2[y-1] + xres2;
}
//If the input image has 3 channels
if(spec2.nchannels==3) {
// Read in all the RGB data and store it in data specifying value of alpha as 255
for (int j=0, i=0; j<(xres2*yres2*channels2) && i<(xres2*yres2); j+=3, i++) {
data2[i].red = pixels2[j];
data2[i].green = pixels2[j+1];
data2[i].blue = pixels2[j+2];
data2[i].alpha = 255;
}
}
//If the input image has 4 channels (Alpha)
else if(spec2.nchannels==4) {
// Read in all the RGBA data and store it in data
for (int j=0, i=0; j<(xres2*yres2*channels2) && i<(xres2*yres2); j+=4, i++) {
data2[i].red = pixels2[j];
data2[i].green = pixels2[j+1];
data2[i].blue = pixels2[j+2];
data2[i].alpha = pixels2[j+3];
}
}
// Close the input file and exit if error occurs
if(! in1->close ()) {
cerr<<"Error closing "
<<filename1<<"\nError: "
<<in1->geterror()<<endl;
exit(-1);
delete[] data2;
delete[] pixmap2;
delete[] data1;
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Close the input file and exit if error occurs
if(! in2->close ()) {
cerr<<"Error closing "
<<filename2<<"\nError: "
<<in2->geterror()<<endl;
exit(-1);
delete[] data2;
delete[] pixmap2;
delete[] data1;
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
// Start up the GLUT utilities
glutInit(&argc, argv);
CreateGLWindow(xres1, yres1);
// Routine that loops forever looking for events. It calls the registered callback routine to handle each event that is detected
glutMainLoop();
// Delete the memory allocated manualy at the end of the program
delete[] dataWarped;
delete[] pixmapWarped;
delete[] data2;
delete[] pixmap2;
delete[] data1;
delete[] pixmap1;
delete pixels2;
delete pixels1;
delete in2;
delete in1;
}
| 31.395531 | 203 | 0.631232 | [
"vector"
] |
1adadb405b0583798288fd845c81fdb694f276bc | 2,281 | cpp | C++ | 10_MST/02_prim.cpp | NaskoVasilev/Data-Structures-And-Algorithms | 1a4dba588df7e88498fddda9c04a8832f8c0dad8 | [
"MIT"
] | 2 | 2021-10-31T18:32:47.000Z | 2022-01-28T08:58:34.000Z | 10_MST/02_prim.cpp | NaskoVasilev/Data-Structures-And-Algorithms | 1a4dba588df7e88498fddda9c04a8832f8c0dad8 | [
"MIT"
] | null | null | null | 10_MST/02_prim.cpp | NaskoVasilev/Data-Structures-And-Algorithms | 1a4dba588df7e88498fddda9c04a8832f8c0dad8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
struct Edge {
int from;
int to;
int weight;
};
struct EdgeComparator {
bool operator()(const Edge &first, const Edge &second) const {
return first.weight > second.weight;
}
};
void prim(vector<vector<Edge>> &graph, int startNode, set<int> &spanningTreeNodes, vector<Edge> &mst) {
spanningTreeNodes.insert(startNode);
priority_queue<Edge, vector<Edge>, EdgeComparator> pq;
for (auto const &edge : graph[startNode]) {
pq.push(edge);
}
while (!pq.empty()) {
Edge currentEdge = pq.top();
pq.pop();
int otherNode = spanningTreeNodes.count(currentEdge.from) ? currentEdge.to : currentEdge.from;
if (!spanningTreeNodes.count(otherNode)) {
mst.push_back(currentEdge);
spanningTreeNodes.insert(otherNode);
for (auto const &edge : graph[otherNode]) {
pq.push(edge);
}
}
}
}
int main() {
int nodes, edgesCount;
cin >> nodes >> edgesCount;
vector<vector<Edge>> graph(nodes);
for (int i = 0; i < edgesCount; ++i) {
int from, to, weight;
cin >> from >> to >> weight;
graph[from].push_back({from, to, weight});
graph[to].push_back({to, from, weight});
}
vector<Edge> mstEdges;
vector<vector<Edge>> msf;
set<int> spanningTreeNodes;
for (int i = 0; i < nodes; ++i) {
if (!spanningTreeNodes.count(i)) {
prim(graph, i, spanningTreeNodes, mstEdges);
msf.emplace_back(mstEdges.begin(), mstEdges.end());
mstEdges.clear();
}
}
cout << "MST forest: " << endl;
int index = 1;
for (auto const &mst : msf) {
cout << "Mst: " << index++ << endl;
for (auto const &edge : mst) {
cout << edge.from << " -> " << edge.to << " with weight: " << edge.weight << endl;
}
}
}
//9 11
//0 1 4
//0 2 5
//0 3 9
//2 3 20
//2 4 7
//3 4 8
//4 5 12
//6 7 7
//6 8 8
//7 8 10
//1 3 2
//MST edges:
//1 -> 3 with weight: 2
//0 -> 1 with weight: 4
//0 -> 2 with weight: 5
//2 -> 4 with weight: 7
//6 -> 7 with weight: 7
//6 -> 8 with weight: 8
//4 -> 5 with weight: 12 | 23.515464 | 103 | 0.555897 | [
"vector"
] |
8c2db2b71916b74dcc0be20319e5d268caeede5c | 1,186 | cpp | C++ | live555/client/ClientSession.cpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | 1 | 2020-02-11T05:37:54.000Z | 2020-02-11T05:37:54.000Z | live555/client/ClientSession.cpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | null | null | null | live555/client/ClientSession.cpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | 1 | 2022-03-01T00:47:19.000Z | 2022-03-01T00:47:19.000Z | /**
* @file ClientSession.cpp
* @brief ClientSession class implementation.
* @author zer0
* @date 2018-10-02
*/
#include <libc2rtsp/client/ClientSession.hpp>
#include <libc2rtsp/client/ClientSubsession.hpp>
#include <libc2rtsp/log/Log.hpp>
#include <cassert>
namespace libc2rtsp {
namespace client {
ClientSession::ClientSession(UsageEnvironment & env) : MediaSession(env)
{
// EMPTY.
}
ClientSession::~ClientSession()
{
// EMPTY.
}
ClientSession * ClientSession::createNew(UsageEnvironment & env, std::string const & sdp_description)
{
ClientSession * new_session = nullptr;
try {
new_session = new ClientSession(env);
} catch (...) {
crLogSE("ClientSession::createNew() Could not create object.");
return nullptr;
}
assert(new_session != nullptr);
if (!new_session->initializeWithSDP(sdp_description.c_str())) {
delete new_session;
crLogSE("ClientSession::createNew() SDP error.");
return nullptr;
}
return new_session;
}
MediaSubsession * ClientSession::createNewMediaSubsession()
{
return new ClientSubsession(*this);
}
} // namespace client
} // namespace libc2rtsp
| 21.962963 | 101 | 0.684654 | [
"object"
] |
8c2fd7975fc3a66ecb93a29cccc1ccbeccd6f9de | 1,341 | cpp | C++ | aws-cpp-sdk-grafana/source/model/PermissionEntry.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-grafana/source/model/PermissionEntry.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-grafana/source/model/PermissionEntry.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/grafana/model/PermissionEntry.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ManagedGrafana
{
namespace Model
{
PermissionEntry::PermissionEntry() :
m_role(Role::NOT_SET),
m_roleHasBeenSet(false),
m_userHasBeenSet(false)
{
}
PermissionEntry::PermissionEntry(JsonView jsonValue) :
m_role(Role::NOT_SET),
m_roleHasBeenSet(false),
m_userHasBeenSet(false)
{
*this = jsonValue;
}
PermissionEntry& PermissionEntry::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("role"))
{
m_role = RoleMapper::GetRoleForName(jsonValue.GetString("role"));
m_roleHasBeenSet = true;
}
if(jsonValue.ValueExists("user"))
{
m_user = jsonValue.GetObject("user");
m_userHasBeenSet = true;
}
return *this;
}
JsonValue PermissionEntry::Jsonize() const
{
JsonValue payload;
if(m_roleHasBeenSet)
{
payload.WithString("role", RoleMapper::GetNameForRole(m_role));
}
if(m_userHasBeenSet)
{
payload.WithObject("user", m_user.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace ManagedGrafana
} // namespace Aws
| 17.644737 | 69 | 0.707681 | [
"model"
] |
8c31ac72bef4f867f94371662cc89024f6ee4913 | 357,356 | cpp | C++ | src/swrast/s_triangle.cpp | OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library | c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3 | [
"MIT"
] | null | null | null | src/swrast/s_triangle.cpp | OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library | c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3 | [
"MIT"
] | null | null | null | src/swrast/s_triangle.cpp | OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library | c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3 | [
"MIT"
] | null | null | null | /* $Id: s_triangle.c,v 1.65 2002/11/13 16:51:01 brianp Exp $ */
/*
* Mesa 3-D graphics library
* Version: 5.1
*
* Copyright (C) 1999-2002 Brian Paul All Rights Reserved.
*
* 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
* BRIAN PAUL 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.
*/
/*
* When the device driver doesn't implement triangle rasterization it
* can hook in _swrast_Triangle, which eventually calls one of these
* functions to draw triangles.
*/
#include "glheader.h"
#include "context.h"
#include "colormac.h"
#include "imports.h"
#include "macros.h"
#include "mmath.h"
#include "texformat.h"
#include "teximage.h"
#include "texstate.h"
#include "s_aatriangle.h"
#include "s_context.h"
#include "s_depth.h"
#include "s_feedback.h"
#include "s_span.h"
#include "s_triangle.h"
#define FIST_MAGIC ((((65536.0 * 65536.0 * 16)+(65536.0 * 0.5))* 65536.0))
/*
* Just used for feedback mode.
*/
GLboolean _mesa_cull_triangle( GLcontext *ctx,
const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
GLfloat ex = v1->win[0] - v0->win[0];
GLfloat ey = v1->win[1] - v0->win[1];
GLfloat fx = v2->win[0] - v0->win[0];
GLfloat fy = v2->win[1] - v0->win[1];
GLfloat c = ex*fy-ey*fx;
if (c * ((SWcontext *)ctx->swrast_context)->_backface_sign > 0)
return 0;
return 1;
}
/*
* Render a flat-shaded color index triangle.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void flat_ci_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = FloatToFixed(v0->win[1] - 0.5F) & snapMask;
const GLfixed fy1 = FloatToFixed(v1->win[1] - 0.5F) & snapMask;
const GLfixed fy2 = FloatToFixed(v2->win[1] - 0.5F) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
/*
* Execute user-supplied setup code
*/
span.interpMask |= 0x004; span.index = ((v2->index) << 11); span.indexStep = 0;
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_index_span(ctx, &span);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
fz += fdzOuter;
fogLeft += dfogOuter;
}
else {
fz += fdzInner;
fogLeft += dfogInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render a smooth-shaded color index triangle.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void smooth_ci_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = FloatToFixed(v0->win[1] - 0.5F) & snapMask;
const GLfixed fy1 = FloatToFixed(v1->win[1] - 0.5F) & snapMask;
const GLfixed fy2 = FloatToFixed(v2->win[1] - 0.5F) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat didx, didy;
/*
* Execute user-supplied setup code
*/
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= 0x004;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_di, eBot_di;
eMaj_di = (GLfloat) ((GLint) vMax->index - (GLint) vMin->index);
eBot_di = (GLfloat) ((GLint) vMid->index - (GLint) vMin->index);
didx = oneOverArea * (eMaj_di * eBot.dy - eMaj.dy * eBot_di);
span.indexStep = (((int) ((((didx) * 2048.0f) >= 0.0F) ? (((didx) * 2048.0f) + 0.5F) : (((didx) * 2048.0f) - 0.5F))));
didy = oneOverArea * (eMaj.dx * eBot_di - eMaj_di * eBot.dx);
}
else {
span.interpMask |= 0x200;
didx = didy = 0.0F;
span.indexStep = 0;
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fi=0, fdiOuter=0, fdiInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == 0x1D01) {
fi = (GLfixed)(vLower->index * 2048.0f
+ didx * adjx + didy * adjy) + 0x00000400;
fdiOuter = (((int) ((((didy + dxOuter * didx) * 2048.0f) >= 0.0F) ? (((didy + dxOuter * didx) * 2048.0f) + 0.5F) : (((didy + dxOuter * didx) * 2048.0f) - 0.5F))));
}
else {
fi = (GLfixed) (v2->index * 2048.0f);
fdiOuter = 0;
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdiInner = fdiOuter + span.indexStep;
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.index = fi;
if (span.index < 0) span.index = 0;
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_index_span(ctx, &span);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
fz += fdzOuter;
fogLeft += dfogOuter;
fi += fdiOuter;
}
else {
fz += fdzInner;
fogLeft += dfogInner;
fi += fdiInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render a flat-shaded RGBA triangle.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void flat_rgba_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
/*
printf("%s()\n", __FUNCTION__);
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = FloatToFixed(v0->win[1] - 0.5F) & snapMask;
const GLfixed fy1 = FloatToFixed(v1->win[1] - 0.5F) & snapMask;
const GLfixed fy2 = FloatToFixed(v2->win[1] - 0.5F) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = FloatToFixed(vMin->win[0] + 0.5F) & snapMask;
vMid_fx = FloatToFixed(vMid->win[0] + 0.5F) & snapMask;
vMax_fx = FloatToFixed(vMax->win[0] + 0.5F) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = FixedToFloat(vMax_fx - vMin_fx);
eMaj.dy = FixedToFloat(vMax_fy - vMin_fy);
eTop.dx = FixedToFloat(vMax_fx - vMid_fx);
eTop.dy = FixedToFloat(vMax_fy - vMid_fy);
eBot.dx = FixedToFloat(vMid_fx - vMin_fx);
eBot.dy = FixedToFloat(vMid_fy - vMin_fy);
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = GL_TRUE;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = FixedCeil(vMin_fy);
eMaj.lines = FixedToInt(FixedCeil(vMax_fy - eMaj.fsy));
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = SignedFloatToFixed(dxdy);
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = FixedCeil(vMid_fy);
eTop.lines = FixedToInt(FixedCeil(vMax_fy - eTop.fsy));
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = SignedFloatToFixed(dxdy);
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = FixedCeil(vMin_fy);
eBot.lines = FixedToInt(FixedCeil(vMid_fy - eBot.fsy));
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = SignedFloatToFixed(dxdy);
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
/*
* Execute user-supplied setup code
*/
span.interpMask |= 0x001;
span.red = ((v2->color[0]) << 11);
span.green = ((v2->color[1]) << 11);
span.blue = ((v2->color[2]) << 11);
span.alpha = ((v2->color[3]) << 11);
span.redStep = 0; span.greenStep = 0; span.blueStep = 0; span.alphaStep = 0;
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= SPAN_Z;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = SignedFloatToFixed(dzdx);
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= SPAN_FOG;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * FIXED_SCALE +
dzdx * adjx + dzdy * adjy) + FIXED_HALF;
if (tmp < MAX_GLUINT / 2)
fz = (GLfixed) tmp;
else
fz = MAX_GLUINT / 2;
fdzOuter = SignedFloatToFixed(dzdy + dxOuter * dzdx);
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * FixedToFloat(adjx)
+ dzdy * FixedToFloat(adjy));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (DEFAULT_SOFTWARE_DEPTH_TYPE *)
_mesa_zbuffer_address(ctx, FixedToInt(fxLeftEdge), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(DEFAULT_SOFTWARE_DEPTH_TYPE);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_rgba_span(ctx, &span);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render a smooth-shaded RGBA triangle.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void smooth_rgba_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((FIXED_ONE / (1 << SUB_PIXEL_BITS)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
/*
printf("%s()\n", __FUNCTION__);
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = FloatToFixed(v0->win[1] - 0.5F) & snapMask;
const GLfixed fy1 = FloatToFixed(v1->win[1] - 0.5F) & snapMask;
const GLfixed fy2 = FloatToFixed(v2->win[1] - 0.5F) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = FloatToFixed(vMin->win[0] + 0.5F) & snapMask;
vMid_fx = FloatToFixed(vMid->win[0] + 0.5F) & snapMask;
vMax_fx = FloatToFixed(vMax->win[0] + 0.5F) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = FixedToFloat(vMax_fx - vMin_fx);
eMaj.dy = FixedToFloat(vMax_fy - vMin_fy);
eTop.dx = FixedToFloat(vMax_fx - vMid_fx);
eTop.dy = FixedToFloat(vMax_fy - vMid_fy);
eBot.dx = FixedToFloat(vMid_fx - vMin_fx);
eBot.dy = FixedToFloat(vMid_fy - vMin_fy);
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = SignedFloatToFixed(dxdy);
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = SignedFloatToFixed(dxdy);
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = SignedFloatToFixed(dxdy);
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat drdx, drdy;
GLfloat dgdx, dgdy;
GLfloat dbdx, dbdy;
GLfloat dadx, dady;
/*
* Execute user-supplied setup code
*/
/* ..... */
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= SPAN_Z;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = SignedFloatToFixed(dzdx);
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= SPAN_FOG;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= SPAN_RGBA;
if (ctx->Light.ShadeModel == GL_SMOOTH) {
GLfloat eMaj_dr, eBot_dr;
GLfloat eMaj_dg, eBot_dg;
GLfloat eMaj_db, eBot_db;
GLfloat eMaj_da, eBot_da;
eMaj_dr = (GLfloat) ((GLint) vMax->color[RCOMP] -
(GLint) vMin->color[RCOMP]);
eBot_dr = (GLfloat) ((GLint) vMid->color[RCOMP] -
(GLint) vMin->color[RCOMP]);
drdx = oneOverArea * (eMaj_dr * eBot.dy - eMaj.dy * eBot_dr);
span.redStep = SignedFloatToFixed(drdx);
drdy = oneOverArea * (eMaj.dx * eBot_dr - eMaj_dr * eBot.dx);
eMaj_dg = (GLfloat) ((GLint) vMax->color[GCOMP] -
(GLint) vMin->color[GCOMP]);
eBot_dg = (GLfloat) ((GLint) vMid->color[GCOMP] -
(GLint) vMin->color[GCOMP]);
dgdx = oneOverArea * (eMaj_dg * eBot.dy - eMaj.dy * eBot_dg);
span.greenStep = SignedFloatToFixed(dgdx);
dgdy = oneOverArea * (eMaj.dx * eBot_dg - eMaj_dg * eBot.dx);
eMaj_db = (GLfloat) ((GLint) vMax->color[BCOMP] -
(GLint) vMin->color[BCOMP]);
eBot_db = (GLfloat) ((GLint) vMid->color[BCOMP] -
(GLint) vMin->color[BCOMP]);
dbdx = oneOverArea * (eMaj_db * eBot.dy - eMaj.dy * eBot_db);
span.blueStep = SignedFloatToFixed(dbdx);
dbdy = oneOverArea * (eMaj.dx * eBot_db - eMaj_db * eBot.dx);
eMaj_da = (GLfloat) ((GLint) vMax->color[ACOMP] -
(GLint) vMin->color[ACOMP]);
eBot_da = (GLfloat) ((GLint) vMid->color[ACOMP] -
(GLint) vMin->color[ACOMP]);
dadx = oneOverArea * (eMaj_da * eBot.dy - eMaj.dy * eBot_da);
span.alphaStep = SignedFloatToFixed(dadx);
dady = oneOverArea * (eMaj.dx * eBot_da - eMaj_da * eBot.dx);
}
else {
span.interpMask |= SPAN_FLAT;
drdx = drdy = 0.0F;
dgdx = dgdy = 0.0F;
dbdx = dbdy = 0.0F;
span.redStep = 0;
span.greenStep = 0;
span.blueStep = 0;
dadx = dady = 0.0F;
span.alphaStep = 0;
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fr = 0, fdrOuter = 0, fdrInner;
GLfixed fg = 0, fdgOuter = 0, fdgInner;
GLfixed fb = 0, fdbOuter = 0, fdbInner;
GLfixed fa = 0, fdaOuter = 0, fdaInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < MAX_GLUINT / 2)
fz = (GLfixed) tmp;
else
fz = MAX_GLUINT / 2;
fdzOuter = SignedFloatToFixed(dzdy + dxOuter * dzdx);
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * FixedToFloat(adjx)
+ dzdy * FixedToFloat(adjy));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == GL_SMOOTH) {
fr = (GLfixed) (ChanToFixed(vLower->color[RCOMP])
+ drdx * adjx + drdy * adjy) + FIXED_HALF;
fdrOuter = SignedFloatToFixed(drdy + dxOuter * drdx);
fg = (GLfixed) (ChanToFixed(vLower->color[GCOMP])
+ dgdx * adjx + dgdy * adjy) + FIXED_HALF;
fdgOuter = SignedFloatToFixed(dgdy + dxOuter * dgdx);
fb = (GLfixed) (ChanToFixed(vLower->color[BCOMP])
+ dbdx * adjx + dbdy * adjy) + FIXED_HALF;
fdbOuter = SignedFloatToFixed(dbdy + dxOuter * dbdx);
fa = (GLfixed) (ChanToFixed(vLower->color[ACOMP])
+ dadx * adjx + dady * adjy) + FIXED_HALF;
fdaOuter = SignedFloatToFixed(dady + dxOuter * dadx);
}
else {
fr = ChanToFixed(v2->color[RCOMP]);
fg = ChanToFixed(v2->color[GCOMP]);
fdrOuter = fdgOuter = fdbOuter = 0;
fa = ChanToFixed(v2->color[ACOMP]);
fdaOuter = 0;
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdrInner = fdrOuter + span.redStep;
fdgInner = fdgOuter + span.greenStep;
fdbInner = fdbOuter + span.blueStep;
fdaInner = fdaOuter + span.alphaStep;
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.red = fr;
span.green = fg;
span.blue = fb;
span.alpha = fa;
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffrend = span.red + len * span.redStep;
GLfixed ffgend = span.green + len * span.greenStep;
GLfixed ffbend = span.blue + len * span.blueStep;
if (ffrend < 0) {
span.red -= ffrend;
if (span.red < 0)
span.red = 0;
}
if (ffgend < 0) {
span.green -= ffgend;
if (span.green < 0)
span.green = 0;
}
if (ffbend < 0) {
span.blue -= ffbend;
if (span.blue < 0)
span.blue = 0;
}
}
{
const GLint len = right - span.x - 1;
GLfixed ffaend = span.alpha + len * span.alphaStep;
if (ffaend < 0) {
span.alpha -= ffaend;
if (span.alpha < 0)
span.alpha = 0;
}
}
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_rgba_span(ctx, &span);
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
fr += fdrOuter;
fg += fdgOuter;
fb += fdbOuter;
fa += fdaOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
fr += fdrInner;
fg += fdgInner;
fb += fdbInner;
fa += fdaInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render an RGB, GL_DECAL, textured triangle.
* Interpolate S,T only w/out mipmapping or perspective correction.
*
* No fog.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void simple_textured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
do { (span).primitive = (0x0009); (span).interpMask = (0); (span).arrayMask = (0); (span).start = 0; (span).end = (0); (span).facing = 0; (span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays; } while (0);
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dsdx, dsdy;
GLfloat dtdx, dtdy;
/*
* Execute user-supplied setup code
*/
SWcontext *swrast = ((SWcontext *)ctx->swrast_context); struct gl_texture_object *obj = ctx->Texture.Unit[0].Current2D; const GLint b = obj->BaseLevel; const GLfloat twidth = (GLfloat) obj->Image[b]->Width; const GLfloat theight = (GLfloat) obj->Image[b]->Height; const GLint twidth_log2 = obj->Image[b]->WidthLog2; const GLchan *texture = (const GLchan *) obj->Image[b]->Data; const GLint smask = obj->Image[b]->Width - 1; const GLint tmask = obj->Image[b]->Height - 1; if (!texture) { return; }
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x040;
{
GLfloat eMaj_ds, eBot_ds;
eMaj_ds = (vMax->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
eBot_ds = (vMid->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
dsdx = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
span.intTexStep[0] = (((int) ((((dsdx) * 2048.0f) >= 0.0F) ? (((dsdx) * 2048.0f) + 0.5F) : (((dsdx) * 2048.0f) - 0.5F))));
dsdy = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
}
{
GLfloat eMaj_dt, eBot_dt;
eMaj_dt = (vMax->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
eBot_dt = (vMid->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
dtdx = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
span.intTexStep[1] = (((int) ((((dtdx) * 2048.0f) >= 0.0F) ? (((dtdx) * 2048.0f) + 0.5F) : (((dtdx) * 2048.0f) - 0.5F))));
dtdy = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLfixed fs=0, fdsOuter=0, fdsInner;
GLfixed ft=0, fdtOuter=0, fdtInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat s0, t0;
s0 = vLower->texcoord[0][0] * twidth;
fs = (GLfixed)(s0 * 2048.0f + dsdx * adjx
+ dsdy * adjy) + 0x00000400;
fdsOuter = (((int) ((((dsdy + dxOuter * dsdx) * 2048.0f) >= 0.0F) ? (((dsdy + dxOuter * dsdx) * 2048.0f) + 0.5F) : (((dsdy + dxOuter * dsdx) * 2048.0f) - 0.5F))));
t0 = vLower->texcoord[0][1] * theight;
ft = (GLfixed)(t0 * 2048.0f + dtdx * adjx
+ dtdy * adjy) + 0x00000400;
fdtOuter = (((int) ((((dtdy + dxOuter * dtdx) * 2048.0f) >= 0.0F) ? (((dtdy + dxOuter * dtdx) * 2048.0f) + 0.5F) : (((dtdy + dxOuter * dtdx) * 2048.0f) - 0.5F))));
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
fdsInner = fdsOuter + span.intTexStep[0];
fdtInner = fdtOuter + span.intTexStep[1];
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.intTex[0] = fs;
span.intTex[1] = ft;
/* This is where we actually generate fragments */
if (span.end > 0) {
GLuint i; span.intTex[0] -= 0x00000400; span.intTex[1] -= 0x00000400; for (i = 0; i < span.end; i++) { GLint s = ((span.intTex[0]) >> 11) & smask; GLint t = ((span.intTex[1]) >> 11) & tmask; GLint pos = (t << twidth_log2) + s; pos = pos + pos + pos; span.array->rgb[i][0] = texture[pos]; span.array->rgb[i][1] = texture[pos+1]; span.array->rgb[i][2] = texture[pos+2]; span.intTex[0] += span.intTexStep[0]; span.intTex[1] += span.intTexStep[1]; } (*swrast->Driver.WriteRGBSpan)(ctx, span.end, span.x, span.y, (const GLchan (*)[3]) span.array->rgb, 0 );;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
fs += fdsOuter;
ft += fdtOuter;
}
else {
fs += fdsInner;
ft += fdtInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render an RGB, GL_DECAL, textured triangle.
* Interpolate S,T, GL_LESS depth test, w/out mipmapping or
* perspective correction.
*
* No fog.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void simple_z_textured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLint fixedToDepthShift = depthBits <= 16 ? FIXED_SHIFT : 0;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
do { (span).primitive = (0x0009); (span).interpMask = (0); (span).arrayMask = (0); (span).start = 0; (span).end = (0); (span).facing = 0; (span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays; } while (0);
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dsdx, dsdy;
GLfloat dtdx, dtdy;
/*
* Execute user-supplied setup code
*/
SWcontext *swrast = ((SWcontext *)ctx->swrast_context); struct gl_texture_object *obj = ctx->Texture.Unit[0].Current2D; const GLint b = obj->BaseLevel; const GLfloat twidth = (GLfloat) obj->Image[b]->Width; const GLfloat theight = (GLfloat) obj->Image[b]->Height; const GLint twidth_log2 = obj->Image[b]->WidthLog2; const GLchan *texture = (const GLchan *) obj->Image[b]->Data; const GLint smask = obj->Image[b]->Width - 1; const GLint tmask = obj->Image[b]->Height - 1; if (!texture) { return; }
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x040;
{
GLfloat eMaj_ds, eBot_ds;
eMaj_ds = (vMax->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
eBot_ds = (vMid->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
dsdx = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
span.intTexStep[0] = (((int) ((((dsdx) * 2048.0f) >= 0.0F) ? (((dsdx) * 2048.0f) + 0.5F) : (((dsdx) * 2048.0f) - 0.5F))));
dsdy = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
}
{
GLfloat eMaj_dt, eBot_dt;
eMaj_dt = (vMax->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
eBot_dt = (vMid->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
dtdx = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
span.intTexStep[1] = (((int) ((((dtdx) * 2048.0f) >= 0.0F) ? (((dtdx) * 2048.0f) + 0.5F) : (((dtdx) * 2048.0f) - 0.5F))));
dtdy = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfixed fs=0, fdsOuter=0, fdsInner;
GLfixed ft=0, fdtOuter=0, fdtInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
{
GLfloat s0, t0;
s0 = vLower->texcoord[0][0] * twidth;
fs = (GLfixed)(s0 * 2048.0f + dsdx * adjx
+ dsdy * adjy) + 0x00000400;
fdsOuter = (((int) ((((dsdy + dxOuter * dsdx) * 2048.0f) >= 0.0F) ? (((dsdy + dxOuter * dsdx) * 2048.0f) + 0.5F) : (((dsdy + dxOuter * dsdx) * 2048.0f) - 0.5F))));
t0 = vLower->texcoord[0][1] * theight;
ft = (GLfixed)(t0 * 2048.0f + dtdx * adjx
+ dtdy * adjy) + 0x00000400;
fdtOuter = (((int) ((((dtdy + dxOuter * dtdx) * 2048.0f) >= 0.0F) ? (((dtdy + dxOuter * dtdx) * 2048.0f) + 0.5F) : (((dtdy + dxOuter * dtdx) * 2048.0f) - 0.5F))));
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
fdsInner = fdsOuter + span.intTexStep[0];
fdtInner = fdtOuter + span.intTexStep[1];
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.intTex[0] = fs;
span.intTex[1] = ft;
/* This is where we actually generate fragments */
if (span.end > 0) {
GLuint i; span.intTex[0] -= 0x00000400; span.intTex[1] -= 0x00000400; for (i = 0; i < span.end; i++) { const GLdepth z = ((span.z) >> fixedToDepthShift); if (z < zRow[i]) { GLint s = ((span.intTex[0]) >> 11) & smask; GLint t = ((span.intTex[1]) >> 11) & tmask; GLint pos = (t << twidth_log2) + s; pos = pos + pos + pos; span.array->rgb[i][0] = texture[pos]; span.array->rgb[i][1] = texture[pos+1]; span.array->rgb[i][2] = texture[pos+2]; zRow[i] = z; span.array->mask[i] = 1; } else { span.array->mask[i] = 0; } span.intTex[0] += span.intTexStep[0]; span.intTex[1] += span.intTexStep[1]; span.z += span.zStep; } (*swrast->Driver.WriteRGBSpan)(ctx, span.end, span.x, span.y, (const GLchan (*)[3]) span.array->rgb, span.array->mask );;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fs += fdsOuter;
ft += fdtOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fs += fdsInner;
ft += fdtInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
struct affine_info
{
GLenum filter;
GLenum format;
GLenum envmode;
GLint smask, tmask;
GLint twidth_log2;
const GLchan *texture;
GLfixed er, eg, eb, ea;
GLint tbytesline, tsize;
};
/* This function can handle GL_NEAREST or GL_LINEAR sampling of 2D RGB or RGBA
* textures with GL_REPLACE, GL_MODULATE, GL_BLEND, GL_DECAL or GL_ADD
* texture env modes.
*/
static inline void
affine_span(GLcontext *ctx, struct sw_span *span,
struct affine_info *info)
{
GLchan sample[4]; /* the filtered texture sample */
/* Instead of defining a function for each mode, a test is done
* between the outer and inner loops. This is to reduce code size
* and complexity. Observe that an optimizing compiler kills
* unused variables (for instance tf,sf,ti,si in case of GL_NEAREST).
*/
/* shortcuts */
GLuint i;
GLchan *dest = span->array->rgba[0];
span->intTex[0] -= 0x00000400;
span->intTex[1] -= 0x00000400;
switch (info->filter) {
case 0x2600:
switch (info->format) {
case 0x1907:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x2101:
case 0x1E01:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255; dest[0] = sample[0]; dest[1] = sample[1]; dest[2] = sample[2]; dest[3] = ((span->alpha) >> 11);; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode in SPAN_LINEAR");
return;
}
break;
case 0x1908:
switch(info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x2101:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = ((255 - sample[3]) * span->red + ((sample[3] + 1) * sample[0] << 11)) >> (11 + 8); dest[1] = ((255 - sample[3]) * span->green + ((sample[3] + 1) * sample[1] << 11)) >> (11 + 8); dest[2] = ((255 - sample[3]) * span->blue + ((sample[3] + 1) * sample[2] << 11)) >> (11 + 8); dest[3] = ((span->alpha) >> 11); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x1E01:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (dest)[0] = (tex00)[0]; (dest)[1] = (tex00)[1]; (dest)[2] = (tex00)[2]; (dest)[3] = (tex00)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (2) in SPAN_LINEAR");
return;
}
break;
}
break;
case 0x2601:
span->intTex[0] -= 0x00000400;
span->intTex[1] -= 0x00000400;
switch (info->format) {
case 0x1907:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x2101:
case 0x1E01:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;{ (dest)[0] = (sample)[0]; (dest)[1] = (sample)[1]; (dest)[2] = (sample)[2]; (dest)[3] = (sample)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (3) in SPAN_LINEAR");
return;
}
break;
case 0x1908:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x2101:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = ((255 - sample[3]) * span->red + ((sample[3] + 1) * sample[0] << 11)) >> (11 + 8); dest[1] = ((255 - sample[3]) * span->green + ((sample[3] + 1) * sample[1] << 11)) >> (11 + 8); dest[2] = ((255 - sample[3]) * span->blue + ((sample[3] + 1) * sample[2] << 11)) >> (11 + 8); dest[3] = ((span->alpha) >> 11); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
case 0x1E01:
for (i = 0; i < span->end; i++) { GLint s = ((span->intTex[0]) >> 11) & info->smask; GLint t = ((span->intTex[1]) >> 11) & info->tmask; GLfixed sf = span->intTex[0] & 0x000007FF; GLfixed tf = span->intTex[1] & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;{ (dest)[0] = (sample)[0]; (dest)[1] = (sample)[1]; (dest)[2] = (sample)[2]; (dest)[3] = (sample)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; span->intTex[0] += span->intTexStep[0]; span->intTex[1] += span->intTexStep[1]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (4) in SPAN_LINEAR");
return;
}
break;
}
break;
}
span->interpMask &= ~0x001;
;
_mesa_write_rgba_span(ctx, span);
}
/*
* Render an RGB/RGBA textured triangle without perspective correction.
*/
/* $Id: s_tritemp.h,v 1.41 2002/11/13 16:51:02 brianp Exp $ */
/*
* Mesa 3-D graphics library
* Version: 5.1
*
* Copyright (C) 1999-2002 Brian Paul All Rights Reserved.
*
* 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
* BRIAN PAUL 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.
*/
/* $XFree86: xc/extras/Mesa/src/swrast/s_tritemp.h,v 1.2 2002/02/27 21:07:54 tsi Exp $ */
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void affine_textured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
do { (span).primitive = (0x0009); (span).interpMask = (0); (span).arrayMask = (0); (span).start = 0; (span).end = (0); (span).facing = 0; (span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays; } while (0);
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat drdx, drdy;
GLfloat dgdx, dgdy;
GLfloat dbdx, dbdy;
GLfloat dadx, dady;
GLfloat dsdx, dsdy;
GLfloat dtdx, dtdy;
/*
* Execute user-supplied setup code
*/
struct affine_info info; struct gl_texture_unit *unit = ctx->Texture.Unit+0; struct gl_texture_object *obj = unit->Current2D; const GLint b = obj->BaseLevel; const GLfloat twidth = (GLfloat) obj->Image[b]->Width; const GLfloat theight = (GLfloat) obj->Image[b]->Height; info.texture = (const GLchan *) obj->Image[b]->Data; info.twidth_log2 = obj->Image[b]->WidthLog2; info.smask = obj->Image[b]->Width - 1; info.tmask = obj->Image[b]->Height - 1; info.format = obj->Image[b]->Format; info.filter = obj->MinFilter; info.envmode = unit->EnvMode; span.arrayMask |= 0x001; if (info.envmode == 0x0BE2) { info.er = (((int) ((((unit->EnvColor[0] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[0] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[0] * 255.0F) * 2048.0f) - 0.5F)))); info.eg = (((int) ((((unit->EnvColor[1] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[1] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[1] * 255.0F) * 2048.0f) - 0.5F)))); info.eb = (((int) ((((unit->EnvColor[2] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[2] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[2] * 255.0F) * 2048.0f) - 0.5F)))); info.ea = (((int) ((((unit->EnvColor[3] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[3] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[3] * 255.0F) * 2048.0f) - 0.5F)))); } if (!info.texture) { return; } switch (info.format) { case 0x1906: case 0x1909: case 0x8049: info.tbytesline = obj->Image[b]->Width; break; case 0x190A: info.tbytesline = obj->Image[b]->Width * 2; break; case 0x1907: info.tbytesline = obj->Image[b]->Width * 3; break; case 0x1908: info.tbytesline = obj->Image[b]->Width * 4; break; default: _mesa_problem(0, "Bad texture format in affine_texture_triangle"); return; } info.tsize = obj->Image[b]->Height * info.tbytesline;
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= 0x001;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dr, eBot_dr;
GLfloat eMaj_dg, eBot_dg;
GLfloat eMaj_db, eBot_db;
GLfloat eMaj_da, eBot_da;
eMaj_dr = (GLfloat) ((GLint) vMax->color[0] -
(GLint) vMin->color[0]);
eBot_dr = (GLfloat) ((GLint) vMid->color[0] -
(GLint) vMin->color[0]);
drdx = oneOverArea * (eMaj_dr * eBot.dy - eMaj.dy * eBot_dr);
span.redStep = (((int) ((((drdx) * 2048.0f) >= 0.0F) ? (((drdx) * 2048.0f) + 0.5F) : (((drdx) * 2048.0f) - 0.5F))));
drdy = oneOverArea * (eMaj.dx * eBot_dr - eMaj_dr * eBot.dx);
eMaj_dg = (GLfloat) ((GLint) vMax->color[1] -
(GLint) vMin->color[1]);
eBot_dg = (GLfloat) ((GLint) vMid->color[1] -
(GLint) vMin->color[1]);
dgdx = oneOverArea * (eMaj_dg * eBot.dy - eMaj.dy * eBot_dg);
span.greenStep = (((int) ((((dgdx) * 2048.0f) >= 0.0F) ? (((dgdx) * 2048.0f) + 0.5F) : (((dgdx) * 2048.0f) - 0.5F))));
dgdy = oneOverArea * (eMaj.dx * eBot_dg - eMaj_dg * eBot.dx);
eMaj_db = (GLfloat) ((GLint) vMax->color[2] -
(GLint) vMin->color[2]);
eBot_db = (GLfloat) ((GLint) vMid->color[2] -
(GLint) vMin->color[2]);
dbdx = oneOverArea * (eMaj_db * eBot.dy - eMaj.dy * eBot_db);
span.blueStep = (((int) ((((dbdx) * 2048.0f) >= 0.0F) ? (((dbdx) * 2048.0f) + 0.5F) : (((dbdx) * 2048.0f) - 0.5F))));
dbdy = oneOverArea * (eMaj.dx * eBot_db - eMaj_db * eBot.dx);
eMaj_da = (GLfloat) ((GLint) vMax->color[3] -
(GLint) vMin->color[3]);
eBot_da = (GLfloat) ((GLint) vMid->color[3] -
(GLint) vMin->color[3]);
dadx = oneOverArea * (eMaj_da * eBot.dy - eMaj.dy * eBot_da);
span.alphaStep = (((int) ((((dadx) * 2048.0f) >= 0.0F) ? (((dadx) * 2048.0f) + 0.5F) : (((dadx) * 2048.0f) - 0.5F))));
dady = oneOverArea * (eMaj.dx * eBot_da - eMaj_da * eBot.dx);
}
else {
;
span.interpMask |= 0x200;
drdx = drdy = 0.0F;
dgdx = dgdy = 0.0F;
dbdx = dbdy = 0.0F;
span.redStep = 0;
span.greenStep = 0;
span.blueStep = 0;
dadx = dady = 0.0F;
span.alphaStep = 0;
}
span.interpMask |= 0x040;
{
GLfloat eMaj_ds, eBot_ds;
eMaj_ds = (vMax->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
eBot_ds = (vMid->texcoord[0][0] - vMin->texcoord[0][0]) * twidth;
dsdx = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
span.intTexStep[0] = (((int) ((((dsdx) * 2048.0f) >= 0.0F) ? (((dsdx) * 2048.0f) + 0.5F) : (((dsdx) * 2048.0f) - 0.5F))));
dsdy = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
}
{
GLfloat eMaj_dt, eBot_dt;
eMaj_dt = (vMax->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
eBot_dt = (vMid->texcoord[0][1] - vMin->texcoord[0][1]) * theight;
dtdx = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
span.intTexStep[1] = (((int) ((((dtdx) * 2048.0f) >= 0.0F) ? (((dtdx) * 2048.0f) + 0.5F) : (((dtdx) * 2048.0f) - 0.5F))));
dtdy = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fr = 0, fdrOuter = 0, fdrInner;
GLfixed fg = 0, fdgOuter = 0, fdgInner;
GLfixed fb = 0, fdbOuter = 0, fdbInner;
GLfixed fa = 0, fdaOuter = 0, fdaInner;
GLfixed fs=0, fdsOuter=0, fdsInner;
GLfixed ft=0, fdtOuter=0, fdtInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == 0x1D01) {
fr = (GLfixed) (((vLower->color[0]) << 11)
+ drdx * adjx + drdy * adjy) + 0x00000400;
fdrOuter = (((int) ((((drdy + dxOuter * drdx) * 2048.0f) >= 0.0F) ? (((drdy + dxOuter * drdx) * 2048.0f) + 0.5F) : (((drdy + dxOuter * drdx) * 2048.0f) - 0.5F))));
fg = (GLfixed) (((vLower->color[1]) << 11)
+ dgdx * adjx + dgdy * adjy) + 0x00000400;
fdgOuter = (((int) ((((dgdy + dxOuter * dgdx) * 2048.0f) >= 0.0F) ? (((dgdy + dxOuter * dgdx) * 2048.0f) + 0.5F) : (((dgdy + dxOuter * dgdx) * 2048.0f) - 0.5F))));
fb = (GLfixed) (((vLower->color[2]) << 11)
+ dbdx * adjx + dbdy * adjy) + 0x00000400;
fdbOuter = (((int) ((((dbdy + dxOuter * dbdx) * 2048.0f) >= 0.0F) ? (((dbdy + dxOuter * dbdx) * 2048.0f) + 0.5F) : (((dbdy + dxOuter * dbdx) * 2048.0f) - 0.5F))));
fa = (GLfixed) (((vLower->color[3]) << 11)
+ dadx * adjx + dady * adjy) + 0x00000400;
fdaOuter = (((int) ((((dady + dxOuter * dadx) * 2048.0f) >= 0.0F) ? (((dady + dxOuter * dadx) * 2048.0f) + 0.5F) : (((dady + dxOuter * dadx) * 2048.0f) - 0.5F))));
}
else {
;
fr = ((v2->color[0]) << 11);
fg = ((v2->color[1]) << 11);
fb = ((v2->color[2]) << 11);
fdrOuter = fdgOuter = fdbOuter = 0;
fa = ((v2->color[3]) << 11);
fdaOuter = 0;
}
{
GLfloat s0, t0;
s0 = vLower->texcoord[0][0] * twidth;
fs = (GLfixed)(s0 * 2048.0f + dsdx * adjx
+ dsdy * adjy) + 0x00000400;
fdsOuter = (((int) ((((dsdy + dxOuter * dsdx) * 2048.0f) >= 0.0F) ? (((dsdy + dxOuter * dsdx) * 2048.0f) + 0.5F) : (((dsdy + dxOuter * dsdx) * 2048.0f) - 0.5F))));
t0 = vLower->texcoord[0][1] * theight;
ft = (GLfixed)(t0 * 2048.0f + dtdx * adjx
+ dtdy * adjy) + 0x00000400;
fdtOuter = (((int) ((((dtdy + dxOuter * dtdx) * 2048.0f) >= 0.0F) ? (((dtdy + dxOuter * dtdx) * 2048.0f) + 0.5F) : (((dtdy + dxOuter * dtdx) * 2048.0f) - 0.5F))));
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdrInner = fdrOuter + span.redStep;
fdgInner = fdgOuter + span.greenStep;
fdbInner = fdbOuter + span.blueStep;
fdaInner = fdaOuter + span.alphaStep;
fdsInner = fdsOuter + span.intTexStep[0];
fdtInner = fdtOuter + span.intTexStep[1];
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.red = fr;
span.green = fg;
span.blue = fb;
span.alpha = fa;
span.intTex[0] = fs;
span.intTex[1] = ft;
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffrend = span.red + len * span.redStep;
GLfixed ffgend = span.green + len * span.greenStep;
GLfixed ffbend = span.blue + len * span.blueStep;
if (ffrend < 0) {
span.red -= ffrend;
if (span.red < 0)
span.red = 0;
}
if (ffgend < 0) {
span.green -= ffgend;
if (span.green < 0)
span.green = 0;
}
if (ffbend < 0) {
span.blue -= ffbend;
if (span.blue < 0)
span.blue = 0;
}
}
{
const GLint len = right - span.x - 1;
GLfixed ffaend = span.alpha + len * span.alphaStep;
if (ffaend < 0) {
span.alpha -= ffaend;
if (span.alpha < 0)
span.alpha = 0;
}
}
/* This is where we actually generate fragments */
if (span.end > 0) {
affine_span(ctx, &span, &info);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
fr += fdrOuter;
fg += fdgOuter;
fb += fdbOuter;
fa += fdaOuter;
fs += fdsOuter;
ft += fdtOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
fr += fdrInner;
fg += fdgInner;
fb += fdbInner;
fa += fdaInner;
fs += fdsInner;
ft += fdtInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
struct persp_info
{
GLenum filter;
GLenum format;
GLenum envmode;
GLint smask, tmask;
GLint twidth_log2;
const GLchan *texture;
GLfixed er, eg, eb, ea; /* texture env color */
GLint tbytesline, tsize;
};
static inline void
fast_persp_span(GLcontext *ctx, struct sw_span *span,
struct persp_info *info)
{
GLchan sample[4]; /* the filtered texture sample */
/* Instead of defining a function for each mode, a test is done
* between the outer and inner loops. This is to reduce code size
* and complexity. Observe that an optimizing compiler kills
* unused variables (for instance tf,sf,ti,si in case of GL_NEAREST).
*/
GLuint i;
GLfloat tex_coord[3], tex_step[3];
GLchan *dest = span->array->rgba[0];
tex_coord[0] = span->tex[0][0] * (info->smask + 1);
tex_step[0] = span->texStepX[0][0] * (info->smask + 1);
tex_coord[1] = span->tex[0][1] * (info->tmask + 1);
tex_step[1] = span->texStepX[0][1] * (info->tmask + 1);
/* span->tex[0][2] only if 3D-texturing, here only 2D */
tex_coord[2] = span->tex[0][3];
tex_step[2] = span->texStepX[0][3];
switch (info->filter) {
case 0x2600:
switch (info->format) {
case 0x1907:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x2101:
case 0x1E01:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255; dest[0] = sample[0]; dest[1] = sample[1]; dest[2] = sample[2]; dest[3] = ((span->alpha) >> 11);; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; sample[0] = tex00[0]; sample[1] = tex00[1]; sample[2] = tex00[2]; sample[3] = 255;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (5) in SPAN_LINEAR");
return;
}
break;
case 0x1908:
switch(info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x2101:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = ((255 - sample[3]) * span->red + ((sample[3] + 1) * sample[0] << 11)) >> (11 + 8); dest[1] = ((255 - sample[3]) * span->green + ((sample[3] + 1) * sample[1] << 11)) >> (11 + 8); dest[2] = ((255 - sample[3]) * span->blue + ((sample[3] + 1) * sample[2] << 11)) >> (11 + 8); dest[3] = ((span->alpha) >> 11); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (sample)[0] = (tex00)[0]; (sample)[1] = (tex00)[1]; (sample)[2] = (tex00)[2]; (sample)[3] = (tex00)[3]; };{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x1E01:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLint s = ifloor(s_tmp) & info->smask; GLint t = ifloor(t_tmp) & info->tmask; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; { (dest)[0] = (tex00)[0]; (dest)[1] = (tex00)[1]; (dest)[2] = (tex00)[2]; (dest)[3] = (tex00)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (6) in SPAN_LINEAR");
return;
}
break;
}
break;
case 0x2601:
switch (info->format) {
case 0x1907:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x2101:
case 0x1E01:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;{ (dest)[0] = (sample)[0]; (dest)[1] = (sample)[1]; (dest)[2] = (sample)[2]; (dest)[3] = (sample)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 3 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 3; const GLchan *tex11 = tex10 + 3; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = 255;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (7) in SPAN_LINEAR");
return;
}
break;
case 0x1908:
switch (info->envmode) {
case 0x2100:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = span->red * (sample[0] + 1u) >> (11 + 8); dest[1] = span->green * (sample[1] + 1u) >> (11 + 8); dest[2] = span->blue * (sample[2] + 1u) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1u) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x2101:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = ((255 - sample[3]) * span->red + ((sample[3] + 1) * sample[0] << 11)) >> (11 + 8); dest[1] = ((255 - sample[3]) * span->green + ((sample[3] + 1) * sample[1] << 11)) >> (11 + 8); dest[2] = ((255 - sample[3]) * span->blue + ((sample[3] + 1) * sample[2] << 11)) >> (11 + 8); dest[3] = ((span->alpha) >> 11); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0BE2:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;dest[0] = ((255 - sample[0]) * span->red + (sample[0] + 1) * info->er) >> (11 + 8); dest[1] = ((255 - sample[1]) * span->green + (sample[1] + 1) * info->eg) >> (11 + 8); dest[2] = ((255 - sample[2]) * span->blue + (sample[2] + 1) * info->eb) >> (11 + 8); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x0104:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;{ GLint rSum = ((span->red) >> 11) + (GLint) sample[0]; GLint gSum = ((span->green) >> 11) + (GLint) sample[1]; GLint bSum = ((span->blue) >> 11) + (GLint) sample[2]; dest[0] = ( (rSum)<(255) ? (rSum) : (255) ); dest[1] = ( (gSum)<(255) ? (gSum) : (255) ); dest[2] = ( (bSum)<(255) ? (bSum) : (255) ); dest[3] = span->alpha * (sample[3] + 1) >> (11 + 8); }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
case 0x1E01:
for (i = 0; i < span->end; i++) { GLdouble invQ = tex_coord[2] ? (1.0 / tex_coord[2]) : 1.0; GLfloat s_tmp = (GLfloat) (tex_coord[0] * invQ); GLfloat t_tmp = (GLfloat) (tex_coord[1] * invQ); GLfixed s_fix = (((int) ((((s_tmp) * 2048.0f) >= 0.0F) ? (((s_tmp) * 2048.0f) + 0.5F) : (((s_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLfixed t_fix = (((int) ((((t_tmp) * 2048.0f) >= 0.0F) ? (((t_tmp) * 2048.0f) + 0.5F) : (((t_tmp) * 2048.0f) - 0.5F)))) - 0x00000400; GLint s = ((((s_fix) & (~0x000007FF))) >> 11) & info->smask; GLint t = ((((t_fix) & (~0x000007FF))) >> 11) & info->tmask; GLfixed sf = s_fix & 0x000007FF; GLfixed tf = t_fix & 0x000007FF; GLfixed si = 0x000007FF - sf; GLfixed ti = 0x000007FF - tf; GLint pos = (t << info->twidth_log2) + s; const GLchan *tex00 = info->texture + 4 * pos; const GLchan *tex10 = tex00 + info->tbytesline; const GLchan *tex01 = tex00 + 4; const GLchan *tex11 = tex10 + 4; (void) ti; (void) si; if (t == info->tmask) { tex10 -= info->tsize; tex11 -= info->tsize; } if (s == info->smask) { tex01 -= info->tbytesline; tex11 -= info->tbytesline; } sample[0] = (ti * (si * tex00[0] + sf * tex01[0]) + tf * (si * tex10[0] + sf * tex11[0])) >> 2 * 11; sample[1] = (ti * (si * tex00[1] + sf * tex01[1]) + tf * (si * tex10[1] + sf * tex11[1])) >> 2 * 11; sample[2] = (ti * (si * tex00[2] + sf * tex01[2]) + tf * (si * tex10[2] + sf * tex11[2])) >> 2 * 11; sample[3] = (ti * (si * tex00[3] + sf * tex01[3]) + tf * (si * tex10[3] + sf * tex11[3])) >> 2 * 11;{ (dest)[0] = (sample)[0]; (dest)[1] = (sample)[1]; (dest)[2] = (sample)[2]; (dest)[3] = (sample)[3]; }; span->red += span->redStep; span->green += span->greenStep; span->blue += span->blueStep; span->alpha += span->alphaStep; tex_coord[0] += tex_step[0]; tex_coord[1] += tex_step[1]; tex_coord[2] += tex_step[2]; dest += 4; };
break;
default:
_mesa_problem(ctx, "bad tex env mode (8) in SPAN_LINEAR");
return;
}
break;
}
break;
}
;
_mesa_write_rgba_span(ctx, span);
}
/*
* Render an perspective corrected RGB/RGBA textured triangle.
* The Q (aka V in Mesa) coordinate must be zero such that the divide
* by interpolated Q/W comes out right.
*
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void persp_textured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
/*
printf("%s()\n", __FUNCTION__);
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat drdx, drdy;
GLfloat dgdx, dgdy;
GLfloat dbdx, dbdy;
GLfloat dadx, dady;
GLfloat dsdx, dsdy;
GLfloat dtdx, dtdy;
GLfloat dudx, dudy;
GLfloat dvdx, dvdy;
/*
* Execute user-supplied setup code
*/
struct persp_info info; const struct gl_texture_unit *unit = ctx->Texture.Unit+0; const struct gl_texture_object *obj = unit->Current2D; const GLint b = obj->BaseLevel; info.texture = (const GLchan *) obj->Image[b]->Data; info.twidth_log2 = obj->Image[b]->WidthLog2; info.smask = obj->Image[b]->Width - 1; info.tmask = obj->Image[b]->Height - 1; info.format = obj->Image[b]->Format; info.filter = obj->MinFilter; info.envmode = unit->EnvMode; if (info.envmode == 0x0BE2) { info.er = (((int) ((((unit->EnvColor[0] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[0] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[0] * 255.0F) * 2048.0f) - 0.5F)))); info.eg = (((int) ((((unit->EnvColor[1] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[1] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[1] * 255.0F) * 2048.0f) - 0.5F)))); info.eb = (((int) ((((unit->EnvColor[2] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[2] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[2] * 255.0F) * 2048.0f) - 0.5F)))); info.ea = (((int) ((((unit->EnvColor[3] * 255.0F) * 2048.0f) >= 0.0F) ? (((unit->EnvColor[3] * 255.0F) * 2048.0f) + 0.5F) : (((unit->EnvColor[3] * 255.0F) * 2048.0f) - 0.5F)))); } if (!info.texture) { return; } switch (info.format) { case 0x1906: case 0x1909: case 0x8049: info.tbytesline = obj->Image[b]->Width; break; case 0x190A: info.tbytesline = obj->Image[b]->Width * 2; break; case 0x1907: info.tbytesline = obj->Image[b]->Width * 3; break; case 0x1908: info.tbytesline = obj->Image[b]->Width * 4; break; default: _mesa_problem(0, "Bad texture format in persp_textured_triangle"); return; } info.tsize = obj->Image[b]->Height * info.tbytesline;
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= 0x001;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dr, eBot_dr;
GLfloat eMaj_dg, eBot_dg;
GLfloat eMaj_db, eBot_db;
GLfloat eMaj_da, eBot_da;
eMaj_dr = (GLfloat) ((GLint) vMax->color[0] -
(GLint) vMin->color[0]);
eBot_dr = (GLfloat) ((GLint) vMid->color[0] -
(GLint) vMin->color[0]);
drdx = oneOverArea * (eMaj_dr * eBot.dy - eMaj.dy * eBot_dr);
span.redStep = (((int) ((((drdx) * 2048.0f) >= 0.0F) ? (((drdx) * 2048.0f) + 0.5F) : (((drdx) * 2048.0f) - 0.5F))));
drdy = oneOverArea * (eMaj.dx * eBot_dr - eMaj_dr * eBot.dx);
eMaj_dg = (GLfloat) ((GLint) vMax->color[1] -
(GLint) vMin->color[1]);
eBot_dg = (GLfloat) ((GLint) vMid->color[1] -
(GLint) vMin->color[1]);
dgdx = oneOverArea * (eMaj_dg * eBot.dy - eMaj.dy * eBot_dg);
span.greenStep = (((int) ((((dgdx) * 2048.0f) >= 0.0F) ? (((dgdx) * 2048.0f) + 0.5F) : (((dgdx) * 2048.0f) - 0.5F))));
dgdy = oneOverArea * (eMaj.dx * eBot_dg - eMaj_dg * eBot.dx);
eMaj_db = (GLfloat) ((GLint) vMax->color[2] -
(GLint) vMin->color[2]);
eBot_db = (GLfloat) ((GLint) vMid->color[2] -
(GLint) vMin->color[2]);
dbdx = oneOverArea * (eMaj_db * eBot.dy - eMaj.dy * eBot_db);
span.blueStep = (((int) ((((dbdx) * 2048.0f) >= 0.0F) ? (((dbdx) * 2048.0f) + 0.5F) : (((dbdx) * 2048.0f) - 0.5F))));
dbdy = oneOverArea * (eMaj.dx * eBot_db - eMaj_db * eBot.dx);
eMaj_da = (GLfloat) ((GLint) vMax->color[3] -
(GLint) vMin->color[3]);
eBot_da = (GLfloat) ((GLint) vMid->color[3] -
(GLint) vMin->color[3]);
dadx = oneOverArea * (eMaj_da * eBot.dy - eMaj.dy * eBot_da);
span.alphaStep = (((int) ((((dadx) * 2048.0f) >= 0.0F) ? (((dadx) * 2048.0f) + 0.5F) : (((dadx) * 2048.0f) - 0.5F))));
dady = oneOverArea * (eMaj.dx * eBot_da - eMaj_da * eBot.dx);
}
else {
;
span.interpMask |= 0x200;
drdx = drdy = 0.0F;
dgdx = dgdy = 0.0F;
dbdx = dbdy = 0.0F;
span.redStep = 0;
span.greenStep = 0;
span.blueStep = 0;
dadx = dady = 0.0F;
span.alphaStep = 0;
}
span.interpMask |= 0x020;
{
GLfloat wMax = vMax->win[3];
GLfloat wMin = vMin->win[3];
GLfloat wMid = vMid->win[3];
GLfloat eMaj_ds, eBot_ds;
GLfloat eMaj_dt, eBot_dt;
GLfloat eMaj_du, eBot_du;
GLfloat eMaj_dv, eBot_dv;
eMaj_ds = vMax->texcoord[0][0] * wMax - vMin->texcoord[0][0] * wMin;
eBot_ds = vMid->texcoord[0][0] * wMid - vMin->texcoord[0][0] * wMin;
dsdx = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
dsdy = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
span.texStepX[0][0] = dsdx;
span.texStepY[0][0] = dsdy;
eMaj_dt = vMax->texcoord[0][1] * wMax - vMin->texcoord[0][1] * wMin;
eBot_dt = vMid->texcoord[0][1] * wMid - vMin->texcoord[0][1] * wMin;
dtdx = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
dtdy = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
span.texStepX[0][1] = dtdx;
span.texStepY[0][1] = dtdy;
eMaj_du = vMax->texcoord[0][2] * wMax - vMin->texcoord[0][2] * wMin;
eBot_du = vMid->texcoord[0][2] * wMid - vMin->texcoord[0][2] * wMin;
dudx = oneOverArea * (eMaj_du * eBot.dy - eMaj.dy * eBot_du);
dudy = oneOverArea * (eMaj.dx * eBot_du - eMaj_du * eBot.dx);
span.texStepX[0][2] = dudx;
span.texStepY[0][2] = dudy;
eMaj_dv = vMax->texcoord[0][3] * wMax - vMin->texcoord[0][3] * wMin;
eBot_dv = vMid->texcoord[0][3] * wMid - vMin->texcoord[0][3] * wMin;
dvdx = oneOverArea * (eMaj_dv * eBot.dy - eMaj.dy * eBot_dv);
dvdy = oneOverArea * (eMaj.dx * eBot_dv - eMaj_dv * eBot.dx);
span.texStepX[0][3] = dvdx;
span.texStepY[0][3] = dvdy;
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fr = 0, fdrOuter = 0, fdrInner;
GLfixed fg = 0, fdgOuter = 0, fdgInner;
GLfixed fb = 0, fdbOuter = 0, fdbInner;
GLfixed fa = 0, fdaOuter = 0, fdaInner;
GLfloat sLeft=0, dsOuter=0, dsInner;
GLfloat tLeft=0, dtOuter=0, dtInner;
GLfloat uLeft=0, duOuter=0, duInner;
GLfloat vLeft=0, dvOuter=0, dvInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == 0x1D01) {
fr = (GLfixed) (((vLower->color[0]) << 11)
+ drdx * adjx + drdy * adjy) + 0x00000400;
fdrOuter = (((int) ((((drdy + dxOuter * drdx) * 2048.0f) >= 0.0F) ? (((drdy + dxOuter * drdx) * 2048.0f) + 0.5F) : (((drdy + dxOuter * drdx) * 2048.0f) - 0.5F))));
fg = (GLfixed) (((vLower->color[1]) << 11)
+ dgdx * adjx + dgdy * adjy) + 0x00000400;
fdgOuter = (((int) ((((dgdy + dxOuter * dgdx) * 2048.0f) >= 0.0F) ? (((dgdy + dxOuter * dgdx) * 2048.0f) + 0.5F) : (((dgdy + dxOuter * dgdx) * 2048.0f) - 0.5F))));
fb = (GLfixed) (((vLower->color[2]) << 11)
+ dbdx * adjx + dbdy * adjy) + 0x00000400;
fdbOuter = (((int) ((((dbdy + dxOuter * dbdx) * 2048.0f) >= 0.0F) ? (((dbdy + dxOuter * dbdx) * 2048.0f) + 0.5F) : (((dbdy + dxOuter * dbdx) * 2048.0f) - 0.5F))));
fa = (GLfixed) (((vLower->color[3]) << 11)
+ dadx * adjx + dady * adjy) + 0x00000400;
fdaOuter = (((int) ((((dady + dxOuter * dadx) * 2048.0f) >= 0.0F) ? (((dady + dxOuter * dadx) * 2048.0f) + 0.5F) : (((dady + dxOuter * dadx) * 2048.0f) - 0.5F))));
}
else {
;
fr = ((v2->color[0]) << 11);
fg = ((v2->color[1]) << 11);
fb = ((v2->color[2]) << 11);
fdrOuter = fdgOuter = fdbOuter = 0;
fa = ((v2->color[3]) << 11);
fdaOuter = 0;
}
{
GLfloat invW = vLower->win[3];
GLfloat s0, t0, u0, v0;
s0 = vLower->texcoord[0][0] * invW;
sLeft = s0 + (span.texStepX[0][0] * adjx + dsdy * adjy)
* (1.0F/2048.0f);
dsOuter = dsdy + dxOuter * span.texStepX[0][0];
t0 = vLower->texcoord[0][1] * invW;
tLeft = t0 + (span.texStepX[0][1] * adjx + dtdy * adjy)
* (1.0F/2048.0f);
dtOuter = dtdy + dxOuter * span.texStepX[0][1];
u0 = vLower->texcoord[0][2] * invW;
uLeft = u0 + (span.texStepX[0][2] * adjx + dudy * adjy)
* (1.0F/2048.0f);
duOuter = dudy + dxOuter * span.texStepX[0][2];
v0 = vLower->texcoord[0][3] * invW;
vLeft = v0 + (span.texStepX[0][3] * adjx + dvdy * adjy)
* (1.0F/2048.0f);
dvOuter = dvdy + dxOuter * span.texStepX[0][3];
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdrInner = fdrOuter + span.redStep;
fdgInner = fdgOuter + span.greenStep;
fdbInner = fdbOuter + span.blueStep;
fdaInner = fdaOuter + span.alphaStep;
dsInner = dsOuter + span.texStepX[0][0];
dtInner = dtOuter + span.texStepX[0][1];
duInner = duOuter + span.texStepX[0][2];
dvInner = dvOuter + span.texStepX[0][3];
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.red = fr;
span.green = fg;
span.blue = fb;
span.alpha = fa;
span.tex[0][0] = sLeft;
span.tex[0][1] = tLeft;
span.tex[0][2] = uLeft;
span.tex[0][3] = vLeft;
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffrend = span.red + len * span.redStep;
GLfixed ffgend = span.green + len * span.greenStep;
GLfixed ffbend = span.blue + len * span.blueStep;
if (ffrend < 0) {
span.red -= ffrend;
if (span.red < 0)
span.red = 0;
}
if (ffgend < 0) {
span.green -= ffgend;
if (span.green < 0)
span.green = 0;
}
if (ffbend < 0) {
span.blue -= ffbend;
if (span.blue < 0)
span.blue = 0;
}
}
{
const GLint len = right - span.x - 1;
GLfixed ffaend = span.alpha + len * span.alphaStep;
if (ffaend < 0) {
span.alpha -= ffaend;
if (span.alpha < 0)
span.alpha = 0;
}
}
/* This is where we actually generate fragments */
if (span.end > 0) {
span.interpMask &= ~0x001; span.arrayMask |= 0x001; fast_persp_span(ctx, &span, &info);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
fr += fdrOuter;
fg += fdgOuter;
fb += fdbOuter;
fa += fdaOuter;
sLeft += dsOuter;
tLeft += dtOuter;
uLeft += duOuter;
vLeft += dvOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
fr += fdrInner;
fg += fdgInner;
fb += fdbInner;
fa += fdaInner;
sLeft += dsInner;
tLeft += dtInner;
uLeft += duInner;
vLeft += dvInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Render a smooth-shaded, textured, RGBA triangle.
* Interpolate S,T,R with perspective correction, w/out mipmapping.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void general_textured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
(span).primitive = (0x0009);
(span).interpMask = (0);
(span).arrayMask = (0);
(span).start = 0;
(span).end = (0);
(span).facing = 0;
(span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays;
/*
printf("%s()\n", __FUNCTION__);
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat drdx, drdy;
GLfloat dgdx, dgdy;
GLfloat dbdx, dbdy;
GLfloat dadx, dady;
GLfloat dsrdx, dsrdy;
GLfloat dsgdx, dsgdy;
GLfloat dsbdx, dsbdy;
GLfloat dsdx, dsdy;
GLfloat dtdx, dtdy;
GLfloat dudx, dudy;
GLfloat dvdx, dvdy;
/*
* Execute user-supplied setup code
*/
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= 0x001;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dr, eBot_dr;
GLfloat eMaj_dg, eBot_dg;
GLfloat eMaj_db, eBot_db;
GLfloat eMaj_da, eBot_da;
eMaj_dr = (GLfloat) ((GLint) vMax->color[0] -
(GLint) vMin->color[0]);
eBot_dr = (GLfloat) ((GLint) vMid->color[0] -
(GLint) vMin->color[0]);
drdx = oneOverArea * (eMaj_dr * eBot.dy - eMaj.dy * eBot_dr);
span.redStep = (((int) ((((drdx) * 2048.0f) >= 0.0F) ? (((drdx) * 2048.0f) + 0.5F) : (((drdx) * 2048.0f) - 0.5F))));
drdy = oneOverArea * (eMaj.dx * eBot_dr - eMaj_dr * eBot.dx);
eMaj_dg = (GLfloat) ((GLint) vMax->color[1] -
(GLint) vMin->color[1]);
eBot_dg = (GLfloat) ((GLint) vMid->color[1] -
(GLint) vMin->color[1]);
dgdx = oneOverArea * (eMaj_dg * eBot.dy - eMaj.dy * eBot_dg);
span.greenStep = (((int) ((((dgdx) * 2048.0f) >= 0.0F) ? (((dgdx) * 2048.0f) + 0.5F) : (((dgdx) * 2048.0f) - 0.5F))));
dgdy = oneOverArea * (eMaj.dx * eBot_dg - eMaj_dg * eBot.dx);
eMaj_db = (GLfloat) ((GLint) vMax->color[2] -
(GLint) vMin->color[2]);
eBot_db = (GLfloat) ((GLint) vMid->color[2] -
(GLint) vMin->color[2]);
dbdx = oneOverArea * (eMaj_db * eBot.dy - eMaj.dy * eBot_db);
span.blueStep = (((int) ((((dbdx) * 2048.0f) >= 0.0F) ? (((dbdx) * 2048.0f) + 0.5F) : (((dbdx) * 2048.0f) - 0.5F))));
dbdy = oneOverArea * (eMaj.dx * eBot_db - eMaj_db * eBot.dx);
eMaj_da = (GLfloat) ((GLint) vMax->color[3] -
(GLint) vMin->color[3]);
eBot_da = (GLfloat) ((GLint) vMid->color[3] -
(GLint) vMin->color[3]);
dadx = oneOverArea * (eMaj_da * eBot.dy - eMaj.dy * eBot_da);
span.alphaStep = (((int) ((((dadx) * 2048.0f) >= 0.0F) ? (((dadx) * 2048.0f) + 0.5F) : (((dadx) * 2048.0f) - 0.5F))));
dady = oneOverArea * (eMaj.dx * eBot_da - eMaj_da * eBot.dx);
}
else {
;
span.interpMask |= 0x200;
drdx = drdy = 0.0F;
dgdx = dgdy = 0.0F;
dbdx = dbdy = 0.0F;
span.redStep = 0;
span.greenStep = 0;
span.blueStep = 0;
dadx = dady = 0.0F;
span.alphaStep = 0;
}
span.interpMask |= 0x002;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dsr, eBot_dsr;
GLfloat eMaj_dsg, eBot_dsg;
GLfloat eMaj_dsb, eBot_dsb;
eMaj_dsr = (GLfloat) ((GLint) vMax->specular[0] -
(GLint) vMin->specular[0]);
eBot_dsr = (GLfloat) ((GLint) vMid->specular[0] -
(GLint) vMin->specular[0]);
dsrdx = oneOverArea * (eMaj_dsr * eBot.dy - eMaj.dy * eBot_dsr);
span.specRedStep = (((int) ((((dsrdx) * 2048.0f) >= 0.0F) ? (((dsrdx) * 2048.0f) + 0.5F) : (((dsrdx) * 2048.0f) - 0.5F))));
dsrdy = oneOverArea * (eMaj.dx * eBot_dsr - eMaj_dsr * eBot.dx);
eMaj_dsg = (GLfloat) ((GLint) vMax->specular[1] -
(GLint) vMin->specular[1]);
eBot_dsg = (GLfloat) ((GLint) vMid->specular[1] -
(GLint) vMin->specular[1]);
dsgdx = oneOverArea * (eMaj_dsg * eBot.dy - eMaj.dy * eBot_dsg);
span.specGreenStep = (((int) ((((dsgdx) * 2048.0f) >= 0.0F) ? (((dsgdx) * 2048.0f) + 0.5F) : (((dsgdx) * 2048.0f) - 0.5F))));
dsgdy = oneOverArea * (eMaj.dx * eBot_dsg - eMaj_dsg * eBot.dx);
eMaj_dsb = (GLfloat) ((GLint) vMax->specular[2] -
(GLint) vMin->specular[2]);
eBot_dsb = (GLfloat) ((GLint) vMid->specular[2] -
(GLint) vMin->specular[2]);
dsbdx = oneOverArea * (eMaj_dsb * eBot.dy - eMaj.dy * eBot_dsb);
span.specBlueStep = (((int) ((((dsbdx) * 2048.0f) >= 0.0F) ? (((dsbdx) * 2048.0f) + 0.5F) : (((dsbdx) * 2048.0f) - 0.5F))));
dsbdy = oneOverArea * (eMaj.dx * eBot_dsb - eMaj_dsb * eBot.dx);
}
else {
dsrdx = dsrdy = 0.0F;
dsgdx = dsgdy = 0.0F;
dsbdx = dsbdy = 0.0F;
span.specRedStep = 0;
span.specGreenStep = 0;
span.specBlueStep = 0;
}
span.interpMask |= 0x020;
{
GLfloat wMax = vMax->win[3];
GLfloat wMin = vMin->win[3];
GLfloat wMid = vMid->win[3];
GLfloat eMaj_ds, eBot_ds;
GLfloat eMaj_dt, eBot_dt;
GLfloat eMaj_du, eBot_du;
GLfloat eMaj_dv, eBot_dv;
eMaj_ds = vMax->texcoord[0][0] * wMax - vMin->texcoord[0][0] * wMin;
eBot_ds = vMid->texcoord[0][0] * wMid - vMin->texcoord[0][0] * wMin;
dsdx = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
dsdy = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
span.texStepX[0][0] = dsdx;
span.texStepY[0][0] = dsdy;
eMaj_dt = vMax->texcoord[0][1] * wMax - vMin->texcoord[0][1] * wMin;
eBot_dt = vMid->texcoord[0][1] * wMid - vMin->texcoord[0][1] * wMin;
dtdx = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
dtdy = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
span.texStepX[0][1] = dtdx;
span.texStepY[0][1] = dtdy;
eMaj_du = vMax->texcoord[0][2] * wMax - vMin->texcoord[0][2] * wMin;
eBot_du = vMid->texcoord[0][2] * wMid - vMin->texcoord[0][2] * wMin;
dudx = oneOverArea * (eMaj_du * eBot.dy - eMaj.dy * eBot_du);
dudy = oneOverArea * (eMaj.dx * eBot_du - eMaj_du * eBot.dx);
span.texStepX[0][2] = dudx;
span.texStepY[0][2] = dudy;
eMaj_dv = vMax->texcoord[0][3] * wMax - vMin->texcoord[0][3] * wMin;
eBot_dv = vMid->texcoord[0][3] * wMid - vMin->texcoord[0][3] * wMin;
dvdx = oneOverArea * (eMaj_dv * eBot.dy - eMaj.dy * eBot_dv);
dvdy = oneOverArea * (eMaj.dx * eBot_dv - eMaj_dv * eBot.dx);
span.texStepX[0][3] = dvdx;
span.texStepY[0][3] = dvdy;
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fr = 0, fdrOuter = 0, fdrInner;
GLfixed fg = 0, fdgOuter = 0, fdgInner;
GLfixed fb = 0, fdbOuter = 0, fdbInner;
GLfixed fa = 0, fdaOuter = 0, fdaInner;
GLfixed fsr=0, fdsrOuter=0, fdsrInner;
GLfixed fsg=0, fdsgOuter=0, fdsgInner;
GLfixed fsb=0, fdsbOuter=0, fdsbInner;
GLfloat sLeft=0, dsOuter=0, dsInner;
GLfloat tLeft=0, dtOuter=0, dtInner;
GLfloat uLeft=0, duOuter=0, duInner;
GLfloat vLeft=0, dvOuter=0, dvInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == 0x1D01) {
fr = (GLfixed) (((vLower->color[0]) << 11)
+ drdx * adjx + drdy * adjy) + 0x00000400;
fdrOuter = (((int) ((((drdy + dxOuter * drdx) * 2048.0f) >= 0.0F) ? (((drdy + dxOuter * drdx) * 2048.0f) + 0.5F) : (((drdy + dxOuter * drdx) * 2048.0f) - 0.5F))));
fg = (GLfixed) (((vLower->color[1]) << 11)
+ dgdx * adjx + dgdy * adjy) + 0x00000400;
fdgOuter = (((int) ((((dgdy + dxOuter * dgdx) * 2048.0f) >= 0.0F) ? (((dgdy + dxOuter * dgdx) * 2048.0f) + 0.5F) : (((dgdy + dxOuter * dgdx) * 2048.0f) - 0.5F))));
fb = (GLfixed) (((vLower->color[2]) << 11)
+ dbdx * adjx + dbdy * adjy) + 0x00000400;
fdbOuter = (((int) ((((dbdy + dxOuter * dbdx) * 2048.0f) >= 0.0F) ? (((dbdy + dxOuter * dbdx) * 2048.0f) + 0.5F) : (((dbdy + dxOuter * dbdx) * 2048.0f) - 0.5F))));
fa = (GLfixed) (((vLower->color[3]) << 11)
+ dadx * adjx + dady * adjy) + 0x00000400;
fdaOuter = (((int) ((((dady + dxOuter * dadx) * 2048.0f) >= 0.0F) ? (((dady + dxOuter * dadx) * 2048.0f) + 0.5F) : (((dady + dxOuter * dadx) * 2048.0f) - 0.5F))));
}
else {
;
fr = ((v2->color[0]) << 11);
fg = ((v2->color[1]) << 11);
fb = ((v2->color[2]) << 11);
fdrOuter = fdgOuter = fdbOuter = 0;
fa = ((v2->color[3]) << 11);
fdaOuter = 0;
}
if (ctx->Light.ShadeModel == 0x1D01) {
fsr = (GLfixed) (((vLower->specular[0]) << 11)
+ dsrdx * adjx + dsrdy * adjy) + 0x00000400;
fdsrOuter = (((int) ((((dsrdy + dxOuter * dsrdx) * 2048.0f) >= 0.0F) ? (((dsrdy + dxOuter * dsrdx) * 2048.0f) + 0.5F) : (((dsrdy + dxOuter * dsrdx) * 2048.0f) - 0.5F))));
fsg = (GLfixed) (((vLower->specular[1]) << 11)
+ dsgdx * adjx + dsgdy * adjy) + 0x00000400;
fdsgOuter = (((int) ((((dsgdy + dxOuter * dsgdx) * 2048.0f) >= 0.0F) ? (((dsgdy + dxOuter * dsgdx) * 2048.0f) + 0.5F) : (((dsgdy + dxOuter * dsgdx) * 2048.0f) - 0.5F))));
fsb = (GLfixed) (((vLower->specular[2]) << 11)
+ dsbdx * adjx + dsbdy * adjy) + 0x00000400;
fdsbOuter = (((int) ((((dsbdy + dxOuter * dsbdx) * 2048.0f) >= 0.0F) ? (((dsbdy + dxOuter * dsbdx) * 2048.0f) + 0.5F) : (((dsbdy + dxOuter * dsbdx) * 2048.0f) - 0.5F))));
}
else {
fsr = ((v2->specular[0]) << 11);
fsg = ((v2->specular[1]) << 11);
fsb = ((v2->specular[2]) << 11);
fdsrOuter = fdsgOuter = fdsbOuter = 0;
}
{
GLfloat invW = vLower->win[3];
GLfloat s0, t0, u0, v0;
s0 = vLower->texcoord[0][0] * invW;
sLeft = s0 + (span.texStepX[0][0] * adjx + dsdy * adjy)
* (1.0F/2048.0f);
dsOuter = dsdy + dxOuter * span.texStepX[0][0];
t0 = vLower->texcoord[0][1] * invW;
tLeft = t0 + (span.texStepX[0][1] * adjx + dtdy * adjy)
* (1.0F/2048.0f);
dtOuter = dtdy + dxOuter * span.texStepX[0][1];
u0 = vLower->texcoord[0][2] * invW;
uLeft = u0 + (span.texStepX[0][2] * adjx + dudy * adjy)
* (1.0F/2048.0f);
duOuter = dudy + dxOuter * span.texStepX[0][2];
v0 = vLower->texcoord[0][3] * invW;
vLeft = v0 + (span.texStepX[0][3] * adjx + dvdy * adjy)
* (1.0F/2048.0f);
dvOuter = dvdy + dxOuter * span.texStepX[0][3];
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdrInner = fdrOuter + span.redStep;
fdgInner = fdgOuter + span.greenStep;
fdbInner = fdbOuter + span.blueStep;
fdaInner = fdaOuter + span.alphaStep;
fdsrInner = fdsrOuter + span.specRedStep;
fdsgInner = fdsgOuter + span.specGreenStep;
fdsbInner = fdsbOuter + span.specBlueStep;
dsInner = dsOuter + span.texStepX[0][0];
dtInner = dtOuter + span.texStepX[0][1];
duInner = duOuter + span.texStepX[0][2];
dvInner = dvOuter + span.texStepX[0][3];
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.red = fr;
span.green = fg;
span.blue = fb;
span.alpha = fa;
span.specRed = fsr;
span.specGreen = fsg;
span.specBlue = fsb;
span.tex[0][0] = sLeft;
span.tex[0][1] = tLeft;
span.tex[0][2] = uLeft;
span.tex[0][3] = vLeft;
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffrend = span.red + len * span.redStep;
GLfixed ffgend = span.green + len * span.greenStep;
GLfixed ffbend = span.blue + len * span.blueStep;
if (ffrend < 0) {
span.red -= ffrend;
if (span.red < 0)
span.red = 0;
}
if (ffgend < 0) {
span.green -= ffgend;
if (span.green < 0)
span.green = 0;
}
if (ffbend < 0) {
span.blue -= ffbend;
if (span.blue < 0)
span.blue = 0;
}
}
{
const GLint len = right - span.x - 1;
GLfixed ffaend = span.alpha + len * span.alphaStep;
if (ffaend < 0) {
span.alpha -= ffaend;
if (span.alpha < 0)
span.alpha = 0;
}
}
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffsrend = span.specRed + len * span.specRedStep;
GLfixed ffsgend = span.specGreen + len * span.specGreenStep;
GLfixed ffsbend = span.specBlue + len * span.specBlueStep;
if (ffsrend < 0) {
span.specRed -= ffsrend;
if (span.specRed < 0)
span.specRed = 0;
}
if (ffsgend < 0) {
span.specGreen -= ffsgend;
if (span.specGreen < 0)
span.specGreen = 0;
}
if (ffsbend < 0) {
span.specBlue -= ffsbend;
if (span.specBlue < 0)
span.specBlue = 0;
}
}
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_texture_span(ctx, &span);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
fr += fdrOuter;
fg += fdgOuter;
fb += fdbOuter;
fa += fdaOuter;
fsr += fdsrOuter;
fsg += fdsgOuter;
fsb += fdsbOuter;
sLeft += dsOuter;
tLeft += dtOuter;
uLeft += duOuter;
vLeft += dvOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
fr += fdrInner;
fg += fdgInner;
fb += fdbInner;
fa += fdaInner;
fsr += fdsrInner;
fsg += fdsgInner;
fsb += fdsbInner;
sLeft += dsInner;
tLeft += dtInner;
uLeft += duInner;
vLeft += dvInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* This is the big one!
* Interpolate Z, RGB, Alpha, specular, fog, and N sets of texture coordinates.
* Yup, it's slow.
*/
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void multitextured_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
do { (span).primitive = (0x0009); (span).interpMask = (0); (span).arrayMask = (0); (span).start = 0; (span).end = (0); (span).facing = 0; (span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays; } while (0);
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
ctx->OcclusionResult = 0x1;
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
GLfloat dfogdy;
GLfloat drdx, drdy;
GLfloat dgdx, dgdy;
GLfloat dbdx, dbdy;
GLfloat dadx, dady;
GLfloat dsrdx, dsrdy;
GLfloat dsgdx, dsgdy;
GLfloat dsbdx, dsbdy;
GLfloat dsdx[8], dsdy[8];
GLfloat dtdx[8], dtdy[8];
GLfloat dudx[8], dudy[8];
GLfloat dvdx[8], dvdy[8];
/*
* Execute user-supplied setup code
*/
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
span.interpMask |= 0x010;
{
const GLfloat eMaj_dfog = vMax->fog - vMin->fog;
const GLfloat eBot_dfog = vMid->fog - vMin->fog;
span.fogStep = oneOverArea * (eMaj_dfog * eBot.dy - eMaj.dy * eBot_dfog);
dfogdy = oneOverArea * (eMaj.dx * eBot_dfog - eMaj_dfog * eBot.dx);
}
span.interpMask |= 0x001;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dr, eBot_dr;
GLfloat eMaj_dg, eBot_dg;
GLfloat eMaj_db, eBot_db;
GLfloat eMaj_da, eBot_da;
eMaj_dr = (GLfloat) ((GLint) vMax->color[0] -
(GLint) vMin->color[0]);
eBot_dr = (GLfloat) ((GLint) vMid->color[0] -
(GLint) vMin->color[0]);
drdx = oneOverArea * (eMaj_dr * eBot.dy - eMaj.dy * eBot_dr);
span.redStep = (((int) ((((drdx) * 2048.0f) >= 0.0F) ? (((drdx) * 2048.0f) + 0.5F) : (((drdx) * 2048.0f) - 0.5F))));
drdy = oneOverArea * (eMaj.dx * eBot_dr - eMaj_dr * eBot.dx);
eMaj_dg = (GLfloat) ((GLint) vMax->color[1] -
(GLint) vMin->color[1]);
eBot_dg = (GLfloat) ((GLint) vMid->color[1] -
(GLint) vMin->color[1]);
dgdx = oneOverArea * (eMaj_dg * eBot.dy - eMaj.dy * eBot_dg);
span.greenStep = (((int) ((((dgdx) * 2048.0f) >= 0.0F) ? (((dgdx) * 2048.0f) + 0.5F) : (((dgdx) * 2048.0f) - 0.5F))));
dgdy = oneOverArea * (eMaj.dx * eBot_dg - eMaj_dg * eBot.dx);
eMaj_db = (GLfloat) ((GLint) vMax->color[2] -
(GLint) vMin->color[2]);
eBot_db = (GLfloat) ((GLint) vMid->color[2] -
(GLint) vMin->color[2]);
dbdx = oneOverArea * (eMaj_db * eBot.dy - eMaj.dy * eBot_db);
span.blueStep = (((int) ((((dbdx) * 2048.0f) >= 0.0F) ? (((dbdx) * 2048.0f) + 0.5F) : (((dbdx) * 2048.0f) - 0.5F))));
dbdy = oneOverArea * (eMaj.dx * eBot_db - eMaj_db * eBot.dx);
eMaj_da = (GLfloat) ((GLint) vMax->color[3] -
(GLint) vMin->color[3]);
eBot_da = (GLfloat) ((GLint) vMid->color[3] -
(GLint) vMin->color[3]);
dadx = oneOverArea * (eMaj_da * eBot.dy - eMaj.dy * eBot_da);
span.alphaStep = (((int) ((((dadx) * 2048.0f) >= 0.0F) ? (((dadx) * 2048.0f) + 0.5F) : (((dadx) * 2048.0f) - 0.5F))));
dady = oneOverArea * (eMaj.dx * eBot_da - eMaj_da * eBot.dx);
}
else {
;
span.interpMask |= 0x200;
drdx = drdy = 0.0F;
dgdx = dgdy = 0.0F;
dbdx = dbdy = 0.0F;
span.redStep = 0;
span.greenStep = 0;
span.blueStep = 0;
dadx = dady = 0.0F;
span.alphaStep = 0;
}
span.interpMask |= 0x002;
if (ctx->Light.ShadeModel == 0x1D01) {
GLfloat eMaj_dsr, eBot_dsr;
GLfloat eMaj_dsg, eBot_dsg;
GLfloat eMaj_dsb, eBot_dsb;
eMaj_dsr = (GLfloat) ((GLint) vMax->specular[0] -
(GLint) vMin->specular[0]);
eBot_dsr = (GLfloat) ((GLint) vMid->specular[0] -
(GLint) vMin->specular[0]);
dsrdx = oneOverArea * (eMaj_dsr * eBot.dy - eMaj.dy * eBot_dsr);
span.specRedStep = (((int) ((((dsrdx) * 2048.0f) >= 0.0F) ? (((dsrdx) * 2048.0f) + 0.5F) : (((dsrdx) * 2048.0f) - 0.5F))));
dsrdy = oneOverArea * (eMaj.dx * eBot_dsr - eMaj_dsr * eBot.dx);
eMaj_dsg = (GLfloat) ((GLint) vMax->specular[1] -
(GLint) vMin->specular[1]);
eBot_dsg = (GLfloat) ((GLint) vMid->specular[1] -
(GLint) vMin->specular[1]);
dsgdx = oneOverArea * (eMaj_dsg * eBot.dy - eMaj.dy * eBot_dsg);
span.specGreenStep = (((int) ((((dsgdx) * 2048.0f) >= 0.0F) ? (((dsgdx) * 2048.0f) + 0.5F) : (((dsgdx) * 2048.0f) - 0.5F))));
dsgdy = oneOverArea * (eMaj.dx * eBot_dsg - eMaj_dsg * eBot.dx);
eMaj_dsb = (GLfloat) ((GLint) vMax->specular[2] -
(GLint) vMin->specular[2]);
eBot_dsb = (GLfloat) ((GLint) vMid->specular[2] -
(GLint) vMin->specular[2]);
dsbdx = oneOverArea * (eMaj_dsb * eBot.dy - eMaj.dy * eBot_dsb);
span.specBlueStep = (((int) ((((dsbdx) * 2048.0f) >= 0.0F) ? (((dsbdx) * 2048.0f) + 0.5F) : (((dsbdx) * 2048.0f) - 0.5F))));
dsbdy = oneOverArea * (eMaj.dx * eBot_dsb - eMaj_dsb * eBot.dx);
}
else {
dsrdx = dsrdy = 0.0F;
dsgdx = dsgdy = 0.0F;
dsbdx = dsbdy = 0.0F;
span.specRedStep = 0;
span.specGreenStep = 0;
span.specBlueStep = 0;
}
span.interpMask |= 0x020;
{
GLfloat wMax = vMax->win[3];
GLfloat wMin = vMin->win[3];
GLfloat wMid = vMid->win[3];
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
GLfloat eMaj_ds, eBot_ds;
GLfloat eMaj_dt, eBot_dt;
GLfloat eMaj_du, eBot_du;
GLfloat eMaj_dv, eBot_dv;
eMaj_ds = vMax->texcoord[u][0] * wMax
- vMin->texcoord[u][0] * wMin;
eBot_ds = vMid->texcoord[u][0] * wMid
- vMin->texcoord[u][0] * wMin;
dsdx[u] = oneOverArea * (eMaj_ds * eBot.dy - eMaj.dy * eBot_ds);
dsdy[u] = oneOverArea * (eMaj.dx * eBot_ds - eMaj_ds * eBot.dx);
span.texStepX[u][0] = dsdx[u];
span.texStepY[u][0] = dsdy[u];
eMaj_dt = vMax->texcoord[u][1] * wMax
- vMin->texcoord[u][1] * wMin;
eBot_dt = vMid->texcoord[u][1] * wMid
- vMin->texcoord[u][1] * wMin;
dtdx[u] = oneOverArea * (eMaj_dt * eBot.dy - eMaj.dy * eBot_dt);
dtdy[u] = oneOverArea * (eMaj.dx * eBot_dt - eMaj_dt * eBot.dx);
span.texStepX[u][1] = dtdx[u];
span.texStepY[u][1] = dtdy[u];
eMaj_du = vMax->texcoord[u][2] * wMax
- vMin->texcoord[u][2] * wMin;
eBot_du = vMid->texcoord[u][2] * wMid
- vMin->texcoord[u][2] * wMin;
dudx[u] = oneOverArea * (eMaj_du * eBot.dy - eMaj.dy * eBot_du);
dudy[u] = oneOverArea * (eMaj.dx * eBot_du - eMaj_du * eBot.dx);
span.texStepX[u][2] = dudx[u];
span.texStepY[u][2] = dudy[u];
eMaj_dv = vMax->texcoord[u][3] * wMax
- vMin->texcoord[u][3] * wMin;
eBot_dv = vMid->texcoord[u][3] * wMid
- vMin->texcoord[u][3] * wMin;
dvdx[u] = oneOverArea * (eMaj_dv * eBot.dy - eMaj.dy * eBot_dv);
dvdy[u] = oneOverArea * (eMaj.dx * eBot_dv - eMaj_dv * eBot.dx);
span.texStepX[u][3] = dvdx[u];
span.texStepY[u][3] = dvdy[u];
}
}
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
GLfloat fogLeft = 0, dfogOuter = 0, dfogInner;
GLfixed fr = 0, fdrOuter = 0, fdrInner;
GLfixed fg = 0, fdgOuter = 0, fdgInner;
GLfixed fb = 0, fdbOuter = 0, fdbInner;
GLfixed fa = 0, fdaOuter = 0, fdaInner;
GLfixed fsr=0, fdsrOuter=0, fdsrInner;
GLfixed fsg=0, fdsgOuter=0, fdsgInner;
GLfixed fsb=0, fdsbOuter=0, fdsbInner;
GLfloat sLeft[8];
GLfloat tLeft[8];
GLfloat uLeft[8];
GLfloat vLeft[8];
GLfloat dsOuter[8], dsInner[8];
GLfloat dtOuter[8], dtInner[8];
GLfloat duOuter[8], duInner[8];
GLfloat dvOuter[8], dvInner[8];
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
fogLeft = vLower->fog + (span.fogStep * adjx + dfogdy * adjy)
* (1.0F/2048.0f);
dfogOuter = dfogdy + dxOuter * span.fogStep;
if (ctx->Light.ShadeModel == 0x1D01) {
fr = (GLfixed) (((vLower->color[0]) << 11)
+ drdx * adjx + drdy * adjy) + 0x00000400;
fdrOuter = (((int) ((((drdy + dxOuter * drdx) * 2048.0f) >= 0.0F) ? (((drdy + dxOuter * drdx) * 2048.0f) + 0.5F) : (((drdy + dxOuter * drdx) * 2048.0f) - 0.5F))));
fg = (GLfixed) (((vLower->color[1]) << 11)
+ dgdx * adjx + dgdy * adjy) + 0x00000400;
fdgOuter = (((int) ((((dgdy + dxOuter * dgdx) * 2048.0f) >= 0.0F) ? (((dgdy + dxOuter * dgdx) * 2048.0f) + 0.5F) : (((dgdy + dxOuter * dgdx) * 2048.0f) - 0.5F))));
fb = (GLfixed) (((vLower->color[2]) << 11)
+ dbdx * adjx + dbdy * adjy) + 0x00000400;
fdbOuter = (((int) ((((dbdy + dxOuter * dbdx) * 2048.0f) >= 0.0F) ? (((dbdy + dxOuter * dbdx) * 2048.0f) + 0.5F) : (((dbdy + dxOuter * dbdx) * 2048.0f) - 0.5F))));
fa = (GLfixed) (((vLower->color[3]) << 11)
+ dadx * adjx + dady * adjy) + 0x00000400;
fdaOuter = (((int) ((((dady + dxOuter * dadx) * 2048.0f) >= 0.0F) ? (((dady + dxOuter * dadx) * 2048.0f) + 0.5F) : (((dady + dxOuter * dadx) * 2048.0f) - 0.5F))));
}
else {
;
fr = ((v2->color[0]) << 11);
fg = ((v2->color[1]) << 11);
fb = ((v2->color[2]) << 11);
fdrOuter = fdgOuter = fdbOuter = 0;
fa = ((v2->color[3]) << 11);
fdaOuter = 0;
}
if (ctx->Light.ShadeModel == 0x1D01) {
fsr = (GLfixed) (((vLower->specular[0]) << 11)
+ dsrdx * adjx + dsrdy * adjy) + 0x00000400;
fdsrOuter = (((int) ((((dsrdy + dxOuter * dsrdx) * 2048.0f) >= 0.0F) ? (((dsrdy + dxOuter * dsrdx) * 2048.0f) + 0.5F) : (((dsrdy + dxOuter * dsrdx) * 2048.0f) - 0.5F))));
fsg = (GLfixed) (((vLower->specular[1]) << 11)
+ dsgdx * adjx + dsgdy * adjy) + 0x00000400;
fdsgOuter = (((int) ((((dsgdy + dxOuter * dsgdx) * 2048.0f) >= 0.0F) ? (((dsgdy + dxOuter * dsgdx) * 2048.0f) + 0.5F) : (((dsgdy + dxOuter * dsgdx) * 2048.0f) - 0.5F))));
fsb = (GLfixed) (((vLower->specular[2]) << 11)
+ dsbdx * adjx + dsbdy * adjy) + 0x00000400;
fdsbOuter = (((int) ((((dsbdy + dxOuter * dsbdx) * 2048.0f) >= 0.0F) ? (((dsbdy + dxOuter * dsbdx) * 2048.0f) + 0.5F) : (((dsbdy + dxOuter * dsbdx) * 2048.0f) - 0.5F))));
}
else {
fsr = ((v2->specular[0]) << 11);
fsg = ((v2->specular[1]) << 11);
fsb = ((v2->specular[2]) << 11);
fdsrOuter = fdsgOuter = fdsbOuter = 0;
}
{
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
GLfloat invW = vLower->win[3];
GLfloat s0, t0, u0, v0;
s0 = vLower->texcoord[u][0] * invW;
sLeft[u] = s0 + (span.texStepX[u][0] * adjx + dsdy[u]
* adjy) * (1.0F/2048.0f);
dsOuter[u] = dsdy[u] + dxOuter * span.texStepX[u][0];
t0 = vLower->texcoord[u][1] * invW;
tLeft[u] = t0 + (span.texStepX[u][1] * adjx + dtdy[u]
* adjy) * (1.0F/2048.0f);
dtOuter[u] = dtdy[u] + dxOuter * span.texStepX[u][1];
u0 = vLower->texcoord[u][2] * invW;
uLeft[u] = u0 + (span.texStepX[u][2] * adjx + dudy[u]
* adjy) * (1.0F/2048.0f);
duOuter[u] = dudy[u] + dxOuter * span.texStepX[u][2];
v0 = vLower->texcoord[u][3] * invW;
vLeft[u] = v0 + (span.texStepX[u][3] * adjx + dvdy[u]
* adjy) * (1.0F/2048.0f);
dvOuter[u] = dvdy[u] + dxOuter * span.texStepX[u][3];
}
}
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
dfogInner = dfogOuter + span.fogStep;
fdrInner = fdrOuter + span.redStep;
fdgInner = fdgOuter + span.greenStep;
fdbInner = fdbOuter + span.blueStep;
fdaInner = fdaOuter + span.alphaStep;
fdsrInner = fdsrOuter + span.specRedStep;
fdsgInner = fdsgOuter + span.specGreenStep;
fdsbInner = fdsbOuter + span.specBlueStep;
{
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
dsInner[u] = dsOuter[u] + span.texStepX[u][0];
dtInner[u] = dtOuter[u] + span.texStepX[u][1];
duInner[u] = duOuter[u] + span.texStepX[u][2];
dvInner[u] = dvOuter[u] + span.texStepX[u][3];
}
}
}
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
span.fog = fogLeft;
span.red = fr;
span.green = fg;
span.blue = fb;
span.alpha = fa;
span.specRed = fsr;
span.specGreen = fsg;
span.specBlue = fsb;
{
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
span.tex[u][0] = sLeft[u];
span.tex[u][1] = tLeft[u];
span.tex[u][2] = uLeft[u];
span.tex[u][3] = vLeft[u];
}
}
}
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffrend = span.red + len * span.redStep;
GLfixed ffgend = span.green + len * span.greenStep;
GLfixed ffbend = span.blue + len * span.blueStep;
if (ffrend < 0) {
span.red -= ffrend;
if (span.red < 0)
span.red = 0;
}
if (ffgend < 0) {
span.green -= ffgend;
if (span.green < 0)
span.green = 0;
}
if (ffbend < 0) {
span.blue -= ffbend;
if (span.blue < 0)
span.blue = 0;
}
}
{
const GLint len = right - span.x - 1;
GLfixed ffaend = span.alpha + len * span.alphaStep;
if (ffaend < 0) {
span.alpha -= ffaend;
if (span.alpha < 0)
span.alpha = 0;
}
}
{
/* need this to accomodate round-off errors */
const GLint len = right - span.x - 1;
GLfixed ffsrend = span.specRed + len * span.specRedStep;
GLfixed ffsgend = span.specGreen + len * span.specGreenStep;
GLfixed ffsbend = span.specBlue + len * span.specBlueStep;
if (ffsrend < 0) {
span.specRed -= ffsrend;
if (span.specRed < 0)
span.specRed = 0;
}
if (ffsgend < 0) {
span.specGreen -= ffsgend;
if (span.specGreen < 0)
span.specGreen = 0;
}
if (ffsbend < 0) {
span.specBlue -= ffsbend;
if (span.specBlue < 0)
span.specBlue = 0;
}
}
/* This is where we actually generate fragments */
if (span.end > 0) {
_mesa_write_texture_span(ctx, &span);;
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
fogLeft += dfogOuter;
fr += fdrOuter;
fg += fdgOuter;
fb += fdbOuter;
fa += fdaOuter;
fsr += fdsrOuter;
fsg += fdsgOuter;
fsb += fdsbOuter;
{
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
sLeft[u] += dsOuter[u];
tLeft[u] += dtOuter[u];
uLeft[u] += duOuter[u];
vLeft[u] += dvOuter[u];
}
}
}
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
fogLeft += dfogInner;
fr += fdrInner;
fg += fdgInner;
fb += fdbInner;
fa += fdaInner;
fsr += fdsrInner;
fsg += fdsgInner;
fsb += fdsbInner;
{
GLuint u;
for (u = 0; u < ctx->Const.MaxTextureUnits; u++) {
if (ctx->Texture.Unit[u]._ReallyEnabled) {
sLeft[u] += dsInner[u];
tLeft[u] += dtInner[u];
uLeft[u] += duInner[u];
vLeft[u] += dvInner[u];
}
}
}
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
/*
* Triangle Rasterizer Template
*
* This file is #include'd to generate custom triangle rasterizers.
*
* The following macros may be defined to indicate what auxillary information
* must be interplated across the triangle:
* INTERP_Z - if defined, interpolate Z values
* INTERP_FOG - if defined, interpolate fog values
* INTERP_RGB - if defined, interpolate RGB values
* INTERP_ALPHA - if defined, interpolate Alpha values (req's INTERP_RGB)
* INTERP_SPEC - if defined, interpolate specular RGB values
* INTERP_INDEX - if defined, interpolate color index values
* INTERP_INT_TEX - if defined, interpolate integer ST texcoords
* (fast, simple 2-D texture mapping)
* INTERP_TEX - if defined, interpolate set 0 float STRQ texcoords
* NOTE: OpenGL STRQ = Mesa STUV (R was taken for red)
* INTERP_MULTITEX - if defined, interpolate N units of STRQ texcoords
* INTERP_FLOAT_RGBA - if defined, interpolate RGBA with floating point
* INTERP_FLOAT_SPEC - if defined, interpolate specular with floating point
*
* When one can directly address pixels in the color buffer the following
* macros can be defined and used to compute pixel addresses during
* rasterization (see pRow):
* PIXEL_TYPE - the datatype of a pixel (GLubyte, GLushort, GLuint)
* BYTES_PER_ROW - number of bytes per row in the color buffer
* PIXEL_ADDRESS(X,Y) - returns the address of pixel at (X,Y) where
* Y==0 at bottom of screen and increases upward.
*
* Similarly, for direct depth buffer access, this type is used for depth
* buffer addressing:
* DEPTH_TYPE - either GLushort or GLuint
*
* Optionally, one may provide one-time setup code per triangle:
* SETUP_CODE - code which is to be executed once per triangle
* CLEANUP_CODE - code to execute at end of triangle
*
* The following macro MUST be defined:
* RENDER_SPAN(span) - code to write a span of pixels.
*
* This code was designed for the origin to be in the lower-left corner.
*
* Inspired by triangle rasterizer code written by Allen Akin. Thanks Allen!
*/
/*
* This is a bit of a hack, but it's a centralized place to enable floating-
* point color interpolation when GLchan is actually floating point.
*/
static void occlusion_zless_triangle(GLcontext *ctx, const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
typedef struct {
const SWvertex *v0, *v1; /* Y(v0) < Y(v1) */
GLfloat dx; /* X(v1) - X(v0) */
GLfloat dy; /* Y(v1) - Y(v0) */
GLfixed fdxdy; /* dx/dy in fixed-point */
GLfixed fsx; /* first sample point x coord */
GLfixed fsy;
GLfloat adjy; /* adjust from v[0]->fy to fsy, scaled */
GLint lines; /* number of lines to be sampled on this edge */
GLfixed fx0; /* fixed pt X of lower endpoint */
} EdgeT;
const GLint depthBits = ctx->Visual.depthBits;
const GLint fixedToDepthShift = depthBits <= 16 ? FIXED_SHIFT : 0;
const GLfloat maxDepth = ctx->DepthMaxF;
EdgeT eMaj, eTop, eBot;
GLfloat oneOverArea;
const SWvertex *vMin, *vMid, *vMax; /* Y(vMin)<=Y(vMid)<=Y(vMax) */
float bf = ((SWcontext *)ctx->swrast_context)->_backface_sign;
const GLint snapMask = ~((0x00000800 / (1 << 4)) - 1); /* for x/y coord snapping */
GLfixed vMin_fx, vMin_fy, vMid_fx, vMid_fy, vMax_fx, vMax_fy;
struct sw_span span;
do { (span).primitive = (0x0009); (span).interpMask = (0); (span).arrayMask = (0); (span).start = 0; (span).end = (0); (span).facing = 0; (span).array = ((SWcontext *)ctx->swrast_context)->SpanArrays; } while (0);
printf("%s()\n", __FUNCTION__);
/*
printf(" %g, %g, %g\n", v0->win[0], v0->win[1], v0->win[2]);
printf(" %g, %g, %g\n", v1->win[0], v1->win[1], v1->win[2]);
printf(" %g, %g, %g\n", v2->win[0], v2->win[1], v2->win[2]);
*/
/* Compute fixed point x,y coords w/ half-pixel offsets and snapping.
* And find the order of the 3 vertices along the Y axis.
*/
{
const GLfixed fy0 = (((int) ((((v0->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v0->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v0->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy1 = (((int) ((((v1->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v1->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v1->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
const GLfixed fy2 = (((int) ((((v2->win[1] - 0.5F) * 2048.0f) >= 0.0F) ? (((v2->win[1] - 0.5F) * 2048.0f) + 0.5F) : (((v2->win[1] - 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
if (fy0 <= fy1) {
if (fy1 <= fy2) {
/* y0 <= y1 <= y2 */
vMin = v0; vMid = v1; vMax = v2;
vMin_fy = fy0; vMid_fy = fy1; vMax_fy = fy2;
}
else if (fy2 <= fy0) {
/* y2 <= y0 <= y1 */
vMin = v2; vMid = v0; vMax = v1;
vMin_fy = fy2; vMid_fy = fy0; vMax_fy = fy1;
}
else {
/* y0 <= y2 <= y1 */
vMin = v0; vMid = v2; vMax = v1;
vMin_fy = fy0; vMid_fy = fy2; vMax_fy = fy1;
bf = -bf;
}
}
else {
if (fy0 <= fy2) {
/* y1 <= y0 <= y2 */
vMin = v1; vMid = v0; vMax = v2;
vMin_fy = fy1; vMid_fy = fy0; vMax_fy = fy2;
bf = -bf;
}
else if (fy2 <= fy1) {
/* y2 <= y1 <= y0 */
vMin = v2; vMid = v1; vMax = v0;
vMin_fy = fy2; vMid_fy = fy1; vMax_fy = fy0;
bf = -bf;
}
else {
/* y1 <= y2 <= y0 */
vMin = v1; vMid = v2; vMax = v0;
vMin_fy = fy1; vMid_fy = fy2; vMax_fy = fy0;
}
}
/* fixed point X coords */
vMin_fx = (((int) ((((vMin->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMin->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMin->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMid_fx = (((int) ((((vMid->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMid->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMid->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
vMax_fx = (((int) ((((vMax->win[0] + 0.5F) * 2048.0f) >= 0.0F) ? (((vMax->win[0] + 0.5F) * 2048.0f) + 0.5F) : (((vMax->win[0] + 0.5F) * 2048.0f) - 0.5F)))) & snapMask;
}
/* vertex/edge relationship */
eMaj.v0 = vMin; eMaj.v1 = vMax; /*TODO: .v1's not needed */
eTop.v0 = vMid; eTop.v1 = vMax;
eBot.v0 = vMin; eBot.v1 = vMid;
/* compute deltas for each edge: vertex[upper] - vertex[lower] */
eMaj.dx = ((vMax_fx - vMin_fx) * (1.0F / 2048.0f));
eMaj.dy = ((vMax_fy - vMin_fy) * (1.0F / 2048.0f));
eTop.dx = ((vMax_fx - vMid_fx) * (1.0F / 2048.0f));
eTop.dy = ((vMax_fy - vMid_fy) * (1.0F / 2048.0f));
eBot.dx = ((vMid_fx - vMin_fx) * (1.0F / 2048.0f));
eBot.dy = ((vMid_fy - vMin_fy) * (1.0F / 2048.0f));
/* compute area, oneOverArea and perform backface culling */
{
const GLfloat area = eMaj.dx * eBot.dy - eBot.dx * eMaj.dy;
/* Do backface culling */
if (area * bf < 0.0)
return;
if (IS_INF_OR_NAN(area) || area == 0.0F)
return;
oneOverArea = 1.0F / area;
}
span.facing = ctx->_Facing; /* for 2-sided stencil test */
/* Edge setup. For a triangle strip these could be reused... */
{
eMaj.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eMaj.lines = (((((vMax_fy - eMaj.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eMaj.lines > 0) {
GLfloat dxdy = eMaj.dx / eMaj.dy;
eMaj.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eMaj.adjy = (GLfloat) (eMaj.fsy - vMin_fy); /* SCALED! */
eMaj.fx0 = vMin_fx;
eMaj.fsx = eMaj.fx0 + (GLfixed) (eMaj.adjy * dxdy);
}
else {
return; /*CULLED*/
}
eTop.fsy = (((vMid_fy) + 0x00000800 - 1) & (~0x000007FF));
eTop.lines = (((((vMax_fy - eTop.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eTop.lines > 0) {
GLfloat dxdy = eTop.dx / eTop.dy;
eTop.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eTop.adjy = (GLfloat) (eTop.fsy - vMid_fy); /* SCALED! */
eTop.fx0 = vMid_fx;
eTop.fsx = eTop.fx0 + (GLfixed) (eTop.adjy * dxdy);
}
eBot.fsy = (((vMin_fy) + 0x00000800 - 1) & (~0x000007FF));
eBot.lines = (((((vMid_fy - eBot.fsy) + 0x00000800 - 1) & (~0x000007FF))) >> 11);
if (eBot.lines > 0) {
GLfloat dxdy = eBot.dx / eBot.dy;
eBot.fdxdy = (((int) ((((dxdy) * 2048.0f) >= 0.0F) ? (((dxdy) * 2048.0f) + 0.5F) : (((dxdy) * 2048.0f) - 0.5F))));
eBot.adjy = (GLfloat) (eBot.fsy - vMin_fy); /* SCALED! */
eBot.fx0 = vMin_fx;
eBot.fsx = eBot.fx0 + (GLfixed) (eBot.adjy * dxdy);
}
}
/*
* Conceptually, we view a triangle as two subtriangles
* separated by a perfectly horizontal line. The edge that is
* intersected by this line is one with maximal absolute dy; we
* call it a ``major'' edge. The other two edges are the
* ``top'' edge (for the upper subtriangle) and the ``bottom''
* edge (for the lower subtriangle). If either of these two
* edges is horizontal or very close to horizontal, the
* corresponding subtriangle might cover zero sample points;
* we take care to handle such cases, for performance as well
* as correctness.
*
* By stepping rasterization parameters along the major edge,
* we can avoid recomputing them at the discontinuity where
* the top and bottom edges meet. However, this forces us to
* be able to scan both left-to-right and right-to-left.
* Also, we must determine whether the major edge is at the
* left or right side of the triangle. We do this by
* computing the magnitude of the cross-product of the major
* and top edges. Since this magnitude depends on the sine of
* the angle between the two edges, its sign tells us whether
* we turn to the left or to the right when travelling along
* the major edge to the top edge, and from this we infer
* whether the major edge is on the left or the right.
*
* Serendipitously, this cross-product magnitude is also a
* value we need to compute the iteration parameter
* derivatives for the triangle, and it can be used to perform
* backface culling because its sign tells us whether the
* triangle is clockwise or counterclockwise. In this code we
* refer to it as ``area'' because it's also proportional to
* the pixel area of the triangle.
*/
{
GLint scan_from_left_to_right; /* true if scanning left-to-right */
GLfloat dzdx, dzdy;
/*
* Execute user-supplied setup code
*/
if (ctx->OcclusionResult) { return; }
scan_from_left_to_right = (oneOverArea < 0.0F);
/* compute d?/dx and d?/dy derivatives */
span.interpMask |= 0x008;
{
GLfloat eMaj_dz, eBot_dz;
eMaj_dz = vMax->win[2] - vMin->win[2];
eBot_dz = vMid->win[2] - vMin->win[2];
dzdx = oneOverArea * (eMaj_dz * eBot.dy - eMaj.dy * eBot_dz);
if (dzdx > maxDepth || dzdx < -maxDepth) {
/* probably a sliver triangle */
dzdx = 0.0;
dzdy = 0.0;
}
else {
dzdy = oneOverArea * (eMaj.dx * eBot_dz - eMaj_dz * eBot.dx);
}
if (depthBits <= 16)
span.zStep = (((int) ((((dzdx) * 2048.0f) >= 0.0F) ? (((dzdx) * 2048.0f) + 0.5F) : (((dzdx) * 2048.0f) - 0.5F))));
else
span.zStep = (GLint) dzdx;
}
/*
* We always sample at pixel centers. However, we avoid
* explicit half-pixel offsets in this code by incorporating
* the proper offset in each of x and y during the
* transformation to window coordinates.
*
* We also apply the usual rasterization rules to prevent
* cracks and overlaps. A pixel is considered inside a
* subtriangle if it meets all of four conditions: it is on or
* to the right of the left edge, strictly to the left of the
* right edge, on or below the top edge, and strictly above
* the bottom edge. (Some edges may be degenerate.)
*
* The following discussion assumes left-to-right scanning
* (that is, the major edge is on the left); the right-to-left
* case is a straightforward variation.
*
* We start by finding the half-integral y coordinate that is
* at or below the top of the triangle. This gives us the
* first scan line that could possibly contain pixels that are
* inside the triangle.
*
* Next we creep down the major edge until we reach that y,
* and compute the corresponding x coordinate on the edge.
* Then we find the half-integral x that lies on or just
* inside the edge. This is the first pixel that might lie in
* the interior of the triangle. (We won't know for sure
* until we check the other edges.)
*
* As we rasterize the triangle, we'll step down the major
* edge. For each step in y, we'll move an integer number
* of steps in x. There are two possible x step sizes, which
* we'll call the ``inner'' step (guaranteed to land on the
* edge or inside it) and the ``outer'' step (guaranteed to
* land on the edge or outside it). The inner and outer steps
* differ by one. During rasterization we maintain an error
* term that indicates our distance from the true edge, and
* select either the inner step or the outer step, whichever
* gets us to the first pixel that falls inside the triangle.
*
* All parameters (z, red, etc.) as well as the buffer
* addresses for color and z have inner and outer step values,
* so that we can increment them appropriately. This method
* eliminates the need to adjust parameters by creeping a
* sub-pixel amount into the triangle at each scanline.
*/
{
int subTriangle;
GLfixed fx;
GLfixed fxLeftEdge = 0, fxRightEdge = 0;
GLfixed fdxLeftEdge = 0, fdxRightEdge = 0;
GLfixed fdxOuter;
int idxOuter;
float dxOuter;
GLfixed fError = 0, fdError = 0;
float adjx, adjy;
GLfixed fy;
GLushort *zRow = 0;
int dZRowOuter = 0, dZRowInner; /* offset in bytes */
GLfixed fz = 0, fdzOuter = 0, fdzInner;
for (subTriangle=0; subTriangle<=1; subTriangle++) {
EdgeT *eLeft, *eRight;
int setupLeft, setupRight;
int lines;
if (subTriangle==0) {
/* bottom half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eBot;
lines = eRight->lines;
setupLeft = 1;
setupRight = 1;
}
else {
eLeft = &eBot;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 1;
}
}
else {
/* top half */
if (scan_from_left_to_right) {
eLeft = &eMaj;
eRight = &eTop;
lines = eRight->lines;
setupLeft = 0;
setupRight = 1;
}
else {
eLeft = &eTop;
eRight = &eMaj;
lines = eLeft->lines;
setupLeft = 1;
setupRight = 0;
}
if (lines == 0)
return;
}
if (setupLeft && eLeft->lines > 0) {
const SWvertex *vLower;
GLfixed fsx = eLeft->fsx;
fx = (((fsx) + 0x00000800 - 1) & (~0x000007FF));
fError = fx - fsx - 0x00000800;
fxLeftEdge = fsx - 1;
fdxLeftEdge = eLeft->fdxdy;
fdxOuter = ((fdxLeftEdge - 1) & (~0x000007FF));
fdError = fdxOuter - fdxLeftEdge + 0x00000800;
idxOuter = ((fdxOuter) >> 11);
dxOuter = (float) idxOuter;
(void) dxOuter;
fy = eLeft->fsy;
span.y = ((fy) >> 11);
adjx = (float)(fx - eLeft->fx0); /* SCALED! */
adjy = eLeft->adjy; /* SCALED! */
vLower = eLeft->v0;
/*
* Now we need the set of parameter (z, color, etc.) values at
* the point (fx, fy). This gives us properly-sampled parameter
* values that we can step from pixel to pixel. Furthermore,
* although we might have intermediate results that overflow
* the normal parameter range when we step temporarily outside
* the triangle, we shouldn't overflow or underflow for any
* pixel that's actually inside the triangle.
*/
{
GLfloat z0 = vLower->win[2];
if (depthBits <= 16) {
/* interpolate fixed-pt values */
GLfloat tmp = (z0 * 2048.0f +
dzdx * adjx + dzdy * adjy) + 0x00000400;
if (tmp < 0xffffffff / 2)
fz = (GLfixed) tmp;
else
fz = 0xffffffff / 2;
fdzOuter = (((int) ((((dzdy + dxOuter * dzdx) * 2048.0f) >= 0.0F) ? (((dzdy + dxOuter * dzdx) * 2048.0f) + 0.5F) : (((dzdy + dxOuter * dzdx) * 2048.0f) - 0.5F))));
}
else {
/* interpolate depth values exactly */
fz = (GLint) (z0 + dzdx * ((adjx) * (1.0F / 2048.0f))
+ dzdy * ((adjy) * (1.0F / 2048.0f)));
fdzOuter = (GLint) (dzdy + dxOuter * dzdx);
}
zRow = (GLushort *)
_mesa_zbuffer_address(ctx, ((fxLeftEdge) >> 11), span.y);
dZRowOuter = (ctx->DrawBuffer->Width + idxOuter) * sizeof(GLushort);
}
} /*if setupLeft*/
if (setupRight && eRight->lines>0) {
fxRightEdge = eRight->fsx - 1;
fdxRightEdge = eRight->fdxdy;
}
if (lines==0) {
continue;
}
/* Rasterize setup */
dZRowInner = dZRowOuter + sizeof(GLushort);
fdzInner = fdzOuter + span.zStep;
while (lines > 0) {
/* initialize the span interpolants to the leftmost value */
/* ff = fixed-pt fragment */
const GLint right = ((fxRightEdge) >> 11);
span.x = ((fxLeftEdge) >> 11);
if (right <= span.x)
span.end = 0;
else
span.end = right - span.x;
span.z = fz;
/* This is where we actually generate fragments */
if (span.end > 0) {
GLuint i; for (i = 0; i < span.end; i++) { GLdepth z = ((span.z) >> fixedToDepthShift); if (z < zRow[i]) { ctx->OcclusionResult = 0x1; return; } span.z += span.zStep; };
}
/*
* Advance to the next scan line. Compute the
* new edge coordinates, and adjust the
* pixel-center x coordinate so that it stays
* on or inside the major edge.
*/
(span.y)++;
lines--;
fxLeftEdge += fdxLeftEdge;
fxRightEdge += fdxRightEdge;
fError += fdError;
if (fError >= 0) {
fError -= 0x00000800;
zRow = (GLushort *) ((GLubyte *) zRow + dZRowOuter);
fz += fdzOuter;
}
else {
zRow = (GLushort *) ((GLubyte *) zRow + dZRowInner);
fz += fdzInner;
}
} /*while lines>0*/
} /* for subTriangle */
}
}
}
static void
nodraw_triangle( GLcontext *ctx,
const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
(void) (ctx && v0 && v1 && v2);
}
/*
* This is used when separate specular color is enabled, but not
* texturing. We add the specular color to the primary color,
* draw the triangle, then restore the original primary color.
* Inefficient, but seldom needed.
*/
void _swrast_add_spec_terms_triangle( GLcontext *ctx,
const SWvertex *v0,
const SWvertex *v1,
const SWvertex *v2 )
{
SWvertex *ncv0 = (SWvertex *)v0; /* drop const qualifier */
SWvertex *ncv1 = (SWvertex *)v1;
SWvertex *ncv2 = (SWvertex *)v2;
GLint rSum, gSum, bSum;
GLchan c[3][4];
/* save original colors */
{ (c[0])[0] = (ncv0->color)[0]; (c[0])[1] = (ncv0->color)[1]; (c[0])[2] = (ncv0->color)[2]; (c[0])[3] = (ncv0->color)[3]; };
{ (c[1])[0] = (ncv1->color)[0]; (c[1])[1] = (ncv1->color)[1]; (c[1])[2] = (ncv1->color)[2]; (c[1])[3] = (ncv1->color)[3]; };
{ (c[2])[0] = (ncv2->color)[0]; (c[2])[1] = (ncv2->color)[1]; (c[2])[2] = (ncv2->color)[2]; (c[2])[3] = (ncv2->color)[3]; };
/* sum v0 */
rSum = ncv0->color[0] + ncv0->specular[0];
gSum = ncv0->color[1] + ncv0->specular[1];
bSum = ncv0->color[2] + ncv0->specular[2];
ncv0->color[0] = ( (rSum)<(255) ? (rSum) : (255) );
ncv0->color[1] = ( (gSum)<(255) ? (gSum) : (255) );
ncv0->color[2] = ( (bSum)<(255) ? (bSum) : (255) );
/* sum v1 */
rSum = ncv1->color[0] + ncv1->specular[0];
gSum = ncv1->color[1] + ncv1->specular[1];
bSum = ncv1->color[2] + ncv1->specular[2];
ncv1->color[0] = ( (rSum)<(255) ? (rSum) : (255) );
ncv1->color[1] = ( (gSum)<(255) ? (gSum) : (255) );
ncv1->color[2] = ( (bSum)<(255) ? (bSum) : (255) );
/* sum v2 */
rSum = ncv2->color[0] + ncv2->specular[0];
gSum = ncv2->color[1] + ncv2->specular[1];
bSum = ncv2->color[2] + ncv2->specular[2];
ncv2->color[0] = ( (rSum)<(255) ? (rSum) : (255) );
ncv2->color[1] = ( (gSum)<(255) ? (gSum) : (255) );
ncv2->color[2] = ( (bSum)<(255) ? (bSum) : (255) );
/* draw */
((SWcontext *)ctx->swrast_context)->SpecTriangle( ctx, ncv0, ncv1, ncv2 );
/* restore original colors */
{ (ncv0->color)[0] = (c[0])[0]; (ncv0->color)[1] = (c[0])[1]; (ncv0->color)[2] = (c[0])[2]; (ncv0->color)[3] = (c[0])[3]; };
{ (ncv1->color)[0] = (c[1])[0]; (ncv1->color)[1] = (c[1])[1]; (ncv1->color)[2] = (c[1])[2]; (ncv1->color)[3] = (c[1])[3]; };
{ (ncv2->color)[0] = (c[2])[0]; (ncv2->color)[1] = (c[2])[1]; (ncv2->color)[2] = (c[2])[2]; (ncv2->color)[3] = (c[2])[3]; };
}
/*
* Determine which triangle rendering function to use given the current
* rendering context.
*
* Please update the summary flag _SWRAST_NEW_TRIANGLE if you add or
* remove tests to this code.
*/
void
_swrast_choose_triangle( GLcontext *ctx )
{
SWcontext *swrast = ((SWcontext *)ctx->swrast_context);
const GLboolean rgbmode = ctx->Visual.rgbMode;
if (ctx->Polygon.CullFlag &&
ctx->Polygon.CullFaceMode == 0x0408) {
swrast->Triangle = nodraw_triangle;;
return;
}
if (ctx->RenderMode==0x1C00) {
if (ctx->Polygon.SmoothFlag) {
_mesa_set_aa_triangle_function(ctx);
;
return;
}
if (ctx->Depth.OcclusionTest &&
ctx->Depth.Test &&
ctx->Depth.Mask == 0x0 &&
ctx->Depth.Func == 0x0201 &&
!ctx->Stencil.Enabled) {
if ((rgbmode &&
ctx->Color.ColorMask[0] == 0 &&
ctx->Color.ColorMask[1] == 0 &&
ctx->Color.ColorMask[2] == 0 &&
ctx->Color.ColorMask[3] == 0)
||
(!rgbmode && ctx->Color.IndexMask == 0)) {
swrast->Triangle = occlusion_zless_triangle;;
return;
}
}
if (ctx->Texture._EnabledUnits) {
/* Ugh, we do a _lot_ of tests to pick the best textured tri func */
const struct gl_texture_object *texObj2D;
const struct gl_texture_image *texImg;
GLenum minFilter, magFilter, envMode;
GLint format;
texObj2D = ctx->Texture.Unit[0].Current2D;
texImg = texObj2D ? texObj2D->Image[texObj2D->BaseLevel] : 0;
format = texImg ? texImg->TexFormat->MesaFormat : -1;
minFilter = texObj2D ? texObj2D->MinFilter : (GLenum) 0;
magFilter = texObj2D ? texObj2D->MagFilter : (GLenum) 0;
envMode = ctx->Texture.Unit[0].EnvMode;
/* First see if we can used an optimized 2-D texture function */
if (ctx->Texture._EnabledUnits == 1
&& ctx->Texture.Unit[0]._ReallyEnabled == 0x02
&& texObj2D->WrapS==0x2901
&& texObj2D->WrapT==0x2901
&& texImg->Border==0
&& texImg->Width == texImg->RowStride
&& (format == MESA_FORMAT_RGB || format == MESA_FORMAT_RGBA)
&& minFilter == magFilter
&& ctx->Light.Model.ColorControl == 0x81F9
&& ctx->Texture.Unit[0].EnvMode != 0x8570) {
if (ctx->Hint.PerspectiveCorrection==0x1101) {
if (minFilter == 0x2600
&& format == MESA_FORMAT_RGB
&& (envMode == 0x1E01 || envMode == 0x2101)
&& ((swrast->_RasterMask == (0x004 | 0x1000)
&& ctx->Depth.Func == 0x0201
&& ctx->Depth.Mask == 0x1)
|| swrast->_RasterMask == 0x1000)
&& ctx->Polygon.StippleFlag == 0x0) {
if (swrast->_RasterMask == (0x004 | 0x1000)) {
swrast->Triangle = simple_z_textured_triangle;
}
else {
swrast->Triangle = simple_textured_triangle;
}
}
else {
swrast->Triangle = affine_textured_triangle;
}
}
else {
swrast->Triangle = persp_textured_triangle;
}
}
else {
/* general case textured triangles */
if (ctx->Texture._EnabledUnits > 1) {
swrast->Triangle = multitextured_triangle;
}
else {
swrast->Triangle = general_textured_triangle;
}
}
}
else {
;
if (ctx->Light.ShadeModel==0x1D01) {
/* smooth shaded, no texturing, stippled or some raster ops */
if (rgbmode) {
swrast->Triangle = smooth_rgba_triangle;
}
else {
swrast->Triangle = smooth_ci_triangle;
}
}
else {
/* flat shaded, no texturing, stippled or some raster ops */
if (rgbmode) {
swrast->Triangle = flat_rgba_triangle;
}
else {
swrast->Triangle = flat_ci_triangle;;
}
}
}
}
else if (ctx->RenderMode==0x1C01) {
swrast->Triangle = _mesa_feedback_triangle;;
}
else {
/* GL_SELECT mode */
swrast->Triangle = _mesa_select_triangle;;
}
}
| 47.319386 | 2,077 | 0.5178 | [
"render",
"model",
"3d"
] |
8c38965182365a38c1f4983c14e0b5b7edeb45d0 | 879 | cpp | C++ | src/MySQLResult.cpp | mark-grimes/CppSQL | 6e34c1bdf46beff92f1c5eb6a97ae52d1f0a19ac | [
"MIT"
] | null | null | null | src/MySQLResult.cpp | mark-grimes/CppSQL | 6e34c1bdf46beff92f1c5eb6a97ae52d1f0a19ac | [
"MIT"
] | null | null | null | src/MySQLResult.cpp | mark-grimes/CppSQL | 6e34c1bdf46beff92f1c5eb6a97ae52d1f0a19ac | [
"MIT"
] | null | null | null | #include "cppsql/MySQLResult.h"
#include <vector>
cppsql::MySQLResult::MySQLResult( MYSQL_RES* pResult )
: pResult_(pResult)
{
if(pResult_==nullptr) throw std::runtime_error("Got null result pointer");
}
cppsql::MySQLResult::~MySQLResult()
{
mysql_free_result(pResult_);
}
int cppsql::MySQLResult::numberOfFields()
{
return mysql_num_fields(pResult_);
}
void cppsql::MySQLResult::showResults( std::function<bool(int,const char* const[],const char* const[])> resultsCallback )
{
int num_fields=numberOfFields();
MYSQL_FIELD* fields=mysql_fetch_fields(pResult_);
std::vector<const char*> fieldNames(num_fields);
for( size_t index=0; index<num_fields; ++index ) fieldNames[index]=fields[index].name;
MYSQL_ROW row;
bool keepGoing=true;
while( (row=mysql_fetch_row(pResult_)) && keepGoing )
{
keepGoing=resultsCallback( num_fields, row, fieldNames.data() );
}
}
| 25.114286 | 121 | 0.748578 | [
"vector"
] |
8c3bff2f71761b665cc392589586ccb233c80c7d | 12,096 | cpp | C++ | DAISGram.cpp | paolodurante94/DAISGram | aaab107d4abd0b0eea38f2c13899a35833258fd1 | [
"MIT"
] | 1 | 2021-09-06T17:51:50.000Z | 2021-09-06T17:51:50.000Z | DAISGram.cpp | paolodurante94/DAISGram | aaab107d4abd0b0eea38f2c13899a35833258fd1 | [
"MIT"
] | null | null | null | DAISGram.cpp | paolodurante94/DAISGram | aaab107d4abd0b0eea38f2c13899a35833258fd1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "dais_exc.h"
#include "tensor.h"
#include "libbmp.h"
#include "DAISGram.h"
using namespace std;
DAISGram::DAISGram(){
}
DAISGram::~DAISGram(){
}
/**
* Load a bitmap from file
*
* @param filename String containing the path of the file
*/
void DAISGram::load_image(string filename){
BmpImg img = BmpImg();
img.read(filename.c_str());
const int h = img.get_height();
const int w = img.get_width();
data = Tensor (h, w, 3, 0.0);
for(int i=0;i<img.get_height();i++){
for(int j=0;j<img.get_width();j++){
data(i,j,0) = (float) img.red_at(j,i);
data(i,j,1) = (float) img.green_at(j,i);
data(i,j,2) = (float) img.blue_at(j,i);
}
}
}
/**
* Save a DAISGram object to a bitmap file.
*
* Data is clamped to 0,255 before saving it.
*
* @param filename String containing the path where to store the image.
*/
void DAISGram::save_image(string filename){
data.clamp(0,255);
BmpImg img = BmpImg(getCols(), getRows());
img.init(getCols(), getRows());
for(int i=0;i<getRows();i++){
for(int j=0;j<getCols();j++){
img.set_pixel(j,i,(unsigned char) data(i,j,0),(unsigned char) data(i,j,1),(unsigned char) data(i,j,2));
}
}
img.write(filename);
}
/**
* Get rows
*
* @return returns the number of rows in the image
*/
int DAISGram::getRows(){
return data.rows();
}
/**
* Get columns
*
* @return returns the number of columns in the image
*/
int DAISGram::getCols(){
return data.cols();
}
/**
* Get depth
*
* @return returns the number of channels in the image
*/
int DAISGram::getDepth()
{
return data.depth();
}
/**
* Brighten the image
*
* It sums the bright variable to all the values in the image.
*
* Before returning the image, the corresponding tensor should be clamped in [0,255]
*
* @param bright the amount of bright to add (if negative the image gets darker)
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::brighten(float bright){
DAISGram res;
res.data.init(getRows(),getCols(),getDepth());
res.data=data+(bright);
res.data.clamp(0, 255);
return res;
}
/**
* Create a grayscale version of the object
*
* A grayscale image is produced by substituting each pixel with its average on all the channel
*
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::grayscale(){
DAISGram res;
float sum, avg;
res.data.init(getRows(),getCols(),getDepth());
for(int i=0; i < getRows(); i++){
for(int j=0; j < getCols(); j++){
sum=0;
for (int k=0; k < getDepth(); k++){
sum += data(i, j, k);
}
avg = sum / getDepth();
for (int k=0; k < getDepth(); k++){
res.data(i,j,k)=avg;
}
}
}
return res;
}
/**
* Create a Warhol effect on the image
*
* This function returns a composition of 4 different images in which the:
* - top left is the original image
* - top right is the original image in which the Red and Green channel are swapped
* - bottom left is the original image in which the Blue and Green channel are swapped
* - bottom right is the original image in which the Red and Blue channel are swapped
*
* The output image is twice the dimensions of the original one.
*
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::warhol(){
int r, c, d;
r = getRows();
c = getCols();
d = getDepth();
DAISGram res;
res.data.init(2*r, 2*c, d);
for (int i = 0; i < r; i++){
for (int j = 0; j < c; j++){
for (int k = 0; k < d; k++){
res.data(i,j,k)=data(i, j, k);
}
}
}
for (int i = 0; i < r; i++){
for (int j = c; j < 2*c; j++){
for (int k = 0; k < d; k++){
if (k == 0) {
res.data(i,j,k)=data(i, j-c, 1);
} else if (k == 1) {
res.data(i,j,k)=data(i, j-c, 0);
} else {
res.data(i,j,k)=data(i, j-c, 2);
}
}
}
}
for (int i = r; i < 2*r; i++){
for (int j = 0; j < c; j++){
for (int k = 0; k < d; k++){
if (k == 0) {
res.data(i,j,k)=data(i-r, j, 0);
} else if (k == 1) {
res.data(i,j,k)=data(i-r, j, 2);
} else {
res.data(i,j,k)=data(i-r, j, 1);
}
}
}
}
for (int i = r; i < 2*r; i++){
for (int j = c; j < 2*c; j++){
for (int k = 0; k < d; k++){
if (k == 0) {
res.data(i,j,k)=data(i-r, j-c, 2);
} else if (k == 1) {
res.data(i,j,k)=data(i-r, j-c, 1);
} else {
res.data(i,j,k)=data(i-r, j-c, 0);
}
}
}
}
return res;
}
/**
* Sharpen the image
*
* This function makes the image sharper by convolving it with a sharp filter
*
* filter[3][3]
* 0 -1 0
* -1 5 -1
* 0 -1 0
*
* Before returning the image, the corresponding tensor should be clamped in [0,255]
*
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::sharpen(){
DAISGram res;
float s[]={ 0,-1, 0, -1, 5,-1, 0,-1, 0};
Tensor filter;
filter.init(3,3,3);
for(int i=0; i<filter.rows(); i++){
for(int j=0; j<filter.cols(); j++){
for(int k=0; k<filter.depth(); k++){
filter(i,j,k)=s[i*filter.cols()+j];
}
}
}
res.data=data.convolve(filter);
res.data.clamp(0, 255);
return res;
}
/**
* Emboss the image
*
* This function makes the image embossed (a light 3D effect) by convolving it with an
* embossing filter
*
* filter[3][3]
* -2 -1 0
* -1 1 1
* 0 1 2
*
* Before returning the image, the corresponding tensor should be clamped in [0,255]
*
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::emboss(){
DAISGram res;
float s[]={-2,-1, 0, -1, 1, 1, 0, 1, 2};
Tensor filter;
filter.init(3,3,3);
for(int i=0; i<filter.rows(); i++){
for(int j=0; j<filter.cols(); j++){
for(int k=0; k<filter.depth(); k++){
filter(i,j,k)=s[i*filter.cols()+j];
}
}
}
res.data=data.convolve(filter);
res.data.clamp(0, 255);
return res;
}
/**
* Smooth the image
*
* This function remove the noise in an image using convolution and an average filter
* of size h*h:
*
* c = 1/(h*h)
*
* filter[3][3]
* c c c
* c c c
* c c c
*
* @param h the size of the filter
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::smooth(int h){
DAISGram res=DAISGram();
float c = 1.0/(h*h);
cout << c << endl;
Tensor supp;
supp.init(h, h, this->data.depth(), c);
for(int i=0; i<supp.rows(); i++){
for(int j=0; j<supp.cols(); j++){
for(int k=0; k<supp.depth(); k++){
cout << supp(i,j,k) << endl;
}
}
}
res.data=data.convolve(supp);
return res;
}
/**
* Edges of an image
*
* This function extract the edges of an image by using the convolution
* operator and the following filter
*
*
* filter[3][3]
* -1 -1 -1
* -1 8 -1
* -1 -1 -1
*
* Remeber to convert the image to grayscale before running the convolution.
*
* Before returning the image, the corresponding tensor should be clamped in [0,255]
*
* @return returns a new DAISGram containing the modified object
*/
DAISGram DAISGram::edge(){
DAISGram res;
DAISGram grayed;
float s[]={-1,-1,-1,-1, 8,-1,-1,-1,-1};
Tensor filter;
filter.init(3,3,3);
for(int i=0; i<filter.rows(); i++){
for(int j=0; j<filter.cols(); j++){
for(int k=0; k<filter.depth(); k++){
filter(i,j,k)=s[i*filter.cols()+j];
}
}
}
grayed=grayscale();
res.data=grayed.data.convolve(filter);
res.data.clamp(0, 255);
return res;
}
/**
* Blend with another image
*
* This function generate a new DAISGram which is the composition
* of the object and another DAISGram object
*
* The composition follows this convex combination:
* results = alpha*this + (1-alpha)*rhs
*
* rhs and this obejct MUST have the same dimensions.
*
* @param rhs The second image involved in the blending
* @param alpha The parameter of the convex combination
* @return returns a new DAISGram containing the blending of the two images.
*/
DAISGram DAISGram::blend(const DAISGram & rhs, float alpha){
DAISGram result;
result.data.init(rhs.data.rows(), rhs.data.cols(), rhs.data.depth());
if(getRows()==rhs.data.rows() && getCols()==rhs.data.cols() && getDepth()==rhs.data.depth()){
DAISGram a, b;
a.data=data*(alpha);
b.data=rhs.data*(1.0-alpha);
result.data=a.data+b.data;
}
else{
throw(dimension_mismatch());
}
return result;
}
/**filter_odd_dimensions();
* Green Screen
*
* This function substitutes a pixel with the corresponding one in a background image
* if its colors are in the surrounding (+- threshold) of a given color (rgb).
*
* (rgb - threshold) <= pixel <= (rgb + threshold)
*
*
* @param bkg The second image used as background
* @param rgb[] The color to substitute (rgb[0] = RED, rgb[1]=GREEN, rgb[2]=BLUE)
* @param threshold[] The threshold to add/remove for each color (threshold[0] = RED, threshold[1]=GREEN, threshold[2]=BLUE)
* @return returns a new DAISGram containing the result.
*/
DAISGram DAISGram::greenscreen(DAISGram & bkg, int rgb[], float threshold[]){
DAISGram res;
res.data = data;
for(int i=0; i<getRows(); i++){
for(int j=0; j<getCols(); j++){
if ( data(i,j,0) >= ( rgb[0] - threshold[0] ) && data(i,j,0) <= ( rgb[0] + threshold[0] ) &&
data(i,j,1) >= ( rgb[1] - threshold[1] ) && data(i,j,1) <= ( rgb[1] + threshold[1] ) &&
data(i,j,2) >= ( rgb[2] - threshold[2] ) && data(i,j,2) <= ( rgb[2] + threshold[2] ) ) {
for(int k=0; k<getDepth(); k++){
res.data(i,j,k) = bkg.data(i,j,k);
}
}
}
}
return res;
}
/**
* Equalize
*
* Stretch the distribution of colors of the image in order to use the full range of intesities.
*
* See https://it.wikipedia.org/wiki/Equalizzazione_dell%27istogramma
*
* @return returns a new DAISGram containing the equalized image.
*/
DAISGram DAISGram::equalize(){
float cdf_min, cdf_v;
DAISGram res;
res.data.init(getRows(), getCols(), getDepth());
for(int k=0; k<getDepth(); k++){
cdf_value* temp;
int size=0;
temp = data.cdf(k, size);
cdf_min = temp[0].cdf;
for(int i=0; i<getRows(); i++){
for(int j=0; j<getCols(); j++){
int l = 0;
while (temp[l].valore != data(i,j,k) && l < size){
l++;
}
cdf_v = temp[l].cdf;
res.data(i,j,k) = ( (cdf_v - cdf_min) / ( (getRows() * getCols() ) - 1 ) ) * (256 - 1);
}
}
delete [] temp;
}
return res;
}
/**
* Generate Random Image
*
* Generate a random image from nois
*
* @param h height of the image
* @param w width of the image
* @param d number of channels
* @return returns a new DAISGram containing the generated image.
*/
void DAISGram::generate_random(int h, int w, int d){
data = Tensor(h,w,d,0.0);
data.init_random(128,50);
data.rescale(255);
}
| 26.352941 | 134 | 0.535632 | [
"object",
"3d"
] |
8c3f0614d1988086e9adf5f4575dac0189464439 | 5,995 | cpp | C++ | Isetta/IsettaTestbed/KnightGame/Level/KnightMainLevel.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | 2 | 2018-09-05T17:51:47.000Z | 2018-09-05T19:35:25.000Z | Isetta/IsettaTestbed/KnightGame/Level/KnightMainLevel.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | null | null | null | Isetta/IsettaTestbed/KnightGame/Level/KnightMainLevel.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Isetta
*/
#include "KnightMainLevel.h"
#include "Components/AxisDrawer.h"
#include "Components/Editor/EditorComponent.h"
#include "KnightGame/Constants.h"
#include "KnightGame/Gameplay/Enemy.h"
#include "KnightGame/Gameplay/FireballCircle.h"
#include "KnightGame/Gameplay/FollowComponent.h"
#include "KnightGame/Gameplay/KnightController.h"
#include "KnightGame/Gameplay/ScoreManager.h"
#include "KnightGame/Gameplay/ScreenShifter.h"
#include "KnightGame/Gameplay/SpinAttack.h"
#include "KnightGame/Gameplay/SwordController.h"
using namespace Isetta;
namespace KnightGame {
using LightProperty = LightComponent::Property;
void KnightMainLevel::Load() {
// Turn off Logger messages for Memory (works for other channels)
Logger::channelMask.set(static_cast<int>(Debug::Channel::Memory), false);
// Create a layer with name, store int
knightLayer = Layers::NewLayer(KNIGHT_LAYER);
// Ignore collisions between knightLayer collisions
Collisions::SetIgnoreLayerCollision(knightLayer, knightLayer);
Entity* cameraEntity = Entity::Instantiate("Camera");
CameraComponent* camComp = cameraEntity->AddComponent<CameraComponent>();
cameraEntity->SetTransform(Math::Vector3{0, 5, 10}, Math::Vector3{-15, 0, 0},
Math::Vector3::one);
cameraEntity->AddComponent<AudioListener>();
// Custom component for shifting to screen right
cameraEntity->AddComponent<ScreenShifter>();
// cameraEntity->AddComponent<FlyController>();
Entity* lightEntity = Entity::Instantiate("Light");
LightComponent* lightComp = lightEntity->AddComponent<LightComponent>();
lightEntity->SetTransform(Math::Vector3{0, 200, 600}, Math::Vector3::zero,
Math::Vector3::one);
// Debug Components
// Entity* editor{Entity::Instantiate("Editor")};
// editor->AddComponent<GridComponent>();
// editor->AddComponent<EditorComponent>();
// Destructor Wall
Entity* leftWall = Entity::Instantiate("Left Wall");
// BoxCollider(center, size)
BoxCollider* leftWallBox = leftWall->AddComponent<BoxCollider>(
Math::Vector3{-8, 1.5f, 0}, Math::Vector3{1, 3, 10});
// Mass is moveable
leftWallBox->mass = 100000;
// Handler is callback holder
CollisionHandler* handler = leftWall->AddComponent<CollisionHandler>();
leftWall->AddComponent<ScreenShifter>();
// Handler callback collider OnEnter
handler->RegisterOnEnter([](Collider* const collider) {
// Check for KnightController component
if (collider->entity->GetComponent<KnightController>()) {
// Destroy entity
Entity::Destroy(collider->entity);
// Create Event
EventObject eventObject{
GAMEOVER_EVENT, Time::GetFrameCount(), EventPriority::HIGH, {}};
// RaiseEvent
Isetta::Events::Instance().RaiseImmediateEvent(eventObject);
} else {
Enemy* enemy;
enemy = collider->entity->GetComponent<Enemy>();
if (enemy)
enemy->Reset();
else {
collider->entity->transform->SetLocalPos(Math::Vector3::zero);
enemy = collider->entity->GetComponentInParent<Enemy>();
if (enemy) enemy->Reset();
}
}
});
// Score Manager entity
Entity* score = Entity::Instantiate("Score");
score->AddComponent<ScoreManager>();
// Knight Entity (mesh + animation)
Entity* knight = Entity::Instantiate("Knight");
// Set layer (used for collision & comparison)
knight->SetLayer(knightLayer);
MeshComponent* knightMesh =
knight->AddComponent<MeshComponent>(KNIGHT_PATH + "idle.scene.xml");
AnimationComponent* animation =
knight->AddComponent<AnimationComponent>(knightMesh);
knight->AddComponent<CapsuleCollider>(Math::Vector3{0, 0.9f, 0.2f});
// Knight movement
KnightController* knightController = knight->AddComponent<KnightController>();
// Flame attack
SpinAttack* spin = knight->AddComponent<SpinAttack>();
// Camera follow entity on true axes (not used for game)
// bool follow[3] = {true, false, false};
// cameraEntity->AddComponent<FollowComponent>(knightMesh, follow);
// Sword (mesh)
Entity* sword = Entity::Instantiate("Sword");
sword->SetLayer(knightLayer);
// Set parent
sword->transform->SetParent(knight->transform);
sword->AddComponent<MeshComponent>(KNIGHT_PATH + "sword_aligned.scene.xml");
// Sword controller
sword->AddComponent<SwordController>(knightMesh, knightController);
Entity* swordCol = Entity::Instantiate("Sword Collider");
swordCol->SetLayer(knightLayer);
swordCol->transform->SetParent(sword->transform);
// Set local rotation (relative to parent)
swordCol->transform->SetLocalRot(Math::Vector3{0, 0, 90.f});
// Set local position (relative to parent)
swordCol->transform->SetLocalPos(-Math::Vector3::left);
swordCol->AddComponent<AxisDrawer>();
BoxCollider* swordBox = swordCol->AddComponent<BoxCollider>(
Math::Vector3::zero, Math::Vector3{0.2f, 2.3f, 0.2f});
swordBox->isTrigger = true;
// Fireball (particle)
Entity* fireball = Entity::Instantiate("Fireball");
fireball->AddComponent<ParticleSystemComponent, false>();
// Fireball action
FireballCircle* fireCircle =
fireball->AddComponent<FireballCircle, false>(knight->transform, spin);
// Sword audio
AudioClip* const swordClip =
AudioClip::Load("KnightGame\\Audio\\sword.aiff", "sword");
// Pool entities
for (int i = 0; i < enemyPool; i++) {
// Create capsule primitive with collider
Entity* enemyEntity = Primitive::Create(Primitive::Type::Capsule, true);
enemyEntity->SetTransform(Math::Vector3{
3.f + i * 3.f, 1.f, (2.f * Math::Random::GetRandom01() - 1.f) * 5.f});
// AudioSource: 3D positioned
enemyEntity->AddComponent<AudioSource>(0b001, swordClip);
CollisionHandler* handler = enemyEntity->AddComponent<CollisionHandler>();
// Sets as entity
Enemy* enemy = enemyEntity->AddComponent<Enemy>(handler, swordClip);
fireCircle->enemies.push_back(enemy);
}
}
} // namespace KnightGame
| 39.440789 | 80 | 0.709758 | [
"mesh",
"transform",
"3d"
] |
8c47f1e48aad93657e1ba2eb779504d952c21f3d | 5,478 | cpp | C++ | IPZ_Client/src/camera.cpp | Dawid-Olcha/IPZ_Project | 83d1b5809635774b61c65df74611680147576b0d | [
"MIT"
] | null | null | null | IPZ_Client/src/camera.cpp | Dawid-Olcha/IPZ_Project | 83d1b5809635774b61c65df74611680147576b0d | [
"MIT"
] | null | null | null | IPZ_Client/src/camera.cpp | Dawid-Olcha/IPZ_Project | 83d1b5809635774b61c65df74611680147576b0d | [
"MIT"
] | null | null | null | #include "camera.h"
#include "application.h"
#include "gtx/quaternion.hpp"
#include "gtx/transform.hpp"
Camera::Camera(float fov, float aspectRatio, float nearClip, float farClip)
:m_fov(fov), m_aspectRatio(aspectRatio), m_nearClip(nearClip), m_farClip(farClip)
{
updateProjMat();
updateViewMat();
onCreate();
}
void Camera::move(vec3 vec)
{
m_pos += vec;
}
void Camera::rotateAroundY(vec3 point, float degree)
{
m_pos.x = point.x + (m_pos.x - point.x)*cos(degree) - (m_pos.z-point.z)*sin(degree);
m_pos.z = point.x + (m_pos.x - point.x)*sin(degree) + (m_pos.z-point.z)*cos(degree);
}
void Camera::rotateAroundX(vec3 point, float degree)
{
m_pos.x = point.x + (m_pos.x - point.x)*cos(degree) - (m_pos.y-point.y)*sin(degree);
m_pos.y = point.x + (m_pos.x - point.x)*sin(degree) + (m_pos.y-point.y)*cos(degree);
}
void Camera::setRotationX(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({radians(degree), euler.y, euler.z});
}
void Camera::setRotationY(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({euler.x, radians(degree), euler.z});
}
void Camera::setRotationZ(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({euler.x, euler.y, radians(degree)});
}
void Camera::addRotationX(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({euler.x + radians(degree), euler.y, euler.z});
}
void Camera::addRotationY(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({euler.x, euler.y + radians(degree), euler.z});
}
void Camera::addRotationZ(float degree)
{
auto euler = eulerAngles(m_rotation);
m_rotation = quat({euler.x, euler.y, euler.z + radians(degree)});
}
void Camera::pointAt(vec3 pos)
{
m_rotation = quatLookAt(normalize(pos - getPos()), {0,1,0});
}
float Camera::getRotationX()
{
return eulerAngles(m_rotation).x;
}
float Camera::getRotationY()
{
return eulerAngles(m_rotation).y;
}
float Camera::getRotationZ()
{
return eulerAngles(m_rotation).z;
}
mat4 Camera::getViewMatrix()
{
updateViewMat();
return m_viewMat;
}
mat4 Camera::getProjMatrix()
{
updateProjMat();
return m_projMat;
}
mat4 Camera::getViewProjectionMatrix()
{
updateProjMat();
updateViewMat();
return m_projMat*m_viewMat;
}
vec3 Camera::up()
{
return glm::rotate(getRotation(), vec3(0, 1, 0));
}
vec3 Camera::right()
{
return glm::rotate(getRotation(), vec3(1, 0, 0));
}
vec3 Camera::forward()
{
return glm::rotate(getRotation(), vec3(0, 0, -1));
}
void Camera::onUpdate(float dt)
{
auto hwnd = App::getWindowHandle();
//MOUSE
float offset = (float)App::getMouseScrollChange();
if(offset!=0)
{
float speed = 0.5f;
LOG("offset: %f", offset);
m_pos += offset * speed * forward();
}
vec3 rotationPoint(0,0,0);
if(glfwGetMouseButton(hwnd, GLFW_MOUSE_BUTTON_RIGHT))
{
// The problem is that first when we call this function mouseChange is huge.
// This is a very ugly hack, later we will use glfwSetCursorPosCallback().
auto mChange = App::getMousePosChange();
if(!firstMouseClick)
{
float sens = 0.005f;
glfwSetInputMode(hwnd, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetInputMode(hwnd, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
auto rot = angleAxis(-mChange.y*sens, right());
auto rot2 = angleAxis(-mChange.x*sens, up());
m_pos = rotationPoint + (rot * (m_pos-rotationPoint));
m_pos = rotationPoint + (rot2 * (m_pos-rotationPoint));
pointAt(rotationPoint);
}
else
firstMouseClick = false;
}
else
{
firstMouseClick = true;
glfwSetInputMode(hwnd, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
//KEYBOARD
float rotationSpeed = 100.f;
if(glfwGetKey(hwnd, GLFW_KEY_W))
addRotationX(rotationSpeed*dt);
if(glfwGetKey(hwnd, GLFW_KEY_S))
addRotationX(-rotationSpeed*dt);
if(glfwGetKey(hwnd, GLFW_KEY_A))
addRotationY(rotationSpeed*dt);
if(glfwGetKey(hwnd, GLFW_KEY_D))
addRotationY(-rotationSpeed*dt);
if(glfwGetKey(hwnd, GLFW_KEY_SPACE))
pointAt({0,0,0});
float speed = 3.f;
vec3 moveVec = {0, 0 ,0};
// right click + mouse move = rotate around center (later selection or mouse pos on xz plane)
if(glfwGetKey(hwnd, GLFW_KEY_UP))
moveVec += forward() * speed * dt;
if(glfwGetKey(hwnd, GLFW_KEY_DOWN))
moveVec += -forward() * speed * dt;
if(glfwGetKey(hwnd, GLFW_KEY_RIGHT))
moveVec += right() * speed * dt;
if(glfwGetKey(hwnd, GLFW_KEY_LEFT))
moveVec += -right() * speed * dt;
if(glfwGetKey(hwnd, GLFW_KEY_Q))
moveVec += up() * speed * dt;
if(glfwGetKey(hwnd, GLFW_KEY_Z))
moveVec += -up() * speed * dt;
move(moveVec);
// auto angles = eulerAngles(getRotation());
// LOG("Rotation: x:%f y:%f z:%f Pos: x:%f y:%f z:%f",
// angles.x, angles.y, angles.z, m_pos.x, m_pos.y, m_pos.z);
}
void Camera::onCreate()
{
setPosition(vec3(0,1.2f,0.01f));
pointAt({0,0,0});
}
void Camera::updateViewMat()
{
m_viewMat = translate(mat4(1.0f), m_pos)* toMat4(getRotation());
m_viewMat = inverse(m_viewMat);
}
void Camera::updateProjMat()
{
m_projMat = perspective(m_fov, m_aspectRatio, m_nearClip, m_farClip);
}
| 25.361111 | 97 | 0.638737 | [
"transform"
] |
8c4c456ef5b7d314879160b782e995905c6ae72d | 2,179 | cpp | C++ | head/contrib/llvm/lib/Target/SystemZ/SystemZTargetMachine.cpp | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 17 | 2015-02-04T05:21:14.000Z | 2021-05-30T21:03:48.000Z | head/contrib/llvm/lib/Target/SystemZ/SystemZTargetMachine.cpp | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | head/contrib/llvm/lib/Target/SystemZ/SystemZTargetMachine.cpp | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 3 | 2018-03-18T23:11:44.000Z | 2019-09-05T11:47:19.000Z | //===-- SystemZTargetMachine.cpp - Define TargetMachine for SystemZ -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SystemZTargetMachine.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
extern "C" void LLVMInitializeSystemZTarget() {
// Register the target.
RegisterTargetMachine<SystemZTargetMachine> X(TheSystemZTarget);
}
SystemZTargetMachine::SystemZTargetMachine(const Target &T, StringRef TT,
StringRef CPU, StringRef FS,
const TargetOptions &Options,
Reloc::Model RM,
CodeModel::Model CM,
CodeGenOpt::Level OL)
: LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
Subtarget(TT, CPU, FS),
// Make sure that global data has at least 16 bits of alignment by default,
// so that we can refer to it using LARL. We don't have any special
// requirements for stack variables though.
DL("E-p:64:64:64-i1:8:16-i8:8:16-i16:16-i32:32-i64:64"
"-f32:32-f64:64-f128:64-a0:8:16-n32:64"),
InstrInfo(*this), TLInfo(*this), TSInfo(*this),
FrameLowering(*this, Subtarget) {
}
namespace {
/// SystemZ Code Generator Pass Configuration Options.
class SystemZPassConfig : public TargetPassConfig {
public:
SystemZPassConfig(SystemZTargetMachine *TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {}
SystemZTargetMachine &getSystemZTargetMachine() const {
return getTM<SystemZTargetMachine>();
}
virtual bool addInstSelector();
};
} // end anonymous namespace
bool SystemZPassConfig::addInstSelector() {
addPass(createSystemZISelDag(getSystemZTargetMachine(), getOptLevel()));
return false;
}
TargetPassConfig *SystemZTargetMachine::createPassConfig(PassManagerBase &PM) {
return new SystemZPassConfig(this, PM);
}
| 35.721311 | 80 | 0.630106 | [
"model"
] |
8c5554970d82af36efe0e136c8d68bbec7715f10 | 1,077 | cpp | C++ | src/iow_sht7x.cpp | devonho/iow_sht7x | 0a625d6e4951516a58d5826faf965659d45843ae | [
"MIT"
] | 1 | 2022-01-27T08:04:15.000Z | 2022-01-27T08:04:15.000Z | src/iow_sht7x.cpp | devonho/iow_sht7x | 0a625d6e4951516a58d5826faf965659d45843ae | [
"MIT"
] | null | null | null | src/iow_sht7x.cpp | devonho/iow_sht7x | 0a625d6e4951516a58d5826faf965659d45843ae | [
"MIT"
] | null | null | null | #include <napi.h>
#include "sht7x.h"
Napi::Number MethodReadTemp(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
double value;
IOWSHT7x sht;
if(sht.open() && sht.read())
{
value = sht.getTemperature();
sht.close();
}
else
{
sht.close();
throw Napi::Error::New(env, sht.get_last_error());
}
return Napi::Number::New(env, value);
}
Napi::Number MethodReadHumidity(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
double value;
IOWSHT7x sht;
if(sht.open() && sht.read())
{
value = sht.getHumidity();
sht.close();
}
else
{
sht.close();
throw Napi::Error::New(env, sht.get_last_error());
}
return Napi::Number::New(env, value);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "readTemperature"),
Napi::Function::New(env, MethodReadTemp));
exports.Set(Napi::String::New(env, "readHumidity"),
Napi::Function::New(env, MethodReadHumidity));
return exports;
}
NODE_API_MODULE(iow_sht7x, Init) | 20.320755 | 65 | 0.626741 | [
"object"
] |
8c657a8338b9815208bcb44e910ea2b573bc8548 | 4,309 | cpp | C++ | ablateLibrary/monitors/maxMinAverage.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | null | null | null | ablateLibrary/monitors/maxMinAverage.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 8 | 2020-12-28T16:05:56.000Z | 2021-01-12T14:36:22.000Z | ablateLibrary/monitors/maxMinAverage.cpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 1 | 2020-12-22T14:16:59.000Z | 2020-12-22T14:16:59.000Z | #include "maxMinAverage.hpp"
#include "io/interval/fixedInterval.hpp"
#include "monitors/logs/stdOut.hpp"
ablate::monitors::MaxMinAverage::MaxMinAverage(const std::string& fieldName, std::shared_ptr<logs::Log> logIn, std::shared_ptr<io::interval::Interval> interval)
: fieldName(fieldName), log(logIn ? logIn : std::make_shared<logs::StdOut>()), interval(interval ? interval : std::make_shared<io::interval::FixedInterval>()) {}
PetscErrorCode ablate::monitors::MaxMinAverage::MonitorMaxMinAverage(TS ts, PetscInt step, PetscReal crtime, Vec u, void* ctx) {
PetscFunctionBeginUser;
PetscErrorCode ierr;
auto monitor = (ablate::monitors::MaxMinAverage*)ctx;
if (monitor->interval->Check(PetscObjectComm((PetscObject)ts), step, crtime)) {
// Get a subvector with only this field
const auto& field = monitor->GetSolver()->GetSubDomain().GetField(monitor->fieldName);
IS vecIs;
Vec vec;
DM subDm;
ierr = monitor->GetSolver()->GetSubDomain().GetFieldSubVector(field, &vecIs, &vec, &subDm);
CHKERRQ(ierr);
// get the comm for this monitor
auto comm = PetscObjectComm((PetscObject)vec);
// Init the min, max, avg values
std::vector<double> min(field.numberComponents, std::numeric_limits<double>::max());
std::vector<double> max(field.numberComponents, std::numeric_limits<double>::lowest());
std::vector<double> avg(field.numberComponents, 0.0);
// Get the local size of the vec
PetscInt locSize;
ierr = VecGetLocalSize(vec, &locSize);
CHKERRQ(ierr);
const PetscScalar* data;
ierr = VecGetArrayRead(vec, &data);
CHKERRQ(ierr);
// Determine the number of data points
PetscInt pts = locSize / field.numberComponents;
// Compute max/min/avg values
for (PetscInt p = 0; p < pts; p++) {
for (PetscInt d = 0; d < field.numberComponents; d++) {
const double value = data[p * field.numberComponents + d];
min[d] = PetscMin(min[d], PetscReal(value));
max[d] = PetscMax(max[d], PetscReal(value));
avg[d] += PetscReal(value);
}
}
// Take across all ranks
std::vector<double> minGlob(field.numberComponents);
std::vector<double> maxGlob(field.numberComponents);
std::vector<double> avgGlob(field.numberComponents);
int mpiError;
mpiError = MPI_Reduce(&min[0], &minGlob[0], minGlob.size(), MPI_DOUBLE, MPI_MIN, 0, comm);
CHKERRMPI(mpiError);
mpiError = MPI_Reduce(&max[0], &maxGlob[0], maxGlob.size(), MPI_DOUBLE, MPI_MAX, 0, comm);
CHKERRMPI(mpiError);
mpiError = MPI_Reduce(&avg[0], &avgGlob[0], avgGlob.size(), MPI_DOUBLE, MPI_SUM, 0, comm);
CHKERRMPI(mpiError);
// Take the avg
PetscInt globSize;
ierr = VecGetSize(vec, &globSize);
CHKERRQ(ierr);
for (auto& avgComp : avgGlob) {
avgComp /= (globSize / field.numberComponents);
}
ierr = VecRestoreArrayRead(vec, &data);
CHKERRQ(ierr);
// if this is the first time step init the log
if (!monitor->log->Initialized()) {
monitor->log->Initialize(comm);
}
// Print the results
monitor->log->Printf("MinMaxAvg %s for timestep %04d:\n", field.name.c_str(), (int)step);
monitor->log->Print("\tmin", minGlob.size(), &minGlob[0], "%2.3g");
monitor->log->Print("\n");
monitor->log->Print("\tmax", maxGlob.size(), &maxGlob[0], "%2.3g");
monitor->log->Print("\n");
monitor->log->Print("\tavg", avgGlob.size(), &avgGlob[0], "%2.3g");
monitor->log->Print("\n");
ierr = monitor->GetSolver()->GetSubDomain().RestoreFieldSubVector(field, &vecIs, &vec, &subDm);
CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
#include "registrar.hpp"
REGISTER(ablate::monitors::Monitor, ablate::monitors::MaxMinAverage, "Prints the min/max/average for a field", ARG(std::string, "field", "the name of the field"),
OPT(ablate::monitors::logs::Log, "log", "where to record log (default is stdout)"), OPT(ablate::io::interval::Interval, "interval", "report interval object, defaults to every"));
| 43.969388 | 187 | 0.621954 | [
"object",
"vector"
] |
8c73e864a9e24c03963a6e0f64996437648cede3 | 1,158 | cpp | C++ | scripts/test/test_intent_event.cpp | umdlife/dialogflow_ros | 764a3236dceae4eef87d6dc96189e5d9be503cb7 | [
"MIT"
] | 17 | 2018-03-28T23:31:11.000Z | 2022-03-07T23:33:20.000Z | scripts/test/test_intent_event.cpp | umdlife/dialogflow_ros | 764a3236dceae4eef87d6dc96189e5d9be503cb7 | [
"MIT"
] | 7 | 2018-03-29T00:20:30.000Z | 2020-10-09T17:01:18.000Z | scripts/test/test_intent_event.cpp | umdlife/dialogflow_ros | 764a3236dceae4eef87d6dc96189e5d9be503cb7 | [
"MIT"
] | 19 | 2018-03-29T00:14:28.000Z | 2022-01-14T21:27:30.000Z | #include <ros/ros.h>
#include <dialogflow_ros/DialogflowEvent.h>
#include <dialogflow_ros/DialogflowParameter.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "test_intent_event");
ros::NodeHandle n;
ros::Rate poll_rate(100);
ros::Publisher pub = n.advertise<dialogflow_ros::DialogflowEvent>("/dialogflow_client/requests/df_event", 10);
while(pub.getNumSubscribers() == 0) poll_rate.sleep();
ros::Duration(1).sleep();
dialogflow_ros::DialogflowEvent event;
event.event_name = "objects_found";
dialogflow_ros::DialogflowParameter parameter;
parameter.param_name = "objects";
std::string milk = "milk";
std::string snack = "snack";
std::vector<std::string> object_list = {milk, snack};
// parameter.value.resize(2);
parameter.value = object_list;
// parameter.value.push_back(milk);
// parameter.value = object_list;
event.parameters.push_back(parameter);
// std::cout << "Event: " << event << std::endl;
std::cout << "Parameter: " << parameter << std::endl;
std::cout << "Values" << std::endl;
for (auto val : parameter.value)
std::cout << val << std::endl;
pub.publish(event);
ros::Duration(1).sleep();
return 0;
} | 31.297297 | 111 | 0.704663 | [
"vector"
] |
8c74e0fa4069438b288d4aaa2db44658a30e3d95 | 8,621 | cc | C++ | lockserver/server.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 437 | 2016-01-13T23:06:06.000Z | 2022-03-07T07:41:55.000Z | lockserver/server.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 13 | 2016-01-14T06:12:21.000Z | 2021-09-15T07:45:17.000Z | lockserver/server.cc | yc1111/tapir | 2ce0f57725611076cd76ad7374b44f887d8618d8 | [
"MIT"
] | 58 | 2016-01-14T05:54:13.000Z | 2022-03-08T02:56:33.000Z | // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
/***********************************************************************
*
* lockserver/server.cc:
* A lockserver replica.
*
* Copyright 2015 Naveen Kr. Sharma <naveenks@cs.washington.edu>
*
* 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 "lockserver/server.h"
#include <algorithm>
#include <iterator>
#include <unordered_set>
namespace lockserver {
using namespace proto;
LockServer::LockServer() { }
LockServer::~LockServer() { }
void
LockServer::ExecInconsistentUpcall(const string &str1)
{
Debug("ExecInconsistent: %s\n", str1.c_str());
Request request;
request.ParseFromString(str1);
string key = request.key();
uint64_t client_id = request.clientid();
if (request.type()) { // Lock operation.
Warning("Lock operation being sent as Inconsistent. Ignored.");
} else {
if (locks.find(key) != locks.end()) {
if (client_id == locks[key]) {
Debug("Releasing lock %lu: %s", client_id, key.c_str());
locks.erase(key);
} else {
Debug("Lock held by someone else %lu: %s, %lu",
client_id, key.c_str(), locks[key]);
}
} else {
Debug("Lock held by no one.");
}
}
}
void
LockServer::ExecConsensusUpcall(const string &str1, string &str2)
{
Debug("ExecConsensus: %s\n", str1.c_str());
Request request;
Reply reply;
request.ParseFromString(str1);
string key = request.key();
uint64_t client_id = request.clientid();
reply.set_key(key);
int status = 0;
if (request.type()) { // Lock operation.
if (locks.find(key) == locks.end()) {
Debug("Assigning lock %lu: %s", client_id, key.c_str());
locks[key] = client_id;
} else if (locks[key] != client_id) {
Debug("Lock already held %lu: %s", client_id, key.c_str());
status = -1;
}
} else {
Warning("Unlock operation being sent as Consensus");
if (locks.find(key) == locks.end()) {
Debug("Lock held by no-one %lu: %s", client_id, key.c_str());
status = -2;
} else if (locks[key] != client_id) {
Debug("Lock held by someone else %lu: %s, %lu",
client_id, key.c_str(), locks[key]);
status = -2;
} else {
Debug("Releasing lock %lu: %s", client_id, key.c_str());
locks.erase(key);
}
}
reply.set_status(status);
reply.SerializeToString(&str2);
}
void
LockServer::UnloggedUpcall(const string &str1, string &str2)
{
Debug("Unlogged: %s\n", str1.c_str());
}
void
LockServer::Sync(const std::map<opid_t, RecordEntry>& record) {
locks.clear();
struct KeyLockInfo {
std::unordered_set<uint64_t> locked;
std::unordered_set<uint64_t> unlocked;
};
std::unordered_map<std::string, KeyLockInfo> key_lock_info;
for (const std::pair<const opid_t, RecordEntry> &p : record) {
const opid_t &opid = p.first;
const RecordEntry &entry = p.second;
Request request;
request.ParseFromString(entry.request.op());
Reply reply;
reply.ParseFromString(entry.result);
KeyLockInfo &info = key_lock_info[request.key()];
Debug("Sync opid=(%lu, %lu), clientid=%lu, key=%s, type=%d, status=%d.",
opid.first, opid.second, request.clientid(),
request.key().c_str(), request.type(), reply.status());
if (request.type() && reply.status() == 0) {
// Lock.
info.locked.insert(request.clientid());
} else if (!request.type() && reply.status() == 0) {
// Unlock.
info.unlocked.insert(request.clientid());
}
}
for (const std::pair<const std::string, KeyLockInfo> &p : key_lock_info) {
const std::string &key = p.first;
const KeyLockInfo &info = p.second;
std::unordered_set<uint64_t> diff;
std::set_difference(std::begin(info.locked), std::end(info.locked),
std::begin(info.unlocked), std::end(info.unlocked),
std::inserter(diff, diff.begin()));
ASSERT(diff.size() == 0 || diff.size() == 1);
if (diff.size() == 1) {
uint64_t client_id = *std::begin(diff);
Debug("Assigning lock %lu: %s", client_id, key.c_str());
locks[key] = client_id;
}
}
}
std::map<opid_t, std::string>
LockServer::Merge(const std::map<opid_t, std::vector<RecordEntry>> &d,
const std::map<opid_t, std::vector<RecordEntry>> &u,
const std::map<opid_t, std::string> &majority_results_in_d) {
// First note that d and u only contain consensus operations, and lock
// requests are the only consensus operations (unlock is an inconsistent
// operation), so d and u only contain lock requests. To merge, we grant
// any majority successful lock request in d if it does not conflict with a
// currently held lock. We do not grant any other lock request.
std::map<opid_t, std::string> results;
using EntryVec = std::vector<RecordEntry>;
for (const std::pair<const opid_t, EntryVec>& p: d) {
const opid_t &opid = p.first;
const EntryVec &entries = p.second;
// Get the request and reply.
const RecordEntry &entry = *std::begin(entries);
Request request;
request.ParseFromString(entry.request.op());
Reply reply;
auto iter = majority_results_in_d.find(opid);
ASSERT(iter != std::end(majority_results_in_d));
reply.ParseFromString(iter->second);
// Form the final result.
const bool operation_successful = reply.status() == 0;
if (operation_successful) {
// If the lock was successful, then we acquire the lock so long as
// it is not already held.
const std::string &key = reply.key();
if (locks.count(key) == 0) {
Debug("Assigning lock %lu: %s", request.clientid(),
key.c_str());
locks[key] = request.clientid();
results[opid] = iter->second;
} else {
Debug("Rejecting lock %lu: %s", request.clientid(),
key.c_str());
reply.set_status(-1);
std::string s;
reply.SerializeToString(&s);
results[opid] = s;
}
} else {
// If the lock was not successful, then we maintain this as the
// majority result.
results[opid] = iter->second;
}
}
// We reject all lock requests in u. TODO: We could acquire a lock if
// it is free, but it's simplest to just reject them unilaterally.
for (const std::pair<const opid_t, EntryVec>& p: u) {
const opid_t &opid = p.first;
const EntryVec &entries = p.second;
const RecordEntry &entry = *std::begin(entries);
Request request;
request.ParseFromString(entry.request.op());
Debug("Rejecting lock %lu: %s", request.clientid(),
request.key().c_str());
Reply reply;
reply.set_key(request.key());
reply.set_status(-1);
std::string s;
reply.SerializeToString(&s);
results[opid] = s;
}
return results;
}
} // namespace lockserver
| 34.902834 | 80 | 0.583343 | [
"vector"
] |
8c753ee609e5b779d0d50cfd455427be12049edc | 4,536 | hpp | C++ | examples/uosbetdice/uosbetdice.hpp | UlordChain/uosio.cdt | fc60000884f2179e9a5ac819e05b6cc3f4d6bb37 | [
"MIT"
] | null | null | null | examples/uosbetdice/uosbetdice.hpp | UlordChain/uosio.cdt | fc60000884f2179e9a5ac819e05b6cc3f4d6bb37 | [
"MIT"
] | null | null | null | examples/uosbetdice/uosbetdice.hpp | UlordChain/uosio.cdt | fc60000884f2179e9a5ac819e05b6cc3f4d6bb37 | [
"MIT"
] | null | null | null | #include <utility>
#include <vector>
#include <string>
#include <uosiolib/uosio.hpp>
#include <uosiolib/time.hpp>
#include <uosiolib/asset.hpp>
#include <uosiolib/contract.hpp>
#include <uosiolib/types.h>
#include <uosiolib/transaction.hpp>
#include <uosiolib/crypto.h>
//#include <boost/algorithm/string.hpp>
using uosio::asset;
using uosio::permission_level;
using uosio::action;
using uosio::print;
using uosio::name;
using uosio::unpack_action_data;
//using uosio::symbol;
using uosio::transaction;
using uosio::time_point_sec;
using uosio::datastream;
using namespace uosio;
CONTRACT uosbetdice : public uosio::contract {
public:
const uint32_t TWO_MINUTES = 2 * 60;
const uint64_t MINBET = 1000;
const uint64_t HOUSEEDGE_times10000 = 200;
const uint64_t HOUSEEDGE_REF_times10000 = 150;
const uint64_t REFERRER_REWARD_times10000 = 50;
const uint64_t BETID_ID = 1;
const uint64_t TOTALAMTBET_ID = 2;
const uint64_t TOTALAMTWON_ID = 3;
const uint64_t LIABILITIES_ID = 4;
// uosbetdice(uint64_t self):uosio::contract(self),
uosbetdice( name receiver, name code, uosio::datastream<const char*> ds )
: uosio::contract(receiver, code, ds),
activebets(_self, _self.value),
globalvars(_self, _self.value),
randkeys(_self, _self.value)
{}
ACTION initcontract(public_key randomness_key);
ACTION newrandkey(public_key randomness_key);
ACTION suspendbet(const uint64_t bet_id);
ACTION transfer(uint64_t sender, uint64_t receiver);
ACTION resolvebet(const uint64_t bet_id, signature sig);
ACTION betreceipt( uint64_t bet_id, uint64_t bettor,
uint64_t amt_contract, asset bet_amt, asset payout,
capi_checksum256 seed, signature signature,uint64_t roll_under,
uint64_t random_roll
);
ACTION refundbet(const uint64_t bet_id) ;
private:
TABLE bet {
uint64_t id;
uint64_t bettor; // 赌博者
uint64_t referral; // 推荐人
uint64_t bet_amt; // 投注金额
uint64_t roll_under; // 投注数字
capi_checksum256 seed; // 随机数种子
time_point_sec bet_time; // 投注时间
uint64_t primary_key() const { return id; }
UOSLIB_SERIALIZE( bet, (id)(bettor)(referral)(bet_amt)(roll_under)(seed)(bet_time))
};
typedef uosio::multi_index< "activebets"_n, bet> bets_index;
TABLE globalvar{
uint64_t id;
uint64_t val;
uint64_t primary_key() const { return id; }
UOSLIB_SERIALIZE(globalvar, (id)(val));
};
typedef uosio::multi_index< "globalvars"_n, globalvar> globalvars_index;
TABLE randkey {
uint64_t id;
public_key key;
uint64_t primary_key() const { return id; }
};
typedef uosio::multi_index< "randkeys"_n, randkey > randkeys_index;
// taken from uosio.token.hpp 直接放内存
struct account {
asset balance;
uint64_t primary_key() const { return balance.symbol.code().raw(); }
};
typedef uosio::multi_index<"accounts"_n, account> accounts;
// taken from uosio.token.hpp
struct st_transfer {
uint64_t from;
uint64_t to;
asset quantity;
std::string memo;
};
struct st_seeds{
capi_checksum256 seed1;
capi_checksum256 seed2;
};
bets_index activebets;
globalvars_index globalvars;
randkeys_index randkeys;
void printtest(const uosio::signature& sig, const uosio::public_key& pubkey );
void increment_liabilities_bet_id(const uint64_t bet_amt);
void increment_game_stats(const uint64_t bet_amt, const uint64_t won_amt);
void decrement_liabilities(const uint64_t bet_amt);
void airdrop_tokens(const uint64_t bet_id, const uint64_t bet_amt, const uint64_t bettor);
uint64_t get_token_balance(const uint64_t token_contract, const symbol& token_type)const ;
uint64_t get_payout_mult_times10000(const uint64_t roll_under, const uint64_t house_edge_times_10000)const ;
uint64_t get_max_win()const ;
};
#define UOSIO_DISPATCH_EX( TYPE, MEMBERS ) \
extern "C" { \
void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
auto self = receiver; \
if( code == self || code == ("uosio.token"_n).value) { \
if( action == ("transfer"_n).value){ \
uosio_assert( code == ("uosio.token"_n).value, "Must transfer UOS"); \
} \
switch( action ) { \
UOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \
} \
/* does not allow destructor of thiscontract to run: uosio_exit(0); */ \
} \
} \
}
| 27.658537 | 111 | 0.684303 | [
"vector"
] |
8c77ae52b8c2d8eadff2523bb8a5da60879a299d | 1,383 | cpp | C++ | 1er Parcial/Vector/rotateArray.cpp | Adrian-Garcia/Algorithms | 95ec54ef05091e4da93c52ccbecb1c278bb2fb43 | [
"MIT"
] | null | null | null | 1er Parcial/Vector/rotateArray.cpp | Adrian-Garcia/Algorithms | 95ec54ef05091e4da93c52ccbecb1c278bb2fb43 | [
"MIT"
] | null | null | null | 1er Parcial/Vector/rotateArray.cpp | Adrian-Garcia/Algorithms | 95ec54ef05091e4da93c52ccbecb1c278bb2fb43 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
std::vector<int> nums;
int k=-8;
// 0 1 2 3 4 5 6
//[1,2,3,4,5,6,7]
//[2 3 4 5 6 7 1] -1
//[7,1,2,3,4,5,6] 1
//[5,6,7,1,2,3,4] 3
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
nums.push_back(4);
nums.push_back(5);
nums.push_back(6);
nums.push_back(7);
queue<int> q;
queue<int> r;
if (k > nums.size()) {
cout << "1" << endl;
k = k%nums.size();
} else if (k < 0 && k > -1*nums.size()) {
cout << "2" << endl;
k*=-1;
k = k%nums.size();
}
if (k > 0) {
for (int i=nums.size()-k; i<nums.size(); i++) {
q.push(nums[i]);
}
for (int i=0; i < nums.size()-k; ++i){
r.push(nums[i]);
}
int i=0;
while(!q.empty()) {
nums[i] = q.front();
q.pop();
i++;
}
while(!r.empty()) {
nums[i] = r.front();
r.pop();
i++;
}
}
else {
int count = 0;
for (int i=k; i<nums.size(); i++) {
q.push(nums[i]);
count++;
}
for (int i=0; i<nums.size()-count; ++i){
r.push(nums[i]);
}
int i=0;
while(!q.empty()) {
nums[i] = q.front();
q.pop();
i++;
}
while(!r.empty()) {
nums[i] = r.front();
r.pop();
i++;
}
}
for (int i = 0; i < nums.size(); ++i){
cout << nums[i] << " " ;
}
return 0;
} | 15.197802 | 50 | 0.439624 | [
"vector"
] |
8c7d21ffee986c16945ac6358803034c6e78487f | 5,001 | cc | C++ | test/cctest/test-ignition-statistics-extension.cc | EXHades/v8 | 5fe0aa3bc79c0a9d3ad546b79211f07105f09585 | [
"BSD-3-Clause"
] | 20,995 | 2015-01-01T05:12:40.000Z | 2022-03-31T21:39:18.000Z | test/cctest/test-ignition-statistics-extension.cc | Andrea-MariaDB-2/v8 | a0f0ebd7a876e8cb2210115adbfcffe900e99540 | [
"BSD-3-Clause"
] | 333 | 2020-07-15T17:06:05.000Z | 2021-03-15T12:13:09.000Z | test/cctest/test-ignition-statistics-extension.cc | Andrea-MariaDB-2/v8 | a0f0ebd7a876e8cb2210115adbfcffe900e99540 | [
"BSD-3-Clause"
] | 4,523 | 2015-01-01T15:12:34.000Z | 2022-03-28T06:23:41.000Z | // Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter.h"
#include "test/cctest/test-api.h"
namespace v8 {
namespace internal {
class IgnitionStatisticsTester {
public:
explicit IgnitionStatisticsTester(Isolate* isolate) : isolate_(isolate) {
// In case the build specified v8_enable_ignition_dispatch_counting, the
// interpreter already has a dispatch counters table and the bytecode
// handlers will update it. To avoid crashes, we keep that array alive here.
// This file doesn't test the results in the real array since there is no
// automated testing on configurations with
// v8_enable_ignition_dispatch_counting.
original_bytecode_dispatch_counters_table_ =
std::move(isolate->interpreter()->bytecode_dispatch_counters_table_);
// This sets up the counters array, but does not rewrite the bytecode
// handlers to update it.
isolate->interpreter()->InitDispatchCounters();
}
void SetDispatchCounter(interpreter::Bytecode from, interpreter::Bytecode to,
uintptr_t value) const {
int from_index = interpreter::Bytecodes::ToByte(from);
int to_index = interpreter::Bytecodes::ToByte(to);
isolate_->interpreter()->bytecode_dispatch_counters_table_
[from_index * interpreter::Bytecodes::kBytecodeCount + to_index] =
value;
CHECK_EQ(isolate_->interpreter()->GetDispatchCounter(from, to), value);
}
private:
Isolate* isolate_;
std::unique_ptr<uintptr_t[]> original_bytecode_dispatch_counters_table_;
};
TEST(IgnitionStatisticsExtension) {
FLAG_expose_ignition_statistics = true;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
IgnitionStatisticsTester tester(CcTest::i_isolate());
Local<Value> typeof_result =
CompileRun("typeof getIgnitionDispatchCounters === 'function'");
CHECK(typeof_result->BooleanValue(isolate));
// Get the list of all bytecode names into a JavaScript array.
#define BYTECODE_NAME_WITH_COMMA(Name, ...) "'" #Name "', "
const char* kBytecodeNames =
"var bytecodeNames = [" BYTECODE_LIST(BYTECODE_NAME_WITH_COMMA) "];";
#undef BYTECODE_NAME_WITH_COMMA
CompileRun(kBytecodeNames);
// Check that the dispatch counters object is a non-empty object of objects
// where each property name is a bytecode name, in order, and each inner
// object is empty.
const char* kEmptyTest = R"(
var emptyCounters = getIgnitionDispatchCounters();
function isEmptyDispatchCounters(counters) {
if (typeof counters !== "object") return false;
var i = 0;
for (var sourceBytecode in counters) {
if (sourceBytecode !== bytecodeNames[i]) return false;
var countersRow = counters[sourceBytecode];
if (typeof countersRow !== "object") return false;
for (var counter in countersRow) {
return false;
}
++i;
}
return true;
}
isEmptyDispatchCounters(emptyCounters);)";
Local<Value> empty_result = CompileRun(kEmptyTest);
CHECK(empty_result->BooleanValue(isolate));
// Simulate running some code, which would update the counters.
tester.SetDispatchCounter(interpreter::Bytecode::kLdar,
interpreter::Bytecode::kStar, 3);
tester.SetDispatchCounter(interpreter::Bytecode::kLdar,
interpreter::Bytecode::kLdar, 4);
tester.SetDispatchCounter(interpreter::Bytecode::kMov,
interpreter::Bytecode::kLdar, 5);
// Check that the dispatch counters object is a non-empty object of objects
// where each property name is a bytecode name, in order, and the inner
// objects reflect the new state.
const char* kNonEmptyTest = R"(
var nonEmptyCounters = getIgnitionDispatchCounters();
function isUpdatedDispatchCounters(counters) {
if (typeof counters !== "object") return false;
var i = 0;
for (var sourceBytecode in counters) {
if (sourceBytecode !== bytecodeNames[i]) return false;
var countersRow = counters[sourceBytecode];
if (typeof countersRow !== "object") return false;
switch (sourceBytecode) {
case "Ldar":
if (JSON.stringify(countersRow) !== '{"Ldar":4,"Star":3}')
return false;
break;
case "Mov":
if (JSON.stringify(countersRow) !== '{"Ldar":5}')
return false;
break;
default:
for (var counter in countersRow) {
return false;
}
}
++i;
}
return true;
}
isUpdatedDispatchCounters(nonEmptyCounters);)";
Local<Value> non_empty_result = CompileRun(kNonEmptyTest);
CHECK(non_empty_result->BooleanValue(isolate));
}
} // namespace internal
} // namespace v8
| 38.469231 | 80 | 0.679664 | [
"object"
] |
8c81390b5de9aeb9dbba4cfd48740475c54cb49e | 3,639 | cpp | C++ | src/typeRef.cpp | p4gauntlet/cdg-backend | 09395409835cc6704acaa4e4c4a31360f45834d0 | [
"Apache-2.0"
] | null | null | null | src/typeRef.cpp | p4gauntlet/cdg-backend | 09395409835cc6704acaa4e4c4a31360f45834d0 | [
"Apache-2.0"
] | null | null | null | src/typeRef.cpp | p4gauntlet/cdg-backend | 09395409835cc6704acaa4e4c4a31360f45834d0 | [
"Apache-2.0"
] | null | null | null | #include "typeRef.h"
#include "baseType.h"
#include "headerStackType.h"
namespace CODEGEN {
IR::Type *typeRef::pick_rnd_type(typeref_probs type_probs) {
const std::vector<int64_t> &type_probs_vector = {
type_probs.p4_bit, type_probs.p4_signed_bit,
type_probs.p4_varbit, type_probs.p4_int,
type_probs.p4_error, type_probs.p4_bool,
type_probs.p4_string, type_probs.p4_enum,
type_probs.p4_header, type_probs.p4_header_stack,
type_probs.p4_struct, type_probs.p4_header_union,
type_probs.p4_tuple, type_probs.p4_void,
type_probs.p4_match_kind};
const std::vector<int64_t> &basetype_probs = {
type_probs.p4_bool, type_probs.p4_error, type_probs.p4_int,
type_probs.p4_string, type_probs.p4_bit, type_probs.p4_signed_bit,
type_probs.p4_varbit};
if (type_probs_vector.size() != 15) {
BUG("pick_rnd_type: Type probabilities must be exact");
}
IR::Type *tp = nullptr;
size_t idx = randind(type_probs_vector);
switch (idx) {
case 0: {
// bit<>
tp = baseType::gen_bit_type(false);
break;
}
case 1: {
// int<>
tp = baseType::gen_bit_type(true);
break;
}
case 2: {
// varbit<>, this is not supported right now
break;
}
case 3: {
// int, this is not supported right now
tp = baseType::gen_int_type();
break;
}
case 4: {
// error, this is not supported right now
break;
}
case 5: {
// bool
tp = baseType::gen_bool_type();
break;
}
case 6: {
// string, this is not supported right now
break;
}
case 7: {
// enum, this is not supported right now
break;
}
case 8: {
// header
auto l_types = P4Scope::get_decls<IR::Type_Header>();
if (l_types.size() == 0) {
tp = baseType::pick_rnd_base_type(basetype_probs);
break;
}
auto candidate_type = l_types.at(get_rnd_int(0, l_types.size() - 1));
auto type_name = candidate_type->name.name;
// check if struct is forbidden
if (P4Scope::not_initialized_structs.count(type_name) == 0) {
tp = new IR::Type_Name(candidate_type->name.name);
} else {
tp = baseType::pick_rnd_base_type(basetype_probs);
}
break;
}
case 9: {
tp = headerStackType::gen();
break;
}
case 10: {
// struct
auto l_types = P4Scope::get_decls<IR::Type_Struct>();
if (l_types.size() == 0) {
tp = baseType::pick_rnd_base_type(basetype_probs);
break;
}
auto candidate_type = l_types.at(get_rnd_int(0, l_types.size() - 1));
auto type_name = candidate_type->name.name;
// check if struct is forbidden
if (P4Scope::not_initialized_structs.count(type_name) == 0) {
tp = new IR::Type_Name(candidate_type->name.name);
} else {
tp = baseType::pick_rnd_base_type(basetype_probs);
}
break;
}
case 11: {
// header union, this is not supported right now
break;
}
case 12: {
// tuple, this is not supported right now
break;
}
case 13: {
// void
tp = new IR::Type_Void();
break;
}
case 14: {
// match kind, this is not supported right now
break;
}
}
if (not tp) {
BUG("pick_rnd_type: Chosen type is Null!");
}
return tp;
}
} // namespace CODEGEN
| 28.653543 | 77 | 0.56499 | [
"vector"
] |
8c8e6a2d915efe54a2a20f1b183a210ca310e069 | 19,433 | cpp | C++ | src/prod/src/Naming/storeservicehealthmonitor.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Naming/storeservicehealthmonitor.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Naming/storeservicehealthmonitor.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Federation;
using namespace std;
using namespace Reliability;
using namespace ServiceModel;
using namespace Naming;
StringLiteral const TraceComponent("HealthMonitor");
TimeSpan const HealthReportSendOverhead = TimeSpan::FromSeconds(30);
// --------------------------------------------------
// HealthMonitoredOperationName
// --------------------------------------------------
namespace Naming
{
namespace HealthMonitoredOperationName
{
void WriteToTextWriter(TextWriter & w, Enum e)
{
switch (e)
{
case PrimaryRecoveryStarted: w << "PrimaryRecoveryStarted"; break;
case AOCreateName: w << "AOCreateName"; break;
case AODeleteName: w << "AODeleteName"; break;
case AOCreateService: w << "AOCreateService"; break;
case AODeleteService: w << "AODeleteService"; break;
case AOUpdateService: w << "AOUpdateService"; break;
case NOCreateName: w << "NOCreateName"; break;
case NODeleteName: w << "NODeleteName"; break;
case NOCreateService: w << "NOCreateService"; break;
case NODeleteService: w << "NODeleteService"; break;
case NOUpdateService: w << "NOUpdateService"; break;
case NameExists: w << "NameExists"; break;
case EnumerateProperties: w << "EnumerateProperties"; break;
case EnumerateNames: w << "EnumerateNames"; break;
case GetServiceDescription: w << "GetServiceDescription"; break;
case PrefixResolve: w << "PrefixResolve"; break;
case PropertyBatch: w << "PropertyBatch"; break;
case InvalidOperation: w << "InvalidOperation"; break;
case PrimaryRecovery: w << "PrimaryRecovery"; break;
default: Assert::CodingError("Invalid state for internal enum: {0}", static_cast<int>(e));
};
}
ENUM_STRUCTURED_TRACE(HealthMonitoredOperationName, PrimaryRecoveryStarted, LastValidEnum);
}
}
// --------------------------------------------------
// HealthMonitoredOperation
// --------------------------------------------------
HealthMonitoredOperation::HealthMonitoredOperation(
Common::ActivityId const & activityId,
HealthMonitoredOperationName::Enum operationName,
std::wstring const & operationMetadata,
Common::TimeSpan const & maxAllowedDuration)
: activityId_(activityId)
, operationName_(operationName)
, operationMetadata_(operationMetadata)
, maxAllowedDuration_(maxAllowedDuration)
, startTime_(Stopwatch::Now())
, completedTime_(StopwatchTime::MaxValue)
, completedError_(ErrorCodeValue::Success)
, lastReportTime_(StopwatchTime::MaxValue)
, lastReportTTL_(TimeSpan::MaxValue)
{
}
HealthMonitoredOperation::~HealthMonitoredOperation()
{
}
bool HealthMonitoredOperation::IsSlowDetected() const
{
return lastReportTime_ != StopwatchTime::MaxValue;
}
bool HealthMonitoredOperation::MarkSendHealthReport(Common::StopwatchTime const & now)
{
if (IsCompleted())
{
// No report is sent for completed operations
return false;
}
if (IsSlowDetected())
{
// Check whether the last report time was sent too long ago
bool resend;
if (lastReportTTL_ <= HealthReportSendOverhead)
{
resend = true;
}
else
{
TimeSpan resendInterval = lastReportTTL_ - HealthReportSendOverhead;
resend = (now - lastReportTime_ >= resendInterval);
}
if (resend)
{
lastReportTime_ = now;
return true;
}
return false;
}
// The operation wasn't previously too slow, check if it still respects duration
if (now - startTime_ >= maxAllowedDuration_)
{
lastReportTime_ = now;
return true;
}
return false;
}
std::wstring HealthMonitoredOperation::GenerateHealthReportExtraDescription() const
{
if (IsCompleted())
{
return wformatString(HMResource::GetResources().NamingOperationSlowCompleted, operationName_, startTime_.ToDateTime(), completedError_, maxAllowedDuration_);
}
else
{
ASSERT_IFNOT(completedError_.IsSuccess(), "{0}: {1}+{2}: completed error set even if operation is not yet completed", activityId_, operationName_, operationMetadata_);
return wformatString(HMResource::GetResources().NamingOperationSlow, operationName_, startTime_.ToDateTime(), maxAllowedDuration_);
}
}
std::wstring HealthMonitoredOperation::GenerateHealthReportProperty() const
{
if (operationMetadata_.empty())
{
return wformatString("{0}", operationName_);
}
return wformatString("{0}.{1}", operationName_, operationMetadata_);
}
HealthReport HealthMonitoredOperation::GenerateHealthReport(
ServiceModel::EntityHealthInformationSPtr && entityInfo,
Common::TimeSpan const & ttl,
int64 reportSequenceNumber) const
{
auto dynamicProperty = this->GenerateHealthReportProperty();
auto extraDescription = this->GenerateHealthReportExtraDescription();
// Remember the ttl to know when to send next report
lastReportTTL_ = ttl;
auto report = HealthReport::CreateSystemHealthReport(
IsCompleted() ? SystemHealthReportCode::Naming_OperationSlowCompleted : SystemHealthReportCode::Naming_OperationSlow,
move(entityInfo),
dynamicProperty,
extraDescription,
reportSequenceNumber,
ttl,
AttributeList());
StoreServiceHealthMonitor::WriteInfo(TraceComponent, "{0}: Created {1}", activityId_, report);
return move(report);
}
void HealthMonitoredOperation::ResetCompletedInfo(Common::ActivityId const & activityId)
{
if (IsCompleted())
{
// A new retry is started for the same operation.
// Mark slow detected false, so a new report will be sent for the new retry.
completedTime_ = StopwatchTime::MaxValue;
lastReportTime_ = StopwatchTime::MaxValue;
lastReportTTL_ = TimeSpan::MaxValue;
// Ignore previous completed value
completedError_.ReadValue();
completedError_ = ErrorCode(ErrorCodeValue::Success);
if (activityId != activityId_)
{
StoreServiceHealthMonitor::WriteInfo(
TraceComponent,
"{0}: {1}+{2}: ResetCompleted on new request {3}",
activityId_,
operationName_,
operationMetadata_,
activityId);
// Set the activity id to the new activity id
activityId_ = activityId;
}
else
{
StoreServiceHealthMonitor::WriteInfo(
TraceComponent,
"{0}: {1}+{2}: ResetCompleted on retry",
activityId_,
operationName_,
operationMetadata_);
}
}
}
bool HealthMonitoredOperation::ShouldBeRemoved(Common::StopwatchTime const & now) const
{
return IsCompleted() && (completedTime_ + NamingConfig::GetConfig().NamingServiceFailedOperationHealthGraceInterval <= now);
}
bool HealthMonitoredOperation::IsCompleted() const
{
return completedTime_ != StopwatchTime::MaxValue;
}
void HealthMonitoredOperation::Complete(Common::ErrorCode const & error)
{
completedTime_ = Stopwatch::Now();
completedError_.ReadValue();
completedError_ = error;
}
// --------------------------------------------------
// StoreServiceHealthMonitor
// --------------------------------------------------
StoreServiceHealthMonitor::StoreServiceHealthMonitor(
ComponentRoot const & root,
Guid const & partitionId,
FABRIC_REPLICA_ID replicaId,
__in FederationWrapper & federation)
: RootedObject(root)
, Store::PartitionedReplicaTraceComponent<Common::TraceTaskCodes::NamingStoreService>(partitionId, replicaId)
, federation_(federation)
, healthClient_()
, lock_()
, timer_()
, operations_()
, isOpen_(false)
{
WriteNoise(TraceComponent, "{0}: ctor {1}", this->TraceId, TextTraceThis);
}
StoreServiceHealthMonitor::~StoreServiceHealthMonitor()
{
WriteNoise(TraceComponent, "{0}: ~dtor {1}", this->TraceId, TextTraceThis);
}
bool StoreServiceHealthMonitor::Comparator::operator()(HealthMonitoredOperationKey const & left, HealthMonitoredOperationKey const & right) const
{
// Same operation name, check the metadata
if (left.first == right.first)
{
return left.second < right.second;
}
// Check operation name
return left.first < right.first;
}
void StoreServiceHealthMonitor::Open()
{
AcquireWriteLock lock(lock_);
ASSERT_IF(isOpen_, "Invalid state for Open: StoreServiceHealthMonitor {0} is already opened", static_cast<void*>(this));
isOpen_ = true;
if (!healthClient_)
{
healthClient_ = federation_.Federation.GetHealthClient();
}
// Create the scan timer, but do not enable it yet, since there are no operations
if (!timer_)
{
auto root = this->Root.CreateAsyncOperationRoot();
timer_ = Timer::Create(TimerTagDefault, [this, root](Common::TimerSPtr const &) { this->OnTimerCallback(); });
}
DisableTimerCallerHoldsLock();
}
void StoreServiceHealthMonitor::Close()
{
AcquireWriteLock grab(lock_);
if (!isOpen_)
{
return;
}
isOpen_ = false;
if (timer_)
{
timer_->Cancel();
timer_.reset();
}
// Since the instance of the primary replica is closed, HM removes all reports on it
// Clear the operations so the 2 views match.
operations_.clear();
}
void StoreServiceHealthMonitor::AddMonitoredOperation(
Common::ActivityId const & activityId,
HealthMonitoredOperationName::Enum operationName,
std::wstring const & operationMetadata,
Common::TimeSpan const & maxAllowedDuration)
{
AcquireWriteLock lock(lock_);
if (!isOpen_)
{
WriteNoise(TraceComponent, "{0}: skip add monitored operation as the health monitor is not opened", activityId);
return;
}
// Create key with a reference to the input operationMetadata
auto itFind = operations_.find(HealthMonitoredOperationKey(operationName, operationMetadata));
if (itFind != operations_.end())
{
// There is already an entry, this can be a client retry for an already existing operation.
// Eg. user called CreateService, timed out on client, retries.
// Naming service has received the previous request and it's processing it.
// Do not add, keep the old operation.
// If the operation was previously completed with error, reset the completed state.
itFind->second->ResetCompletedInfo(activityId);
return;
}
auto operation = make_shared<HealthMonitoredOperation>(
activityId,
operationName,
operationMetadata,
maxAllowedDuration);
// Create a new key to insert in map with reference to the operation metadata inside the operation
HealthMonitoredOperationKey mapKey(operationName, operation->OperationMetadata);
#ifdef DBG
auto insertResult = operations_.insert(make_pair(mapKey, move(operation)));
ASSERT_IFNOT(insertResult.second, "{0}: {1}+{2}: the operation is already in the monitored list", activityId, operationName, operationMetadata);
#else
operations_.insert(make_pair(mapKey, move(operation)));
#endif
// If this is the first item added, start the timer
if (operations_.size() == 1)
{
EnableTimerCallerHoldsLock();
}
}
void StoreServiceHealthMonitor::CompleteSuccessfulMonitoredOperation(
Common::ActivityId const & activityId,
HealthMonitoredOperationName::Enum operationName,
std::wstring const & operationMetadata)
{
CompleteMonitoredOperation(activityId, operationName, operationMetadata, ErrorCode::Success(), false);
}
void StoreServiceHealthMonitor::CompleteMonitoredOperation(
Common::ActivityId const & activityId,
HealthMonitoredOperationName::Enum operationName,
std::wstring const & operationMetadata,
Common::ErrorCode const & error,
bool keepOperation)
{
HealthMonitoredOperationSPtr deletedOp;
FABRIC_SEQUENCE_NUMBER reportSequenceNumber = FABRIC_INVALID_SEQUENCE_NUMBER;
{ // lock
AcquireWriteLock lock(lock_);
if (!isOpen_)
{
// Nothing to do in this case, when replica is removed from health store all reports are cleaned up
return;
}
// Get the operation, if it exists, so we can clear reports on it
auto itOp = operations_.find(HealthMonitoredOperationKey(operationName, operationMetadata));
if (itOp == operations_.end())
{
WriteNoise(TraceComponent, "{0}: {1}+{2}: Monitored operation was not found", activityId, operationName, operationMetadata);
return;
}
// Check that the operation is for the same activity id. Keep only one entry,
// the first one since we care about start time.
if (itOp->second->ActivityId != activityId)
{
WriteInfo(TraceComponent, "{0}: Complete {1}+{2}: Monitored operation has different activityId {3}, skip.", activityId, operationName, operationMetadata, itOp->second->ActivityId);
return;
}
itOp->second->Complete(error);
if (keepOperation)
{
// The operation didn't yet complete successfully.
// It's possible there may be more retries from either authority owner or user.
// Keep track of initial startup time by keeping the old operation for a while.
deletedOp = itOp->second;
}
else
{
// Remove the operation from the map under the lock
deletedOp = move(itOp->second);
operations_.erase(itOp);
// If there are no more operations, stop the timer
if (operations_.empty())
{
DisableTimerCallerHoldsLock();
}
}
// Generate the health report sequence number under the lock
if (deletedOp->IsSlowDetected())
{
reportSequenceNumber = SequenceNumber::GetNext();
}
} // endlock
// Send report to clear the previous reports (if any), outside the lock
if (reportSequenceNumber != FABRIC_INVALID_SEQUENCE_NUMBER)
{
// The report stays in store for ttl before being removed, so users can have a chance to see it
// If the operation is kept for longer, use the configured TTL.
// Otherwise, use a small TTL so the operation is cleaned up quickly.
auto ttl = keepOperation ?
NamingConfig::GetConfig().NamingServiceFailedOperationHealthReportTimeToLive :
TimeSpan::FromSeconds(1);
auto healthReport = deletedOp->GenerateHealthReport(
CreateNamingPrimaryEntityInfo(),
ttl,
reportSequenceNumber);
// Once created, the health client is not changed, so it's OK to access outside lock
auto reportError = healthClient_->AddHealthReport(move(healthReport));
if (!reportError.IsSuccess())
{
WriteInfo(
TraceComponent,
"{0}: Add completed report returned {1}",
deletedOp->ActivityId,
reportError);
}
}
}
void StoreServiceHealthMonitor::OnTimerCallback()
{
// Look for all operations that took longer than expected and report health on them
using MonitoredOperationWithSequence = pair<int64, HealthMonitoredOperationSPtr>;
vector<MonitoredOperationWithSequence> slowOperations;
StopwatchTime now = Stopwatch::Now();
int count = 0;
int maxCount = NamingConfig::GetConfig().MaxNamingServiceHealthReports;
if (maxCount == 0)
{
maxCount = numeric_limits<int>::max();
}
{ // lock
AcquireWriteLock lock(lock_);
if (!isOpen_ || !healthClient_)
{
return;
}
OperationMap tempOperations;
for (auto && op : operations_)
{
if (op.second->ShouldBeRemoved(now))
{
// Remove operations that have been completed but not retried in a more than grace period
continue;
}
if (count < maxCount && op.second->MarkSendHealthReport(now))
{
// Generate a sequence number under the lock to prevent races when adding to health client
slowOperations.push_back(make_pair(SequenceNumber::GetNext(), op.second));
++count;
}
tempOperations.insert(move(op));
}
operations_ = move(tempOperations);
// If there are no more operations, stop the timer
if (operations_.empty())
{
DisableTimerCallerHoldsLock();
}
} // endlock
if (count >= maxCount)
{
WriteInfo(TraceComponent, "TimerCallback: there are more slow operations that max {0}, report {0}", maxCount);
}
if (!slowOperations.empty())
{
vector<HealthReport> reports;
for (auto & op : slowOperations)
{
auto healthReport = op.second->GenerateHealthReport(
CreateNamingPrimaryEntityInfo(),
NamingConfig::GetConfig().NamingServiceSlowOperationHealthReportTimeToLive,
op.first/*reportSequenceNumber*/);
reports.push_back(move(healthReport));
}
// Once created, the health client is not changed, so it's ok to access outside lock
auto error = healthClient_->AddHealthReports(move(reports));
if (!error.IsSuccess())
{
WriteInfo(
TraceComponent,
"{0}: Adding reports for {1} operations returned error {2}",
slowOperations[0].second->ActivityId,
slowOperations.size(),
error);
}
}
}
void StoreServiceHealthMonitor::DisableTimerCallerHoldsLock()
{
timer_->Change(TimeSpan::MaxValue);
}
void StoreServiceHealthMonitor::EnableTimerCallerHoldsLock()
{
auto scanTime = NamingConfig::GetConfig().NamingServiceHealthReportingTimerInterval;
timer_->Change(scanTime, scanTime);
}
ServiceModel::EntityHealthInformationSPtr StoreServiceHealthMonitor::CreateNamingPrimaryEntityInfo() const
{
// The naming service replica doesn't have access to the instance id.
// Because of this, it can't report on transitions only, because reports may be delayed
// and applied on the new instance. In this case, they will not be cleaned up.
// Instead, we report periodically with RemoveWhenExpired=true,
// so even if reports are applied on a new instance, they will be cleaned up after TTL.
return EntityHealthInformation::CreateStatefulReplicaEntityHealthInformation(
this->PartitionId,
this->ReplicaId,
FABRIC_INVALID_INSTANCE_ID);
}
| 34.826165 | 192 | 0.644368 | [
"vector"
] |
8c9030036039a1640a3fdfaf8783844cc14aee64 | 8,723 | cpp | C++ | src/gendata.cpp | nileshrathi/libsnark-tutorial | 61a570683381c2154ed726ca6660cd2a1819ecd2 | [
"MIT"
] | null | null | null | src/gendata.cpp | nileshrathi/libsnark-tutorial | 61a570683381c2154ed726ca6660cd2a1819ecd2 | [
"MIT"
] | null | null | null | src/gendata.cpp | nileshrathi/libsnark-tutorial | 61a570683381c2154ed726ca6660cd2a1819ecd2 | [
"MIT"
] | null | null | null | #include <libff/common/default_types/ec_pp.hpp>
#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>
#include "libsnark/common/default_types/r1cs_ppzksnark_pp.hpp"
#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>
#include <libsnark/gadgetlib1/pb_variable.hpp>
#include <libsnark/gadgetlib1/gadgets/basic_gadgets.hpp>
#include <cassert>
#include <memory>
#include <chrono>
#include <libsnark/gadgetlib1/gadget.hpp>
using namespace libsnark;
using namespace libff;
#include<iostream>
#include <fstream>
using namespace std;
typedef libff::default_ec_pp ppT;
vector<vector<size_t>> nodes_coeff;
int random_number(int min,int max)
{
int randNum = rand()%(max-min + 1) + min;
return randNum;
}
/* Global Variables Defining properties of the system */
size_t number_of_chains=1000;
size_t number_of_users_per_shard=50000;
#define ONE pb_variable<libff::Fr<ppT>>(0)
int main (int argc, char* argv[]) {
typedef libff::Fr<ppT> field_T ;
default_r1cs_gg_ppzksnark_pp::init_public_params();
//test_r1cs_gg_ppzksnark<default_r1cs_gg_ppzksnark_pp>(1000, 100);
// Create protoboard
// number_of_chains=stoi(argv[1]);
//number_of_users_per_shard=number_of_users_per_shard/number_of_chains;
if(number_of_chains==0)
{
number_of_chains=1;
}
protoboard<field_T> pb;
pb_variable<field_T> x;
pb_variable<field_T> sym_1;
pb_variable<field_T> y;
pb_variable<field_T> sym_2;
pb_variable<field_T> out;
vector<pb_variable_array<field_T> > ledger_array;
vector<pb_variable_array<field_T> > blocks_array;
pb_variable_array<field_T> coefficients;
pb_variable_array<field_T> ledger_array_encoded;
vector<shared_ptr<inner_product_gadget<field_T> > > lip;
vector<shared_ptr<inner_product_gadget<field_T> > > bip;
pb_variable_array<field_T> blocks_array_encoded;
pb_variable_array<field_T> result_array_encoded;
// Allocate variables to protoboard
// The strings (like "x") are only for debugging purposes
out.allocate(pb, "out");
x.allocate(pb, "x");
sym_1.allocate(pb, "sym_1");
y.allocate(pb, "y");
sym_2.allocate(pb, "sym_2");
//resizing the ledger_aay to number of shards
ledger_array.resize(number_of_users_per_shard);
//allocating each ledger of ledger_array with num_of_users_per_shard elements
for(size_t i=0;i<number_of_users_per_shard;i++)
{
ledger_array[i].allocate(pb,number_of_chains,"every element contain and individual ledger");
}
//resizing the ledger_aay to number of shards
blocks_array.resize(number_of_users_per_shard);
//allocating each ledger of ledger_array with num_of_users_per_shard elements
for(size_t i=0;i<number_of_users_per_shard;i++)
{
blocks_array[i].allocate(pb,number_of_chains,"every element contain and individual ledger");
}
//Allocating the coefficients to be equal to number of chains is system
coefficients.allocate(pb,number_of_chains,"Coefficients for chain i");
//allocating encoded ledger
ledger_array_encoded.allocate(pb,number_of_users_per_shard,"encoded ledger for node i");
//allocating encoded ledger
blocks_array_encoded.allocate(pb,number_of_users_per_shard,"encoded ledger for node i");
//allocate the result array
result_array_encoded.allocate(pb,number_of_users_per_shard,"encoded_results");
lip.resize(number_of_users_per_shard);
for(int i=0;i<number_of_users_per_shard;i++)
{
lip[i].reset(new inner_product_gadget<field_T>(pb, ledger_array[i], coefficients, ledger_array_encoded[i], "ip"));
}
bip.resize(number_of_users_per_shard);
for(int i=0;i<number_of_users_per_shard;i++)
{
bip[i].reset(new inner_product_gadget<field_T>(pb, blocks_array[i], coefficients, blocks_array_encoded[i], "ip"));
}
// This sets up the protoboard variables
// so that the first one (out) represents the public
// input and the rest is private input
pb.set_input_sizes(pb.num_variables());
// Add R1CS constraints to protoboard
// x*x = sym_1
pb.add_r1cs_constraint(r1cs_constraint<field_T>(x, x, sym_1));
// sym_1 * x = y
pb.add_r1cs_constraint(r1cs_constraint<field_T>(sym_1, x, y));
// y + x = sym_2
pb.add_r1cs_constraint(r1cs_constraint<field_T>(y + x, 1, sym_2));
// sym_2 + 5 = ~out
pb.add_r1cs_constraint(r1cs_constraint<field_T>(sym_2 + 5, 1, out));
for(int i=0;i<number_of_users_per_shard;i++)
{
lip[i]->generate_r1cs_constraints();
}
for(int i=0;i<number_of_users_per_shard;i++)
{
bip[i]->generate_r1cs_constraints();
}
for(int i=0;i<number_of_users_per_shard;i++)
{
pb.add_r1cs_constraint(r1cs_constraint<field_T>(ledger_array_encoded[i] - blocks_array_encoded[i], 1, result_array_encoded[i]));
}
// Add witness values
pb.val(x) = 3;
pb.val(out) = 35;
pb.val(sym_1) = 9;
pb.val(y) = 27;
pb.val(sym_2) = pb.val(y)+pb.val(x);
for(int i=0;i<number_of_users_per_shard;i++)
{
for(int j=0;j<number_of_chains;j++)
{
pb.val(ledger_array[i][j])= random_number(1000,10000);
pb.val(blocks_array[i][j])= random_number(1000,10000);
}
}
for(int j=0;j<number_of_chains;j++)
{
pb.val(coefficients[j])= random_number(1,50);
}
for(int i=0;i<number_of_users_per_shard;i++)
{
lip[i]->generate_r1cs_witness();
}
for(int i=0;i<number_of_users_per_shard;i++)
{
bip[i]->generate_r1cs_witness();
}
for(int i=0;i<number_of_users_per_shard;i++)
{
pb.val(result_array_encoded[i])=pb.val(ledger_array_encoded[i])-pb.val(blocks_array_encoded[i]);
}
const r1cs_constraint_system<field_T> constraint_system = pb.get_constraint_system();
libff::print_header("R1CS GG-ppzkSNARK Generator");
r1cs_gg_ppzksnark_keypair<ppT> keypair = r1cs_gg_ppzksnark_generator<ppT>(constraint_system);
printf("\n"); libff::print_indent(); libff::print_mem("after generator");
libff::print_header("Preprocess verification key");
r1cs_gg_ppzksnark_processed_verification_key<ppT> pvk = r1cs_gg_ppzksnark_verifier_process_vk<ppT>(keypair.vk);
libff::print_header("R1CS GG-ppzkSNARK Prover");
auto proving_time_start = std::chrono::high_resolution_clock::now();
r1cs_gg_ppzksnark_proof<ppT> proof = r1cs_gg_ppzksnark_prover<ppT>(keypair.pk, pb.primary_input(), pb.auxiliary_input());
auto proving_time_end = std::chrono::high_resolution_clock::now();
printf("\n"); libff::print_indent(); libff::print_mem("after prover");
libff::print_header("R1CS GG-ppzkSNARK Verifier");
auto verification_time_start = std::chrono::high_resolution_clock::now();
const bool ans = r1cs_gg_ppzksnark_verifier_strong_IC<ppT>(keypair.vk, pb.primary_input(), proof);
auto verification_time_end = std::chrono::high_resolution_clock::now();
printf("\n"); libff::print_indent(); libff::print_mem("after verifier");
printf("* The verification result is: %s\n", (ans ? "PASS" : "FAIL"));
libff::print_header("R1CS GG-ppzkSNARK Online Verifier");
auto online_verification_time_start = std::chrono::high_resolution_clock::now();
const bool ans2 = r1cs_gg_ppzksnark_online_verifier_strong_IC<ppT>(pvk, pb.primary_input(), proof);
auto online_verification_time_end = std::chrono::high_resolution_clock::now();
assert(ans == ans2);
cout << "Number of R1CS constraints: " << constraint_system.num_constraints() << endl;
//cout << "Primary (public) input: " << pb.primary_input() << endl;
cout << "Auxiliary (private) input: " << pb.auxiliary_input() << endl;
cout << "Verification status: " << ans << endl;
cout<<"The verifier answer is "<<ans<<" "<<ans2<<"\n";
auto proving_time = std::chrono::duration_cast<std::chrono::microseconds>( proving_time_end - proving_time_start ).count();
auto verification_time= std::chrono::duration_cast<std::chrono::microseconds>( verification_time_end - verification_time_start ).count();
auto online_verifiction_time=std::chrono::duration_cast<std::chrono::microseconds>( online_verification_time_end - online_verification_time_start ).count();
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app);
outfile <<number_of_chains<<" "<<number_of_users_per_shard<<" "<<constraint_system.num_constraints()<<" "<<proving_time<<" "<<verification_time<<" "<<online_verifiction_time<<" "<<keypair.pk.size_in_bits()<<" "<<keypair.vk.size_in_bits()<<" "<<proof.size_in_bits()<<" "<<ans<<"\n";
outfile.close();
return 0;
}
| 29.569492 | 286 | 0.717643 | [
"vector"
] |
8c941fbdc664d02b0e9ed45eb3e906cc7f21d548 | 651 | cpp | C++ | src/base/integrator.cpp | shiinamiyuki/LuisaRender | 46f4d5baa3adf1923bbe1f854f3b0db2739e33bd | [
"BSD-3-Clause"
] | null | null | null | src/base/integrator.cpp | shiinamiyuki/LuisaRender | 46f4d5baa3adf1923bbe1f854f3b0db2739e33bd | [
"BSD-3-Clause"
] | null | null | null | src/base/integrator.cpp | shiinamiyuki/LuisaRender | 46f4d5baa3adf1923bbe1f854f3b0db2739e33bd | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Mike on 2021/12/14.
//
#include <base/scene.h>
#include <base/sampler.h>
#include <sdl/scene_node_desc.h>
#include <base/integrator.h>
namespace luisa::render {
Integrator::Integrator(Scene *scene, const SceneNodeDesc *desc) noexcept
: SceneNode{scene, desc, SceneNodeTag::INTEGRATOR},
_sampler{scene->load_sampler(desc->property_node_or_default(
"sampler", SceneNodeDesc::shared_default_sampler("Independent")))},
_light_sampler{scene->load_light_sampler(desc->property_node_or_default(
"light_sampler", SceneNodeDesc::shared_default_light_sampler("Uniform")))} {}
}// namespace luisa::render
| 32.55 | 87 | 0.735791 | [
"render"
] |
8c9bc22d5b9275a701b0501e61327572dd1e29d6 | 3,568 | cpp | C++ | src/ls-hubd/test/test_api_version_parser.cpp | webosose/luna-service2 | cb41d1bf417aea81747bb4ca9a5c8e4c34575d3e | [
"Apache-2.0"
] | 7 | 2018-03-19T22:06:27.000Z | 2021-03-15T23:17:21.000Z | src/ls-hubd/test/test_api_version_parser.cpp | webosce/luna-service2 | 19ea833074bd9e091b13f3a520705d68ff75c29c | [
"Apache-2.0"
] | 3 | 2018-09-08T05:35:18.000Z | 2018-09-29T05:28:22.000Z | src/ls-hubd/test/test_api_version_parser.cpp | webosose/luna-service2 | cb41d1bf417aea81747bb4ca9a5c8e4c34575d3e | [
"Apache-2.0"
] | 12 | 2018-03-22T04:21:08.000Z | 2021-11-19T13:03:20.000Z | // Copyright (c) 2015-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#include <iostream>
#include <vector>
#include <luna-service2/lunaservice.hpp>
#include <gtest/gtest.h>
#include <pbnjson.hpp>
#include "../hub.hpp"
#include "../permission.hpp"
#include "../file_parser.hpp"
#include "../permissions_map.hpp"
#include "../service_permissions.hpp"
#include "../security.hpp"
static std::string error_msg;
class VersionParser : public ::testing::Test
{
protected:
void SetUp() override
{
}
void parseJsons(std::vector<std::string> jsons)
{
PermissionArray perms;
perms.push_back(mk_ptr(LSHubPermissionNewRef("com.webos.foo", "/usr/bin/foo"), LSHubPermissionUnref));
perms.push_back(mk_ptr(LSHubPermissionNewRef("com.webos.bar", "/usr/bin/bar"), LSHubPermissionUnref));
for (auto &json: jsons)
{
LS::Error error;
ASSERT_TRUE(_parser.parse(json, pbnjson::JSchema::AllSchema()));
ParseJSONGetAPIVersions(_parser.getDom(), "localhost", perms, error);
if (error.isSet())
{
error_msg = error.get()->message;
return;
}
}
for (auto & perm : perms)
{
PermissionsMap &pmap = SecurityData::CurrentSecurityData().permissions;
pmap.Add(std::move(perm));
}
}
std::string valid_json = R"json({
"versions": {
"com.webos.foo": "0.1",
"com.webos.bar": "4.2"
}
})json";
std::string invalid_json = R"json({
"versions": []
})json";
std::string unknown_service_json = R"json({
"versions": {
"com.webos.foo": "0.1"
}
})json";
std::string service_duplication_json = R"json({
"versions": {
"com.webos.foo": "0.1"
}
})json";
pbnjson::JDomParser _parser;
};
TEST_F(VersionParser, VersionParserTest)
{
auto getVersion = [](const std::string &sname, const std::string &exe) -> const pbnjson::JValue
{
PermissionsMap &pmap = SecurityData::CurrentSecurityData().permissions;
auto permission = pmap.LookupServicePermissions(sname.c_str());
return permission
? LSHubPermissionGetAPIVersion(LSHubServicePermissionsLookupPermission(permission, exe.c_str()))
: pbnjson::JValue();
};
parseJsons({valid_json});
EXPECT_EQ(getVersion("com.webos.foo", "/usr/bin/foo"), pbnjson::JValue("0.1"));
EXPECT_EQ(getVersion("com.webos.bar", "/usr/bin/bar"), pbnjson::JValue("4.2"));
EXPECT_TRUE(error_msg.empty());
parseJsons({valid_json, service_duplication_json});
EXPECT_EQ(error_msg, "Error reading version from the JSON file: localhost. "
"'com.webos.foo' service already has version set to '0.1'.");
error_msg.clear();
}
int
main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 29.00813 | 112 | 0.626121 | [
"vector"
] |
8ca5bbe41def479a2fc8952d825e31dcfed47c24 | 1,780 | cpp | C++ | functions.cpp | evan3139/Final | 5e5b2fa2402099ad4e847dcb4f759c9db648de3c | [
"MIT"
] | null | null | null | functions.cpp | evan3139/Final | 5e5b2fa2402099ad4e847dcb4f759c9db648de3c | [
"MIT"
] | null | null | null | functions.cpp | evan3139/Final | 5e5b2fa2402099ad4e847dcb4f759c9db648de3c | [
"MIT"
] | null | null | null | /**
* Authors: Evan Wildenhain & John Sullivan.
**/
#include "functions.h"
#include "bigint/bigint.h"
frequency::frequency()
{
frequencies.push_back(0);
}
frequency::frequency(const std::vector<int> &f)
{
frequencies = f;
}
//Gets the size of a frequency vector
size_t frequency::getSize()
{
return frequencies.size();
}
//Allows the use of index when referencing a frequency vector
int frequency::operator[](size_t index) const
{
return frequencies[index];
}
std::vector<int> frequency::freqValue(std::ifstream &infile)
{
//A vector with the length of 26^3 is created.
std::vector<int> freqs (17576);
char ch, b[3];
int n = 0, result = 0;
while(infile.get(ch))
{
//Makes every char lowercase and makes sure they are a letter that falls between a and z
ch = tolower(ch);
if(((ch -'a') >= 0 && (ch-'a') <= 25))
{
//If n is less than 3 put the first 3 letters into the array
if (n <= 2) b[n] = ch;
//Once it equals 3 for the first time it adds the frequency value of those 3 letters to the vector
else if(n==3) result = (int)((b[0] - 'a') * 676) + (int)((b[1] - 'a') * 26) + (int)(b[2] - 'a');
else
{
//Once n is greater than 2 it will shift each letter to the back of the array pushing the first letter out and putting
//A new letter in the last index. and then adding the value to the vector
freqs[result] += 1;
result = (int)((b[0] - 'a') * 676) + (int)((b[1] - 'a') * 26) + (int)(b[2] - 'a');
b[0] = b[1];
b[1] = b[2];
b[2] = ch;
}
n++;
}
}
freqs[result] += 1;
return freqs;
}
| 29.180328 | 134 | 0.542135 | [
"vector"
] |
8cb2dbc5eb04381d80f5019d1b32bf27444255b0 | 794 | cc | C++ | leetcode/two_sum.cc | sservulo/programming-challenges | 65a872c96ab5cda347c0ee6b6742a07d55ba9d33 | [
"Apache-2.0"
] | null | null | null | leetcode/two_sum.cc | sservulo/programming-challenges | 65a872c96ab5cda347c0ee6b6742a07d55ba9d33 | [
"Apache-2.0"
] | null | null | null | leetcode/two_sum.cc | sservulo/programming-challenges | 65a872c96ab5cda347c0ee6b6742a07d55ba9d33 | [
"Apache-2.0"
] | null | null | null | /*
Other possible solutions are:
1) Sort the array and keep pointers to the start and the end until they cross or we find a match
2) Traverse the array and store the values in a hash table, verifying for each entry if the complement is already into the hash table
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> retval;
for(size_t idx0 = 0; idx0 < nums.size(); idx0++){
for(size_t idx1 = idx0 + 1; idx1 < nums.size(); idx1++){
if(nums[idx0] == target - nums[idx1]){
retval = {idx0, idx1};
return retval;
}
}
}
return retval;
}
}; | 39.7 | 139 | 0.508816 | [
"vector"
] |
8cbe8c8de0b1935d42edabb672788e324924d82e | 139 | cpp | C++ | chapter6/exercise6_54.cpp | zerenlu/primer_Cpp | 4882e244ef90c9f69e344171468b8cfc8308b2c4 | [
"MIT"
] | null | null | null | chapter6/exercise6_54.cpp | zerenlu/primer_Cpp | 4882e244ef90c9f69e344171468b8cfc8308b2c4 | [
"MIT"
] | null | null | null | chapter6/exercise6_54.cpp | zerenlu/primer_Cpp | 4882e244ef90c9f69e344171468b8cfc8308b2c4 | [
"MIT"
] | null | null | null | #include<vector>
using std::vector;
int foo(int, int);
using fooType = int(*)(int, int);
vector<decltype(foo)*> v;
vector<fooType> v2;
| 12.636364 | 33 | 0.669065 | [
"vector"
] |
bc49018e531c2a11fd284a41a54ad1b2183827e0 | 3,627 | hpp | C++ | Schedule.hpp | mbilalakmal/shoAIb | a96db6e61def3386951a401f409cc76064bb0c1c | [
"MIT"
] | 2 | 2019-10-07T15:29:27.000Z | 2020-03-05T07:25:22.000Z | Schedule.hpp | mbilalakmal/shoAIb | a96db6e61def3386951a401f409cc76064bb0c1c | [
"MIT"
] | 1 | 2020-03-05T07:38:36.000Z | 2020-03-05T07:38:36.000Z | Schedule.hpp | mbilalakmal/shoAIb | a96db6e61def3386951a401f409cc76064bb0c1c | [
"MIT"
] | null | null | null | #ifndef SCHEDULE
#define SCHEDULE
#include<vector>
#include<unordered_map>
#include"Lecture.hpp"
#include"Room.hpp"
using namespace std;
//describes a whole week's schedule in time-space slots occupied by lectures
class Schedule{
//crossover occurs by randomly swapping some classes between two schedules
friend void crossover(Schedule&, Schedule&, int&);
//swap function used in assignment operator and other
friend void swap(Schedule&, Schedule&);
public:
//fitness divided by the whole population's fitness
double relativeFitness;
//cum probability of being selected in fitness proportionate
double cumulativeProb;
//default constructor
Schedule(
int,
const unordered_map<int, Room*>&,
const unordered_map<string, Course*>&,
const unordered_map<string, Teacher*>&,
const unordered_map<string, StudentSection*>&,
const vector<Lecture*>&
);
//copy constructor
Schedule(const Schedule&);
//assignment operator
Schedule& operator = (Schedule);
//destructor
~Schedule();
//initialize schedule with random slots
void initialize();
//mutation occurs by randomly swapping some classes within a schedule
void mutation();
const vector< vector<Lecture*> >& getSlots() const {return slots;}
const unordered_map<Lecture*, vector<int> >& getClasses() const {return classes;}
// const vector<int>& getConstraints() const {return constraints;}
double getFitness() const {return fitness;}
/*
FOR TESTING PURPOSE ONLY
*/
void printSchedule(bool) const;
private:
//day * time_slot * rooms
vector< vector<Lecture*> > slots;
//Lecture mapped to it's slots
unordered_map< Lecture*, vector<int> > classes;
//GA Parameters
const double mutationRate;
const double crossoverRate;
const int mutationSize;
const int crossoverSize;
//Aggregated objects
const unordered_map<int, Room*>&
rooms;
const unordered_map<string, Course*>&
courses;
const unordered_map<string, Teacher*>&
teachers;
const unordered_map<string, StudentSection*>&
sections;
const vector<Lecture*>&
lectures;
//used to calc fitness [true = that constraint is fulfilled]
mutable vector< vector< vector<bool> > >
lectureConstraints;
mutable vector< vector<bool> >
teacherConstraints;
mutable vector< vector<bool> >
sectionConstraints;
//schedule's score for complying with constraints
double fitness;
//seed value for schedule's random values
int seed;
//calculate score of schedule based on given constraints
void calculateFitness();
//checks each constraint for all classes and put true/false in the vector
void checkConstraints() const;
//adds all the entries in the bool vector, multiplies, and returns a single fitness value
double addConstraintsWeights();
Room* getRoomById(int) const;
// //helper functions to check section & teacher constraints
// int maxConsecutive(const vector< vector<int> >&) const;
// int maxDaily(const vector< vector<int> >&) const;
// int daysOff(const vector< vector<int> >&) const;
// bool oneAtATime(const vector< vector<int> >&) const;
};
#endif
| 28.559055 | 97 | 0.626137 | [
"vector"
] |
bc4cd20263be292a44c7d7d61f6411580b26e5ec | 2,982 | cpp | C++ | amd_geometryfx/src/GeometryFXUtility_Internal.cpp | mehdy6/GeometryFXx | 3499d3f37a60d3c072296296d7450b1394e912b4 | [
"MIT"
] | 234 | 2016-01-26T13:40:51.000Z | 2022-03-14T10:03:41.000Z | amd_geometryfx/src/GeometryFXUtility_Internal.cpp | mehdy6/GeometryFXx | 3499d3f37a60d3c072296296d7450b1394e912b4 | [
"MIT"
] | 7 | 2016-01-27T18:41:21.000Z | 2018-09-27T10:50:19.000Z | amd_geometryfx/src/GeometryFXUtility_Internal.cpp | mehdy6/GeometryFXx | 3499d3f37a60d3c072296296d7450b1394e912b4 | [
"MIT"
] | 20 | 2016-02-05T23:38:58.000Z | 2022-01-20T12:10:05.000Z | //
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 "GeometryFXUtility_Internal.h"
namespace AMD
{
namespace GeometryFX_Internal
{
////////////////////////////////////////////////////////////////////////////////
bool CreateShader(ID3D11Device *device, ID3D11DeviceChild **shader, const size_t shaderSize,
const void *shaderSource, ShaderType::Enum shaderType, ID3D11InputLayout **inputLayout,
const int inputElementCount, const D3D11_INPUT_ELEMENT_DESC *inputElements)
{
if (inputLayout)
{
device->CreateInputLayout(
inputElements, inputElementCount, shaderSource, shaderSize, inputLayout);
}
switch (shaderType)
{
case ShaderType::Compute:
device->CreateComputeShader(
shaderSource, shaderSize, nullptr, (ID3D11ComputeShader **)shader);
break;
case ShaderType::Pixel:
device->CreatePixelShader(
shaderSource, shaderSize, nullptr, (ID3D11PixelShader **)shader);
break;
case ShaderType::Vertex:
device->CreateVertexShader(
shaderSource, shaderSize, nullptr, (ID3D11VertexShader **)shader);
break;
case ShaderType::Hull:
device->CreateHullShader(
shaderSource, shaderSize, nullptr, (ID3D11HullShader **)shader);
break;
case ShaderType::Domain:
device->CreateDomainShader(
shaderSource, shaderSize, nullptr, (ID3D11DomainShader **)shader);
break;
case ShaderType::Geometry:
device->CreateGeometryShader(
shaderSource, shaderSize, nullptr, (ID3D11GeometryShader **)shader);
break;
}
return true;
}
} // namespace GeometryFX_Internal
} // namespace AMD
| 40.297297 | 93 | 0.653588 | [
"geometry"
] |
bc533f3c632797462d1b54a3e3c124bab3eb486c | 12,442 | cpp | C++ | Day22/Day22.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | 1 | 2018-12-05T18:32:50.000Z | 2018-12-05T18:32:50.000Z | Day22/Day22.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | Day22/Day22.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <array>
#include <algorithm>
#include <cmath>
#include "Coordinate.h"
#include "Node.h"
/*
- region divided into squares (type: rocky, narrow, wet) of X,Y coordinates (starting at 0,0)
- type defined by erosion level
- erosion level defined by geological index
- geolocial index derived from 5 rules (the first applicable counts)
1) (0,0) has geological index of 0
2) target coordinate has geological index 0
3) If Y=0 -> geoIdx = X*16807
4) If X=0 -> geoIdx = Y*48271
5) Else: geoIdx = erosionLvl(X-1,Y) * erosionLvl(X,Y-1)
- Erosion level = (geoIdx*depth)%20183
- Region type = erosionLvl % 3 (where 0:rocky, 1:wet, 2:narrow)
*/
//void removeElementFromList(Node, std::list<Node>&);
bool listContains(Node, std::list<Node>&);
std::list<Node> getFeasibleChildren(Node&, std::list<Node>&, std::list<Node>&, const std::vector<std::vector<Coordinate>>&);
//Tool getCommonTool(const Node, const Node, const std::vector<std::vector<Coordinate>>&);
//int getStepCost(const Node, const Node);
ll estimateHScore(Node&, const Node&, const std::vector<std::vector<Coordinate>>&);
//bool lowestFcost(const Node&, const Node&);
bool smallerDistance(const Node&, const Node&);
//bool isFeasibleTransition(const Node, const Coordinate&);
bool isValidTool(Tool, Coordinate);
std::string toolStr(Tool);
std::string typeStr(int);
void printMap(const std::vector<std::vector<Coordinate>>&, size_t , size_t);
int main() {
// INPUT Day17
//depth: 3066
//target : 13, 726
int depth = 3066;
int xTarget = 13;
int yTarget = 726;
size_t nCols = 1000;
size_t nRows = 2000;
Coordinate* target = new Coordinate(xTarget, yTarget,0 );
// Test Input
//depth = 510;
//xTarget = 10;
//yTarget = 10;
//nCols = 16+1;
//nRows = 16+1;
//target = new Coordinate(10, 10,0);
target->setIsTarget(true);
Coordinate* mouth = new Coordinate(0, 0, 0);
// Map
std::vector<std::vector<Coordinate>> map(nCols, std::vector<Coordinate>(nRows, Coordinate(0, 0)));
// Init Map
ll risk = 0;
map[0][0] = *mouth;
map[xTarget][yTarget] = *target;
// Assign Type to borders
for (int xC = 1; xC < nCols; ++xC) {
map[xC][0] = Coordinate(xC, 0, (ll)xC * 16807);
if (xC <= xTarget) risk += map[xC][0].getType();// add risk
}
for (int yC = 1; yC < nRows; ++yC) {
map[0][yC] = Coordinate(0, yC, (ll)yC * 48271);
if (yC <= yTarget) risk += map[0][yC].getType();// add risk
}
// Fill map
size_t s, xC, yC;
ll gIdx;
for (s = 2; s < (nCols + nRows - 2); ++s) {
for (xC = 1; xC < nCols; ++xC) {
yC = s - xC;
if (yC < 1 || yC >= nRows) continue;
//std::cout << "(" << xC << "," << yC << ")";
if (xC != xTarget || yC != yTarget) { // do not redefine type of target with non-zero geoIdx
gIdx = map[xC - 1][yC].getELvl() * map[xC][yC - 1].getELvl();
map[xC][yC] = Coordinate((int)xC, (int)yC, gIdx);
}
if (xC <= xTarget && yC <= yTarget) risk += map[xC][yC].getType(); // add risk
}
//std::cout << std::endl;
}
//printMap(map, xTarget, yTarget);
// Show resulting risk (mouth and target have risk 0)
std::cout << "P1: Risk: " << risk << std::endl; // solution: 10115
//////////////////////////////////////////////////////////////////
////////////////////////// PART TWO: /////////////////////////////
//////////////////////////////////////////////////////////////////
// - two tools, can use, one of them or none (torch, climbing gear)
// - rocky: need to use torch or climbing
// - wet: need to use climbing gear or neither
// - narrow: need to use torch or neither
//
// - start at mouth with torch
// - can move up, down, left, right
// - one step: 1 Minute
// - switching tools: 7 Minutes
// - at target u need the torch
// - valid type transitions:
// - 0: torch allows rocky(0)[.] <-> narrow(2)[|]
// - 1: climbing gear allows rocky(0)[.] <-> wet(1)[=]
// - 2: neither allows wet(1)[=] <-> narrow(2)[|]
/////////////////////////////////////////////////////////////////////////////////////////
// A* Method
// ================
// g(n): exact cost from start to node n
// h(n): estimated cost from node to target
// * If h(n) is always <= the cost of moving from n to the goal,
// then A* is guaranteed to find a shortest path.
// The lower h(n) is, the more node A* expands, making it slower.
// * If h(n) is sometimes > the cost of moving from n to the goal,
// then A* is NOT guaranteed to find a shortest path, but it can run faster.
//
// Algo Outline:
// OPEN = priority queue containing START
// CLOSED = empty set
// while lowest rank in OPEN is not the GOAL:
// current = remove lowest rank item from OPEN
// add current to CLOSED
// for neighbors of current:
// cost = g(current) + movementcost(current, neighbor)
// if neighbor in OPEN and cost less than g(neighbor):
// remove neighbor from OPEN, because new path is better
// if neighbor in CLOSED and cost less than g(neighbor):
// remove neighbor from CLOSED
// if neighbor not in OPEN and neighbor not in CLOSED:
// set g(neighbor) to cost
// add neighbor to OPEN
// set priority queue rank to g(neighbor) + h(neighbor)
// set neighbor's parent to current
//
// reconstruct reverse path from goal to start
// by following parent pointers
/////////////////////////////////////////////////////////////////////////////////////////
std::list<Node> open, closed, neighbor;
Node goalNode;
Node start(mouth);
Node goal(target);
goal.setNodeProperties(nullptr, LLONG_MAX, 0, torch);
start.setNodeProperties(&start, 0, estimateHScore(start, goal, map), torch);
Node cur;
open.push_back(start);
//while (open.front() != goal) {
while (!open.empty()) {
cur = open.front(); // Assign the lowest rank member of <open> to <cur>
open.pop_front(); // Remove the lowest rank member from the OPEN list
closed.push_back(cur); // Add the lowest rank member <cur> to CLOSED list
if (cur.getLocation().x == goal.getLocation().x &&
cur.getLocation().y == goal.getLocation().y &&
cur.getTool() == torch) {
// Store goal node for path reconstruction
goal = cur;
std::cout << "Reached Goal Node: " << cur.getGcost() << std::endl;
break;
}
// Get feasible neibhbors (UP,RIGH,DOWN,LEFT, but not at neg. location and with valid transition)
neighbor = getFeasibleChildren(cur, open, closed, map);
for (std::list<Node>::iterator it = neighbor.begin(); it != neighbor.end(); ++it) {
open.push_back(*it);
}
// Sort according to estimated total cost
open.sort(smallerDistance);
}
//testFeasibleTransition();
std::cout << "Cost so far of 'Start': " << start.getGcost() << std::endl;
std::cout << "Cost of goal element: " << goal.getGcost() << std::endl;
std::vector<Node> optimalPath;
Node parent = goal;
parent.printNode();
optimalPath.push_back(parent);
size_t goalX = start.getLocation().x;
size_t goalY = start.getLocation().y;
std::cout << "Best path found so far (" << optimalPath.size() << "): ";
while ((parent.getLocation().x != goalX) || (parent.getLocation().y != goalY)) {
std::cout << "[" << parent.getLocation().x << "," << parent.getLocation().y << "]-";
if (parent.getParent() == nullptr) { std::cout << " Optimal Path not restoreable" << std::endl; }
parent = *parent.getParent();
optimalPath.push_back(parent);
}
// Part 2: 990
// free memory
delete target, mouth;
return 0;
}
// Check if Node cur is element of list open
bool listContains(Node cur, std::list<Node>& list) {
std::list<Node>::iterator findIter = std::find(list.begin(), list.end(), cur);
if (findIter == list.end()) {
//std::cout << "Element [" << cur.getLocation().x << "," << cur.getLocation().y << "] NOT found in list" << std::endl;
return false;
}
else {
//std::cout << "Element [" << cur.getLocation().x << "," << cur.getLocation().y << "] FOUND in list" << std::endl;
return true;
}
}
// Get feasible Children for current Node <cur> in Map <map>
// TODO: Make sure we don't go backwards (should be ok, by design)
std::list<Node> getFeasibleChildren(Node& cur, std::list<Node>& open, std::list<Node>& closed, const std::vector<std::vector<Coordinate>>& map) {
std::list<Node> children;
Node child;
int nCols = (int)map.size();
int nRows = (int)map.front().size();
// Get Nodes on same location as cur but with different tool
for (int i = 0; i < 3; ++i) {
if (isValidTool(Tool(i), map[cur.getLocation().x][cur.getLocation().y]) && cur.getTool() != Tool(i)) {
child = Node(&map[cur.getLocation().x][cur.getLocation().y]);
child.setNodeProperties(&cur, cur.getGcost() + 7, LLONG_MAX, Tool(i));
if (!(listContains(child, open)) && !(listContains(child, closed))) {
children.push_back(child);
//std::cout << "Added Node [" << cur.getLocation().x << "," << cur.getLocation().y << "] with new Tool " << toolStr(Tool(i)) << std::endl;
}
}
}
// travel directions: 0:UP, 1:RIGHT, 2:DOWN, 3:LEFT
int dx[] = { 0, 1, 0, -1 };
int dy[] = { -1, 0, 1, 0 };
int newX, newY;
// Check all four direcitions around OPEN wich can be reached with same tool
for (int i = 0; i < 4; ++i) {
newX = (int)cur.getLocation().x + dx[i];
newY = (int)cur.getLocation().y + dy[i];
// not in solid ground or outside map
if (!(newX >= 0 && newY >= 0 && newX < nCols && newY < nRows)) { continue; }
if (isValidTool(cur.getTool(), map[newX][newY])) {
child = Node(&map[newX][newY]);
child.setNodeProperties(&cur, cur.getGcost() + 1, LLONG_MAX, cur.getTool());
if (!(listContains(child, open)) && !(listContains(child, closed))) {
children.push_back(child);
//std::cout << "Added new Node [" << newX << "," << newY << "] with Tool " << toolStr(cur.getTool()) << std::endl;
}
}
}
//std::cout << std::endl;
return children;
}
// Get the tool which is common to the current and next node
// Valid type transitions:
// - 0: torch allows rocky(0)[.] <-> narrow(2)[|]
// - 1: climbing gear allows rocky(0)[.] <-> wet(1)[=]
// - 2: neither allows wet(1)[=] <-> narrow(2)[|]
bool isValidTool(Tool tool, Coordinate curC) {
if (curC.getType() == 0 && (tool == 0 || tool == 1)) return true;
if (curC.getType() == 1 && (tool == 1 || tool == 2)) return true;
if (curC.getType() == 2 && (tool == 2 || tool == 0)) return true;
return false;
}
// Return matching string for tool integer
// - 0: torch allows rocky(0) and narrow(2)
// - 1: climbing gear allows rocky(0) and wet(1)
// - 2: neither allows wet(1) and narrow(2)
std::string toolStr(Tool tool) {
if (tool == torch) return "torch";
else if (tool == climbingGear) return "climbing gear";
else if (tool == neither) return "neither";
else return "undefined tool code";
}
// Return matching string for ground type integer
// - 0: torch allows rocky(0) and narrow(2)
// - 1: climbing gear allows rocky(0) and wet(1)
// - 2: neither allows wet(1) and narrow(2)
std::string typeStr(int type) {
if (type == 0) return "rocky";
else if (type == 1) return "wet";
else if (type == 2) return "narrow";
else return "undefined type code";
}
void printMap(const std::vector<std::vector<Coordinate>>& map,size_t tX, size_t tY) {
int nCols = (int)map.size();
int nRows = (int)map.front().size();
for (int i = 0; i < nRows; ++i) {
std::cout << i << ":\t";
for (int j = 0; j < nCols; ++j) {
if (i == 0 && j == 0) {
std::cout << "M";
}
else if (i == tY && j == tX) {
std::cout << "T";
}
else if (map[j][i].getType() == 0) { // rocky
std::cout << ".";
}
else if (map[j][i].getType() == 1) { // wet
std::cout << "=";
}
else if (map[j][i].getType() == 2) { // narrow
std::cout << "|";
}
else { // undef
// do nothing
std::cout << "*";
}
}
std::cout << std::endl;
}
}
// Estimate cost from current location <node> to <target>
ll estimateHScore(Node& node, const Node& target, const std::vector<std::vector<Coordinate>>& map) {
size_t deltaX = target.getLocation().x - node.getLocation().x;
size_t deltaY = target.getLocation().y - node.getLocation().y;
ll fScore = 0;
// Simple Manhatten Distance so far
fScore = std::abs((ll)deltaX) + std::abs((ll)deltaY);
return fScore;
}
bool smallerDistance(const Node& lhs, const Node& rhs) {
if (lhs.getGcost() < rhs.getGcost()) return true;
else return false;
}
| 33.446237 | 145 | 0.60336 | [
"vector",
"solid"
] |
bc546dd31475d359f7c9f72996e3eadcf3325466 | 1,733 | hpp | C++ | include/mgard-x/MDR/Interleaver/InterleaverInterface.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | include/mgard-x/MDR/Interleaver/InterleaverInterface.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | include/mgard-x/MDR/Interleaver/InterleaverInterface.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | #ifndef _MDR_INTERLEAVER_INTERFACE_HPP
#define _MDR_INTERLEAVER_INTERFACE_HPP
#include "../../RuntimeX/RuntimeX.h"
namespace mgard_x {
namespace MDR {
namespace concepts {
// level data interleaver: interleave level coefficients
template <mgard_x::DIM D, typename T> class InterleaverInterface {
public:
virtual ~InterleaverInterface() = default;
virtual void interleave(T const *data, const std::vector<SIZE> &dims,
const std::vector<SIZE> &dims_fine,
const std::vector<SIZE> &dims_coasre,
T *buffer) const = 0;
virtual void reposition(T const *buffer, const std::vector<SIZE> &dims,
const std::vector<SIZE> &dims_fine,
const std::vector<SIZE> &dims_coasre,
T *data) const = 0;
virtual void print() const = 0;
};
} // namespace concepts
} // namespace MDR
} // namespace mgard_x
namespace mgard_m {
namespace MDR {
namespace concepts {
// level data interleaver: interleave level coefficients
template <typename HandleType, mgard_x::DIM D, typename T>
class InterleaverInterface {
public:
virtual ~InterleaverInterface() = default;
virtual void
interleave(mgard_x::SubArray<D, T, mgard_x::CUDA> decomposed_data,
mgard_x::SubArray<1, T, mgard_x::CUDA> *levels_decomposed_data,
int queue_idx) const = 0;
virtual void
reposition(mgard_x::SubArray<1, T, mgard_x::CUDA> *levels_decomposed_data,
mgard_x::SubArray<D, T, mgard_x::CUDA> decomposed_data,
int queue_idx) const = 0;
virtual void print() const = 0;
};
} // namespace concepts
} // namespace MDR
} // namespace mgard_m
#endif
| 29.87931 | 80 | 0.652626 | [
"vector"
] |
bc59561e9aba7fa2cdcb6bcbd0f2e8688b6f3070 | 9,811 | hh | C++ | src/backends/bullet/bullet.hh | rlofc/GameDevelopementTemplates | 5b52eafb7350c2bb51b3947db82cb8f908077925 | [
"Unlicense"
] | 42 | 2017-02-25T18:46:36.000Z | 2022-01-12T01:30:41.000Z | src/backends/bullet/bullet.hh | rlofc/GameDevelopementTemplates | 5b52eafb7350c2bb51b3947db82cb8f908077925 | [
"Unlicense"
] | 5 | 2017-03-04T17:44:36.000Z | 2017-03-04T17:46:11.000Z | src/backends/bullet/bullet.hh | rlofc/GameDevelopementTemplates | 5b52eafb7350c2bb51b3947db82cb8f908077925 | [
"Unlicense"
] | 2 | 2017-11-26T02:55:18.000Z | 2020-05-19T01:45:56.000Z | #ifndef GDT_BULLET_HEADER_INCLUDED
#define GDT_BULLET_HEADER_INCLUDED
#include <btBulletDynamicsCommon.h>
#include "backends/blueprints/physics.hh"
namespace gdt::physics::bullet {
static btVector3 vec3_to_bt(math::vec3 v)
{
return btVector3(v.x, v.y, v.z);
}
static math::vec3 bt_to_vec3(btVector3 v)
{
return math::vec3(v.getX(), v.getY(), v.getZ());
}
class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback {
public:
ClosestNotMe(btRigidBody* me, btVector3 a, btVector3 b)
: btCollisionWorld::ClosestRayResultCallback(a, b)
{
m_me = me;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,
bool normalInWorldSpace)
{
if (rayResult.m_collisionObject == m_me) {
return 1.0;
}
return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
protected:
btRigidBody* m_me;
};
class backend;
class bullet_shape : public blueprints::physics::shape {
private:
std::unique_ptr<btCollisionShape> _s;
public:
bullet_shape(std::unique_ptr<btCollisionShape> s) : _s(std::move(s))
{
}
bullet_shape(bullet_shape&& b) : _s(std::move(b._s))
{
}
bullet_shape& operator=(bullet_shape&& other) noexcept
{
_s = std::move(other._s);
return *this;
}
btCollisionShape* get_impl() const
{
return _s.get();
}
};
class bullet_static_body : public blueprints::physics::static_body {
private:
std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>> _impl;
btDiscreteDynamicsWorld* _world;
public:
bullet_static_body()
{
}
bullet_static_body(const bullet_static_body& b) = delete;
bullet_static_body(bullet_static_body&& b) : _impl(std::move(b._impl)), _world(b._world)
{
}
bullet_static_body& operator=(bullet_static_body&& other) noexcept
{
_impl = std::move(other._impl);
_world = other._world;
return *this;
}
bullet_static_body(btDiscreteDynamicsWorld* world,
std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>>
impl)
: _impl(std::move(impl)), _world(world)
{
}
virtual ~bullet_static_body()
{
}
};
class bullet_rigid_body : public blueprints::physics::rigid_body {
private:
std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>> _impl;
btDiscreteDynamicsWorld* _world;
public:
bullet_rigid_body()
{
}
bullet_rigid_body(const bullet_rigid_body& b) = delete;
bullet_rigid_body(bullet_rigid_body&& b) : _impl(std::move(b._impl)), _world(b._world)
{
}
bullet_rigid_body& operator=(bullet_rigid_body&& other) noexcept
{
_impl = std::move(other._impl);
_world = other._world;
return *this;
}
bullet_rigid_body(btDiscreteDynamicsWorld* world,
std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>>
impl)
: _impl(std::move(impl)), _world(world)
{
}
virtual ~bullet_rigid_body()
{
}
void disable_sleep()
{
_impl.get()->setActivationState(DISABLE_DEACTIVATION);
}
void update_transform(math::mat4* t) override
{
btTransform trans;
_impl.get()->getMotionState()->getWorldTransform(trans);
trans.getOpenGLMatrix((btScalar*)t);
}
void set_gravity(math::vec3 g) override
{
_impl.get()->setGravity(vec3_to_bt(g));
}
void set_actor_params() override
{
_impl.get()->setAngularFactor(0);
_impl.get()->setSleepingThresholds(0.0, 0.0);
_impl.get()->setRestitution(0);
}
void reposition(math::vec3 position)
{
btTransform initialTransform;
initialTransform.setOrigin(vec3_to_bt(position));
initialTransform.setRotation(btQuaternion(0, 0, 0, 1));
_impl.get()->setWorldTransform(initialTransform);
_impl.get()->getMotionState()->setWorldTransform(initialTransform);
}
void stop() override
{
btVector3 antislide = _impl.get()->getLinearVelocity() * -1;
_impl.get()->applyCentralImpulse(antislide);
}
void impulse(math::vec3 v) override
{
_impl.get()->applyCentralImpulse(vec3_to_bt(v));
}
float nearest_collision(math::vec3 from, math::vec3 to) override
{
ClosestNotMe res(_impl.get(), vec3_to_bt(from), vec3_to_bt(to));
_world->rayTest(vec3_to_bt(from), vec3_to_bt(to), res);
if (res.hasHit()) {
math::vec3 pos = get_pos();
return (pos.y - res.m_hitPointWorld.getY());
}
return 999999999999.0;
}
math::vec3 get_pos() override
{
btTransform trans;
_impl.get()->getMotionState()->getWorldTransform(trans);
return bt_to_vec3(trans.getOrigin());
}
};
class backend
: public blueprints::physics::backend<bullet_rigid_body, bullet_static_body, bullet_shape> {
public:
std::unique_ptr<btBroadphaseInterface> broadphase;
std::unique_ptr<btDefaultCollisionConfiguration> collisionConfiguration;
std::unique_ptr<btCollisionDispatcher> dispatcher;
std::unique_ptr<btSequentialImpulseConstraintSolver> solver;
std::unique_ptr<btDiscreteDynamicsWorld> dynamicsWorld;
btCollisionShape* fallShape;
btConvexShape* fallShape2;
backend()
{
broadphase = std::make_unique<btDbvtBroadphase>();
collisionConfiguration = std::make_unique<btDefaultCollisionConfiguration>();
dispatcher = std::make_unique<btCollisionDispatcher>(collisionConfiguration.get());
solver = std::make_unique<btSequentialImpulseConstraintSolver>();
dynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>(
dispatcher.get(), broadphase.get(), solver.get(), collisionConfiguration.get());
dynamicsWorld.get()->setGravity(btVector3(0, -10, 0));
}
bullet_shape make_box_shape(math::vec3 dimensions) override
{
auto shape = std::make_unique<btBoxShape>(vec3_to_bt(dimensions));
return bullet_shape(std::move(shape));
}
bullet_shape make_sphere_shape(float r) override
{
auto shape = std::make_unique<btSphereShape>(r);
return bullet_shape(std::move(shape));
}
bullet_rigid_body make_rigid_body(const bullet_shape& shape, math::vec3 pos, math::quat r,
float m) override
{
btDefaultMotionState* fallMotionState = new btDefaultMotionState(
// btTransform(btQuaternion(r.x,r.y,r.z,r.w), btVector3(pos.x, pos.y,
// pos.z)));
btTransform(btQuaternion(0, 0, 0, 1), btVector3(pos.x, pos.y, pos.z)));
btScalar mass = m;
btVector3 fallInertia(0, 0, 0);
shape.get_impl()->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState,
shape.get_impl(), fallInertia);
auto fallRigidBody = std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>>(
new btRigidBody(fallRigidBodyCI), [this](btRigidBody* f) {
this->dynamicsWorld.get()->removeRigidBody(f);
delete f->getMotionState();
delete f;
});
dynamicsWorld.get()->addRigidBody(fallRigidBody.get());
return bullet_rigid_body(dynamicsWorld.get(), std::move(fallRigidBody));
}
bullet_static_body make_wall(math::vec3 plane, math::vec3 pos) override
{
btStaticPlaneShape* groundShape = new btStaticPlaneShape(vec3_to_bt(plane), 1);
btDefaultMotionState* groundMotionState =
new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), vec3_to_bt(pos)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(
0, groundMotionState, groundShape, btVector3(0, 0, 0));
auto groundRigidBody = std::unique_ptr<btRigidBody, std::function<void(btRigidBody*)>>(
new btRigidBody(groundRigidBodyCI), [this](btRigidBody* g) {
this->dynamicsWorld.get()->removeRigidBody(g);
delete g->getCollisionShape();
delete g->getMotionState();
delete g;
});
dynamicsWorld.get()->addRigidBody(groundRigidBody.get());
return bullet_static_body(dynamicsWorld.get(), std::move(groundRigidBody));
}
void update(const core_context& ctx) override
{
dynamicsWorld->stepSimulation(ctx.elapsed, 10);
}
virtual ~backend()
{
}
math::vec3 lase_normal(math::vec3 from, math::vec3 to) override
{
btVector3 Normal(-1, -1, -1);
btVector3 Start(from.x, from.y, from.z);
btVector3 End(to.x, to.y, to.z);
btCollisionWorld::ClosestRayResultCallback RayCallback(Start, End);
dynamicsWorld->rayTest(Start, End, RayCallback);
if (RayCallback.hasHit()) {
Normal = RayCallback.m_hitNormalWorld;
}
return math::vec3(Normal.x(), Normal.y(), Normal.z());
}
math::vec3 lase_pos(math::vec3 from, math::vec3 to) override
{
btVector3 Pos(-1, -1, -1);
btVector3 Start(from.x, from.y, from.z);
btVector3 End(to.x, to.y, to.z);
btCollisionWorld::ClosestRayResultCallback RayCallback(Start, End);
dynamicsWorld->rayTest(Start, End, RayCallback);
if (RayCallback.hasHit()) {
Pos = RayCallback.m_hitPointWorld;
}
return math::vec3(Pos.x(), Pos.y(), Pos.z());
}
};
};
#endif // GDT_BULLET_HEADER_INCLUDED
| 30.563863 | 96 | 0.633676 | [
"shape"
] |
bc63ec763252d7d07974f72d34bb7bb63eeb45b7 | 27,206 | cpp | C++ | src/public/src/fslazywindow/src/uwp/fslazywindow_uwp.cpp | rothberg-cmu/rothberg-run | a42df5ca9fae97de77753864f60d05295d77b59f | [
"MIT"
] | 1 | 2019-08-10T00:24:09.000Z | 2019-08-10T00:24:09.000Z | src/public/src/fslazywindow/src/uwp/fslazywindow_uwp.cpp | rothberg-cmu/rothberg-run | a42df5ca9fae97de77753864f60d05295d77b59f | [
"MIT"
] | null | null | null | src/public/src/fslazywindow/src/uwp/fslazywindow_uwp.cpp | rothberg-cmu/rothberg-run | a42df5ca9fae97de77753864f60d05295d77b59f | [
"MIT"
] | 2 | 2019-05-01T03:11:10.000Z | 2019-05-01T03:30:35.000Z | /* ////////////////////////////////////////////////////////////
File Name: fslazywindow_uwp.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <stdio.h>
#include <time.h>
#include <vector>
#include <map>
#include <direct.h>
#include <agile.h>
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <EGL/eglplatform.h>
#include <angle_windowsstore.h>
#include <fssimplewindow.h>
#include <fslazywindow.h>
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::System;
using namespace Platform;
extern void FsUWPReportWindowSize(int wid,int hei);
extern void FsUWPMakeReportWindowSize(void);
extern void FsUWPSwapBuffers(void);
extern void FsUWPReportMouseEvent(int evt,int lb,int mb,int rb,int mx,int my);
extern void FsUWPReportCharIn(int unicode);
ref class SingleWindowAppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
{
public:
typedef SingleWindowAppView THISCLASS;
private: // Cannot have a public member variable?
bool isWindowClosed,isWindowVisible,first;
Platform::Agile<CoreWindow> hWnd;
bool lastKnownLbutton,lastKnownMButton,lastKnownRButton;
int lastKnownX,lastKnownY;
static THISCLASS ^CurrentView;
EGLDisplay mEglDisplay;
EGLContext mEglContext;
EGLSurface mEglSurface;
class KeyMap
{
public:
Windows::System::VirtualKey uwpKey;
int fsKey;
KeyMap(){};
KeyMap(Windows::System::VirtualKey uwpKey,int fsKey)
{
this->uwpKey=uwpKey;
this->fsKey=fsKey;
}
};
std::vector <KeyMap> keyMapTable;
public:
static THISCLASS ^GetCurrentView(void);
SingleWindowAppView();
void ReportWindowSize(void);
virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
virtual void Load(Platform::String^ entryPoint);
virtual void Run();
virtual void Uninitialize();
virtual void OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args);
virtual void OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args);
virtual void OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args);
virtual void OnKeyDown(CoreWindow^ window,KeyEventArgs^ args);
virtual void OnKeyUp(CoreWindow^ window,KeyEventArgs^ args);
virtual void CharIn(CoreWindow^ window,CharacterReceivedEventArgs^ args);
virtual void OnMousePointerMoved(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args);
virtual void OnMouseWheelMoved(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args);
virtual void OnMouseButtonPressed(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args);
virtual void OnMouseButtonReleased(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args);
void ProcessMouseEvent(Windows::UI::Core::PointerEventArgs^ args);
private:
void InitializeOpenGLES2(void);
EGLBoolean InitializeEGLDisplayDefault(void);
EGLBoolean InitializeEGLDisplay(int level);
std::vector <EGLint> MakeDisplayAttribute(int level) const;
std::map <Windows::System::VirtualKey,int> uwpKeyToFsKey;
void SetUpConfigAttrib(EGLint configAttrib[],int depthBit);
void CleanUpOpenGLES2(void);
};
/* static */ SingleWindowAppView ^SingleWindowAppView::CurrentView;
/* static */ SingleWindowAppView ^SingleWindowAppView::GetCurrentView(void)
{
return CurrentView;
}
SingleWindowAppView::SingleWindowAppView()
{
isWindowClosed=false;
isWindowVisible=false;
first=true;
lastKnownLbutton=false;
lastKnownMButton=false;
lastKnownRButton=false;
lastKnownX=0;
lastKnownY=0;
mEglDisplay=EGL_NO_DISPLAY;
mEglContext=EGL_NO_CONTEXT;
mEglSurface=EGL_NO_SURFACE;
CurrentView=this;
auto app=FsLazyWindowApplicationBase::GetApplication();
char *argv[1];
argv[0]=(char *)"executable.exe";
app->BeforeEverything(1,argv);
// See https://msdn.microsoft.com/en-us/library/system.windows.forms.keys(v=vs.110).aspx
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::A,FSKEY_A));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::B,FSKEY_B));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::C,FSKEY_C));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::D,FSKEY_D));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::E,FSKEY_E));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F,FSKEY_F));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::G,FSKEY_G));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::H,FSKEY_H));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::I,FSKEY_I));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::J,FSKEY_J));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::K,FSKEY_K));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::L,FSKEY_L));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::M,FSKEY_M));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::N,FSKEY_N));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::O,FSKEY_O));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::P,FSKEY_P));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Q,FSKEY_Q));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::R,FSKEY_R));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::S,FSKEY_S));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::T,FSKEY_T));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::U,FSKEY_U));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::V,FSKEY_V));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::W,FSKEY_W));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::X,FSKEY_X));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Y,FSKEY_Y));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Z,FSKEY_Z));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Add,FSKEY_PLUS));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Application,FSKEY_ALT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Back,FSKEY_BS));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Control,FSKEY_CTRL)); // What's the difference from Windows::System::VirtualKey::Control?
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Decimal,FSKEY_DOT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Delete,FSKEY_DEL));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Divide,FSKEY_SLASH));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Down,FSKEY_DOWN));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::End,FSKEY_END));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Enter,FSKEY_ENTER));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Escape,FSKEY_ESC));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F1,FSKEY_F1));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F2,FSKEY_F2));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F3,FSKEY_F3));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F4,FSKEY_F4));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F5,FSKEY_F5));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F6,FSKEY_F6));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F7,FSKEY_F7));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F8,FSKEY_F8));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F9,FSKEY_F9));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F10,FSKEY_F10));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F11,FSKEY_F11));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::F12,FSKEY_F12));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Home,FSKEY_HOME));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Insert,FSKEY_INS));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Left,FSKEY_LEFT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberKeyLock,FSKEY_NUMLOCK));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad0,FSKEY_TEN0));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad1,FSKEY_TEN1));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad2,FSKEY_TEN2));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad3,FSKEY_TEN3));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad4,FSKEY_TEN4));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad5,FSKEY_TEN5));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad6,FSKEY_TEN6));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad7,FSKEY_TEN7));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad8,FSKEY_TEN8));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::NumberPad9,FSKEY_TEN9));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::PageDown,FSKEY_PAGEDOWN));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::PageUp,FSKEY_PAGEUP));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Pause,FSKEY_PAUSEBREAK));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Right,FSKEY_RIGHT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Scroll,FSKEY_SCROLLLOCK));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Space,FSKEY_SPACE));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Subtract,FSKEY_MINUS));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Tab,FSKEY_TAB));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Up,FSKEY_UP));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::LeftShift,FSKEY_SHIFT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::RightShift,FSKEY_SHIFT));
keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::Shift,FSKEY_SHIFT));
// keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::,FSKEY_));
// keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::,FSKEY_));
// keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::,FSKEY_));
// keyMapTable.push_back(KeyMap(Windows::System::VirtualKey::,FSKEY_));
for(auto km : keyMapTable)
{
uwpKeyToFsKey[km.uwpKey]=km.fsKey;
}
}
void SingleWindowAppView::ReportWindowSize(void)
{
EGLint w=0,h=0;
eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &w);
eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &h);
FsUWPReportWindowSize(w,h);
}
/* virtual */ void SingleWindowAppView::Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView)
{
applicationView->Activated+=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this,&THISCLASS::OnActivated);
}
/* virtual */ void SingleWindowAppView::SetWindow(Windows::UI::Core::CoreWindow^ window)
{
hWnd=window;
window->KeyDown+=
ref new TypedEventHandler<CoreWindow^,KeyEventArgs^>(this,&THISCLASS::OnKeyDown);
window->KeyUp+=
ref new TypedEventHandler<CoreWindow^,KeyEventArgs^>(this,&THISCLASS::OnKeyUp);
window->CharacterReceived+=
ref new TypedEventHandler<CoreWindow^,CharacterReceivedEventArgs^>(this,&THISCLASS::CharIn);
window->PointerMoved+=
ref new TypedEventHandler<CoreWindow^,PointerEventArgs^>(this,&THISCLASS::OnMousePointerMoved);
window->PointerWheelChanged+=
ref new TypedEventHandler<CoreWindow^,PointerEventArgs^>(this,&THISCLASS::OnMouseWheelMoved);
window->PointerPressed+=
ref new TypedEventHandler<CoreWindow^,PointerEventArgs^>(this,&THISCLASS::OnMouseButtonPressed);
window->PointerReleased+=
ref new TypedEventHandler<CoreWindow^,PointerEventArgs^>(this,&THISCLASS::OnMouseButtonReleased);
window->VisibilityChanged+=
ref new TypedEventHandler<CoreWindow^,VisibilityChangedEventArgs^>(this,&THISCLASS::OnVisibilityChanged);
window->Closed+=
ref new TypedEventHandler<CoreWindow^,CoreWindowEventArgs^>(this,&THISCLASS::OnWindowClosed);
InitializeOpenGLES2(); // Example initializes OpenGL ES context in here.
// 2017/02/16
// To work with abusive use of asynchronous operation in UWP API, I need to run an
// event loop when I need to block until an IAsyncOperation is over.
// But, calling
// CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
// from here looks to break something and the program crashes on exit.
// In today's case, calling YsFileInfo of YsPort library from Initialize cause the program to crasn on exit.
// Instead, Initialize is called in Run, just before the first call to Interval.
}
/* virtual */ void SingleWindowAppView::Load(Platform::String^ entryPoint)
{
// Example creates renderers here.
}
/* virtual */ void SingleWindowAppView::Run()
{
while(!isWindowClosed)
{
// See https://blogs.msdn.microsoft.com/oldnewthing/20041130-00/?p=37173 for difference between GetKeyState and GetAsyncKeyState.
// Go with GetAsyncKeyState. GetKeyState may be useless.
if(Windows::UI::Core::CoreVirtualKeyStates::Down==hWnd->GetKeyState(Windows::System::VirtualKey::Escape))
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
if(Windows::UI::Core::CoreVirtualKeyStates::Down==hWnd->GetAsyncKeyState(Windows::System::VirtualKey::Escape))
{
printf("%s %d\n",__FUNCTION__,__LINE__);
char dir[256];
_getcwd(dir,255);
printf("%s\n",dir);
}
if (isWindowVisible)
{
// 2017/02/16 See explanation above.
// To work with ridiculous abusive use of asynchronous operation in Universal Windows API,
// I need to call Initialize from here.
if(true==first)
{
auto app=FsLazyWindowApplicationBase::GetApplication();
FsOpenWindowOption opt;
app->GetOpenWindowOption(opt);
char *argv[1];
argv[0]=(char *)"executable.exe";
app->Initialize(1,argv);
first=false;
}
// This doesn't seem to wait for an event. Like a PeekMessage
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
auto app=FsLazyWindowApplicationBase::GetApplication();
app->Interval();
if(true==app->NeedRedraw())
{
app->Draw();
if (eglSwapBuffers(mEglDisplay, mEglSurface) != GL_TRUE)
{
// Device lost? So, you mean I need to re-create all the resources?
// No way. Why do you make it as bad as Direct 3D9.
CleanUpOpenGLES2();
InitializeOpenGLES2();
app->ContextLostAndRecreated();
}
}
if(true==app->MustTerminate())
{
// How can I close the window?
}
// sleep for app->GetMinimumSleepPerInterval();
}
else
{
// This seems to wait until an event is thrown.
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
}
}
auto app=FsLazyWindowApplicationBase::GetApplication();
app->BeforeTerminate();
CleanUpOpenGLES2(); // Example deletes OpenGL context here.
}
/* virtual */ void SingleWindowAppView::Uninitialize()
{
}
/* virtual */ void SingleWindowAppView::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}
/* virtual */ void SingleWindowAppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
isWindowVisible=args->Visible;
}
/* virtual */ void SingleWindowAppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
isWindowClosed=true;
}
/* virtual */ void SingleWindowAppView::OnKeyDown(CoreWindow^ window,KeyEventArgs^ args)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
auto Lshift=window->GetAsyncKeyState(Windows::System::VirtualKey::LeftShift);
auto Rshift=window->GetAsyncKeyState(Windows::System::VirtualKey::RightShift);
if(Lshift==Windows::UI::Core::CoreVirtualKeyStates::Down)
{
printf("Lshift\n");
}
if(Rshift==Windows::UI::Core::CoreVirtualKeyStates::Down)
{
printf("Rshift\n");
}
auto found=uwpKeyToFsKey.find(args->VirtualKey);
if(uwpKeyToFsKey.end()!=found)
{
FsPushKey(found->second);
}
}
/* virtual */ void SingleWindowAppView::OnKeyUp(CoreWindow^ window,KeyEventArgs^ args)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
/* virtual */ void SingleWindowAppView::CharIn(CoreWindow^ window,CharacterReceivedEventArgs^ args)
{
FsUWPReportCharIn(args->KeyCode);
}
/* virtual */ void SingleWindowAppView::OnMousePointerMoved(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args)
{
auto point=args->CurrentPoint;
if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Mouse)
{
ProcessMouseEvent(args);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Pen)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Touch)
{
printf("%s %d (ID %d)\n",__FUNCTION__,__LINE__,point->PointerId);
}
}
/* virtual */ void SingleWindowAppView::OnMouseWheelMoved(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
/* virtual */ void SingleWindowAppView::OnMouseButtonPressed(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args)
{
auto point=args->CurrentPoint;
if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Mouse)
{
ProcessMouseEvent(args);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Pen)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Touch)
{
printf("%s %d (ID %d)\n",__FUNCTION__,__LINE__,point->PointerId);
}
}
/* virtual */ void SingleWindowAppView::OnMouseButtonReleased(Windows::UI::Core::CoreWindow^ window,Windows::UI::Core::PointerEventArgs^ args)
{
auto point=args->CurrentPoint;
if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Mouse)
{
ProcessMouseEvent(args);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Pen)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
}
else if(point->PointerDevice->PointerDeviceType==Windows::Devices::Input::PointerDeviceType::Touch)
{
printf("%s %d (ID %d)\n",__FUNCTION__,__LINE__,point->PointerId);
}
}
void SingleWindowAppView::ProcessMouseEvent(Windows::UI::Core::PointerEventArgs^ args)
{
auto point=args->CurrentPoint;
auto prop=point->Properties;
int Lbutton=(int)prop->IsLeftButtonPressed;
int Mbutton=(int)prop->IsMiddleButtonPressed;
int Rbutton=(int)prop->IsRightButtonPressed;
auto dispInfo=Windows::Graphics::Display::DisplayInformation::GetForCurrentView();
auto dpiX=dispInfo->LogicalDpi; // Should I go with LogicalDpi or RawDpi?
auto dpiY=dispInfo->LogicalDpi; // Should I go with LogicalDpi or RawDpi?
int x=(int)(point->Position.X*dpiX/96.0);
int y=(int)(point->Position.Y*dpiY/96.0);
if(!lastKnownLbutton && Lbutton)
{
FsUWPReportMouseEvent(FSMOUSEEVENT_LBUTTONDOWN,Lbutton,Mbutton,Rbutton,x,y);
}
if(lastKnownX!=x || lastKnownY!=y)
{
FsUWPReportMouseEvent(FSMOUSEEVENT_MOVE,Lbutton,Mbutton,Rbutton,x,y);
}
if(lastKnownLbutton && !Lbutton)
{
FsUWPReportMouseEvent(FSMOUSEEVENT_LBUTTONUP,Lbutton,Mbutton,Rbutton,x,y);
}
lastKnownLbutton=Lbutton;
lastKnownMButton=Mbutton;
lastKnownRButton=Rbutton;
lastKnownX=x;
lastKnownY=y;
}
void SingleWindowAppView::InitializeOpenGLES2(void)
{
// Cut & Pasted from OpenGL ES2 example.
// Modified so that it selects the maximum depth bits.
EGLint configAttributes[]=
{
EGL_RED_SIZE,8,
EGL_GREEN_SIZE,8,
EGL_BLUE_SIZE,8,
EGL_ALPHA_SIZE,8,
EGL_DEPTH_SIZE,24,
EGL_STENCIL_SIZE,8,
EGL_NONE
};
const EGLint contextAttributes[]=
{
EGL_CONTEXT_CLIENT_VERSION,2,
EGL_NONE
};
const EGLint surfaceAttributes[]=
{
EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER,EGL_TRUE,
EGL_NONE
};
EGLConfig config = NULL;
// According to the example, the program should try to initialize OpenGL ES context with
// EGL to D3D11 Feature Level 10_0+ first. If it fails, try EGL to D3D11 Feature Level 9_3.
// If it fails, try EGL to D3D11 Feature Level 11_0 on WARP.
if(InitializeEGLDisplayDefault()!=EGL_TRUE &&
InitializeEGLDisplay(0)!=EGL_TRUE &&
InitializeEGLDisplay(1)!=EGL_TRUE &&
InitializeEGLDisplay(2)!=EGL_TRUE)
{
throw Exception::CreateException(E_FAIL, L"Failed to initialize EGL");
}
// The sample code given with the OpenGL ES template uses 8-bit Z-buffer,
// which is pretty much useless.
// Ideallly want to have 64-bit (or as precise as coordinates, in many cases 32-bit),
// but here get whatever available.
EGLint numConfigs = 0;
for(int depthBit=32; 8<=depthBit; depthBit-=8)
{
SetUpConfigAttrib(configAttributes,depthBit);
if(eglChooseConfig(mEglDisplay,configAttributes,&config,1,&numConfigs)==EGL_TRUE && 0!=numConfigs)
{
printf("%d Depth Bits\n",depthBit);
break;
}
}
if(0==numConfigs)
{
throw Exception::CreateException(E_FAIL,L"Failed to choose first EGLConfig");
}
PropertySet^ surfaceCreationProperties = ref new PropertySet();
surfaceCreationProperties->Insert(ref new String(EGLNativeWindowTypeProperty), hWnd.Get());
mEglSurface=eglCreateWindowSurface(mEglDisplay,config,reinterpret_cast<IInspectable*>(surfaceCreationProperties),surfaceAttributes);
if(mEglSurface==EGL_NO_SURFACE)
{
throw Exception::CreateException(E_FAIL,L"Failed to create EGL fullscreen surface");
}
mEglContext=eglCreateContext(mEglDisplay,config,EGL_NO_CONTEXT,contextAttributes);
if(mEglContext==EGL_NO_CONTEXT)
{
throw Exception::CreateException(E_FAIL,L"Failed to create EGL context");
}
if(eglMakeCurrent(mEglDisplay,mEglSurface,mEglSurface,mEglContext)==EGL_FALSE)
{
throw Exception::CreateException(E_FAIL,L"Failed to make fullscreen EGLSurface current");
}
glClearColor(1,1,1,0);
}
EGLBoolean SingleWindowAppView::InitializeEGLDisplayDefault(void)
{
// The sample code tells that eglGetPlatformDisplayEXT is use in place for eglGetDisplay to pass display attributes.
// But, why not trying eglGetDisplay first?
mEglDisplay=eglGetDisplay(EGL_DEFAULT_DISPLAY);
if(EGL_NO_DISPLAY!=mEglDisplay)
{
auto b=eglInitialize(mEglDisplay,NULL,NULL);
printf("Looks like the default eglGetDisplay is good enough. Isn't it?");
return b;
}
return EGL_FALSE;
}
EGLBoolean SingleWindowAppView::InitializeEGLDisplay(int level)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT=
reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
throw Exception::CreateException(E_FAIL, L"Failed to get function eglGetPlatformDisplayEXT");
}
auto attrib=MakeDisplayAttribute(level);
mEglDisplay=eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE,EGL_DEFAULT_DISPLAY,attrib.data());
if(mEglDisplay!=EGL_NO_DISPLAY)
{
return eglInitialize(mEglDisplay,NULL,NULL);
}
return EGL_FALSE;
}
std::vector <EGLint> SingleWindowAppView::MakeDisplayAttribute(int level) const
{
const EGLint commonDisplayAttributePre[]=
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE,EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
};
const EGLint commonDisplayAttributePost[]=
{
EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER,EGL_TRUE,
EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE,EGL_TRUE,
EGL_NONE,
};
std::vector <EGLint> attrib;
for(auto v : commonDisplayAttributePre)
{
attrib.push_back(v);
}
switch(level)
{
case 0:
break;
case 1: // FL9. I don't know exactly what FL9 stands for, but as example says.
attrib.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE);
attrib.push_back(9);
attrib.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE);
attrib.push_back(3);
break;
case 2: // warp. I don't know exactly what it means by "warp", but as example says.
attrib.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE);
attrib.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE);
break;
}
for(auto v : commonDisplayAttributePost)
{
attrib.push_back(v);
}
return attrib;
}
void SingleWindowAppView::SetUpConfigAttrib(EGLint configAttrib[],int depthBit)
{
for(int i=0; configAttrib[i]!=EGL_NONE; i+=2)
{
if(EGL_DEPTH_SIZE==configAttrib[i])
{
configAttrib[i+1]=depthBit;
}
}
}
void SingleWindowAppView::CleanUpOpenGLES2(void)
{
// Cut & Pasted from OpenGL ES2 Example.
if(mEglDisplay!=EGL_NO_DISPLAY && mEglSurface!=EGL_NO_SURFACE)
{
eglDestroySurface(mEglDisplay,mEglSurface);
mEglSurface=EGL_NO_SURFACE;
}
if(mEglDisplay!=EGL_NO_DISPLAY && mEglContext!=EGL_NO_CONTEXT)
{
eglDestroyContext(mEglDisplay,mEglContext);
mEglContext=EGL_NO_CONTEXT;
}
if(mEglDisplay!=EGL_NO_DISPLAY)
{
eglTerminate(mEglDisplay);
mEglDisplay=EGL_NO_DISPLAY;
}
}
void FsUWPMakeReportWindowSize(void)
{
auto view=SingleWindowAppView::GetCurrentView();
view->ReportWindowSize();
}
void FsUWPSwapBuffers(void)
{
// auto view=SingleWindowAppView::GetCurrentView();
// view->SwapBuffers();
}
ref class SingleWindowAppSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{
public:
virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView()
{
return ref new SingleWindowAppView();
}
};
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto singleWindowAppSource = ref new SingleWindowAppSource();
CoreApplication::Run(singleWindowAppSource);
return 0;
}
| 36.814614 | 148 | 0.767735 | [
"vector"
] |
bc66235fa583e687ea41a36f61734e33d099bd93 | 1,698 | cpp | C++ | test/TestTransform.cpp | peterlauro/type_list | 945695a5d45362f2a676945d49675b0e78dbee3f | [
"Apache-2.0"
] | null | null | null | test/TestTransform.cpp | peterlauro/type_list | 945695a5d45362f2a676945d49675b0e78dbee3f | [
"Apache-2.0"
] | null | null | null | test/TestTransform.cpp | peterlauro/type_list | 945695a5d45362f2a676945d49675b0e78dbee3f | [
"Apache-2.0"
] | null | null | null | #include <type_list.h>
#include <gtest/gtest.h>
namespace stdx::test
{
enum class kind
{
req = 0,
rsp = 1,
nfy = 2
};
template<kind K, int Id, int Value>
struct literal
{
constexpr literal() = default;
constexpr static kind k = K;
constexpr static int id = Id;
constexpr static int value = Value;
};
struct req
{
constexpr static kind k = kind::req;
};
struct rsp
{
constexpr static kind k = kind::rsp;
};
struct nfy
{
constexpr static kind k = kind::nfy;
};
using req1 = literal<kind::req, 1, 15>;
using req2 = literal<kind::req, 2, 16>;
using req3 = literal<kind::req, 3, 17>;
using rsp1 = literal<kind::rsp, 4, 15>;
using rsp2 = literal<kind::rsp, 5, 16>;
using rsp3 = literal<kind::rsp, 6, 17>;
using nfy1 = literal<kind::nfy, 7, 15>;
using nfy2 = literal<kind::nfy, 8, 16>;
using nfy3 = literal<kind::nfy, 9, 17>;
using messages = stdx::type_list<req1, req2, req3, rsp1, rsp2, rsp3, nfy1, nfy2, nfy3>;
using my_empty_list_type = stdx::type_list<>;
constexpr auto detector = [](auto x) constexpr -> decltype(auto){
if constexpr (x.k == kind::req)
{
return req{};
}
else if constexpr (x.k == kind::rsp)
{
return rsp{};
}
else
{
return nfy{};
}
};
TEST(TypeList_Transform, from_empty_list)
{
using t = decltype(my_empty_list_type::transform(detector));
static_assert(std::is_same_v<t, stdx::type_list<>>);
}
TEST(TypeList_Transform, message_detector)
{
using t = decltype(messages::transform(detector));
static_assert(std::is_same_v<t, stdx::type_list<req, req, req, rsp, rsp, rsp, nfy, nfy, nfy>>);
}
}
| 21.493671 | 99 | 0.612485 | [
"transform"
] |
bc872146f446c4a3eccdaedc74a989b36f5b681a | 15,405 | hpp | C++ | ThirdParty-mod/java2cpp/android/widget/RadioGroup.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/widget/RadioGroup.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/widget/RadioGroup.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.widget.RadioGroup
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_DECL
#define J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace android { namespace content { class Context; } } }
namespace j2cpp { namespace android { namespace view { class View; } } }
namespace j2cpp { namespace android { namespace view { namespace ViewGroup_ { class OnHierarchyChangeListener; } } } }
namespace j2cpp { namespace android { namespace view { namespace ViewGroup_ { class MarginLayoutParams; } } } }
namespace j2cpp { namespace android { namespace view { namespace ViewGroup_ { class LayoutParams; } } } }
namespace j2cpp { namespace android { namespace widget { class LinearLayout; } } }
namespace j2cpp { namespace android { namespace widget { namespace LinearLayout_ { class LayoutParams; } } } }
namespace j2cpp { namespace android { namespace widget { namespace RadioGroup_ { class OnCheckedChangeListener; } } } }
namespace j2cpp { namespace android { namespace widget { namespace RadioGroup_ { class LayoutParams; } } } }
namespace j2cpp { namespace android { namespace util { class AttributeSet; } } }
#include <android/content/Context.hpp>
#include <android/util/AttributeSet.hpp>
#include <android/view/View.hpp>
#include <android/view/ViewGroup.hpp>
#include <android/widget/LinearLayout.hpp>
#include <android/widget/RadioGroup.hpp>
#include <java/lang/Object.hpp>
namespace j2cpp {
namespace android { namespace widget {
class RadioGroup;
namespace RadioGroup_ {
class OnCheckedChangeListener;
class OnCheckedChangeListener
: public object<OnCheckedChangeListener>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
explicit OnCheckedChangeListener(jobject jobj)
: object<OnCheckedChangeListener>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
void onCheckedChanged(local_ref< android::widget::RadioGroup > const&, jint);
}; //class OnCheckedChangeListener
class LayoutParams;
class LayoutParams
: public object<LayoutParams>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
explicit LayoutParams(jobject jobj)
: object<LayoutParams>(jobj)
{
}
operator local_ref<android::widget::LinearLayout_::LayoutParams>() const;
LayoutParams(local_ref< android::content::Context > const&, local_ref< android::util::AttributeSet > const&);
LayoutParams(jint, jint);
LayoutParams(jint, jint, jfloat);
LayoutParams(local_ref< android::view::ViewGroup_::LayoutParams > const&);
LayoutParams(local_ref< android::view::ViewGroup_::MarginLayoutParams > const&);
}; //class LayoutParams
} //namespace RadioGroup_
class RadioGroup
: public object<RadioGroup>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
J2CPP_DECLARE_METHOD(12)
J2CPP_DECLARE_METHOD(13)
J2CPP_DECLARE_METHOD(14)
typedef RadioGroup_::OnCheckedChangeListener OnCheckedChangeListener;
typedef RadioGroup_::LayoutParams LayoutParams;
explicit RadioGroup(jobject jobj)
: object<RadioGroup>(jobj)
{
}
operator local_ref<android::widget::LinearLayout>() const;
RadioGroup(local_ref< android::content::Context > const&);
RadioGroup(local_ref< android::content::Context > const&, local_ref< android::util::AttributeSet > const&);
void setOnHierarchyChangeListener(local_ref< android::view::ViewGroup_::OnHierarchyChangeListener > const&);
void addView(local_ref< android::view::View > const&, jint, local_ref< android::view::ViewGroup_::LayoutParams > const&);
void check(jint);
jint getCheckedRadioButtonId();
void clearCheck();
void setOnCheckedChangeListener(local_ref< android::widget::RadioGroup_::OnCheckedChangeListener > const&);
local_ref< android::widget::RadioGroup_::LayoutParams > generateLayoutParams(local_ref< android::util::AttributeSet > const&);
local_ref< android::widget::LinearLayout_::LayoutParams > generateLayoutParams_1(local_ref< android::util::AttributeSet > const&);
local_ref< android::view::ViewGroup_::LayoutParams > generateLayoutParams_2(local_ref< android::util::AttributeSet > const&);
}; //class RadioGroup
} //namespace widget
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_IMPL
#define J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_IMPL
namespace j2cpp {
android::widget::RadioGroup_::OnCheckedChangeListener::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
void android::widget::RadioGroup_::OnCheckedChangeListener::onCheckedChanged(local_ref< android::widget::RadioGroup > const &a0, jint a1)
{
return call_method<
android::widget::RadioGroup_::OnCheckedChangeListener::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::OnCheckedChangeListener::J2CPP_METHOD_NAME(0),
android::widget::RadioGroup_::OnCheckedChangeListener::J2CPP_METHOD_SIGNATURE(0),
void
>(get_jobject(), a0, a1);
}
J2CPP_DEFINE_CLASS(android::widget::RadioGroup_::OnCheckedChangeListener,"android/widget/RadioGroup$OnCheckedChangeListener")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::OnCheckedChangeListener,0,"onCheckedChanged","(Landroid/widget/RadioGroup;I)V")
android::widget::RadioGroup_::LayoutParams::operator local_ref<android::widget::LinearLayout_::LayoutParams>() const
{
return local_ref<android::widget::LinearLayout_::LayoutParams>(get_jobject());
}
android::widget::RadioGroup_::LayoutParams::LayoutParams(local_ref< android::content::Context > const &a0, local_ref< android::util::AttributeSet > const &a1)
: object<android::widget::RadioGroup_::LayoutParams>(
call_new_object<
android::widget::RadioGroup_::LayoutParams::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_NAME(0),
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_SIGNATURE(0)
>(a0, a1)
)
{
}
android::widget::RadioGroup_::LayoutParams::LayoutParams(jint a0, jint a1)
: object<android::widget::RadioGroup_::LayoutParams>(
call_new_object<
android::widget::RadioGroup_::LayoutParams::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_NAME(1),
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
android::widget::RadioGroup_::LayoutParams::LayoutParams(jint a0, jint a1, jfloat a2)
: object<android::widget::RadioGroup_::LayoutParams>(
call_new_object<
android::widget::RadioGroup_::LayoutParams::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_NAME(2),
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_SIGNATURE(2)
>(a0, a1, a2)
)
{
}
android::widget::RadioGroup_::LayoutParams::LayoutParams(local_ref< android::view::ViewGroup_::LayoutParams > const &a0)
: object<android::widget::RadioGroup_::LayoutParams>(
call_new_object<
android::widget::RadioGroup_::LayoutParams::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_NAME(3),
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_SIGNATURE(3)
>(a0)
)
{
}
android::widget::RadioGroup_::LayoutParams::LayoutParams(local_ref< android::view::ViewGroup_::MarginLayoutParams > const &a0)
: object<android::widget::RadioGroup_::LayoutParams>(
call_new_object<
android::widget::RadioGroup_::LayoutParams::J2CPP_CLASS_NAME,
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_NAME(4),
android::widget::RadioGroup_::LayoutParams::J2CPP_METHOD_SIGNATURE(4)
>(a0)
)
{
}
J2CPP_DEFINE_CLASS(android::widget::RadioGroup_::LayoutParams,"android/widget/RadioGroup$LayoutParams")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,0,"<init>","(Landroid/content/Context;Landroid/util/AttributeSet;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,1,"<init>","(II)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,2,"<init>","(IIF)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,3,"<init>","(Landroid/view/ViewGroup$LayoutParams;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,4,"<init>","(Landroid/view/ViewGroup$MarginLayoutParams;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup_::LayoutParams,5,"setBaseAttributes","(Landroid/content/res/TypedArray;II)V")
android::widget::RadioGroup::operator local_ref<android::widget::LinearLayout>() const
{
return local_ref<android::widget::LinearLayout>(get_jobject());
}
android::widget::RadioGroup::RadioGroup(local_ref< android::content::Context > const &a0)
: object<android::widget::RadioGroup>(
call_new_object<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(0),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
android::widget::RadioGroup::RadioGroup(local_ref< android::content::Context > const &a0, local_ref< android::util::AttributeSet > const &a1)
: object<android::widget::RadioGroup>(
call_new_object<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(1),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
void android::widget::RadioGroup::setOnHierarchyChangeListener(local_ref< android::view::ViewGroup_::OnHierarchyChangeListener > const &a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(2),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(2),
void
>(get_jobject(), a0);
}
void android::widget::RadioGroup::addView(local_ref< android::view::View > const &a0, jint a1, local_ref< android::view::ViewGroup_::LayoutParams > const &a2)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(4),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(4),
void
>(get_jobject(), a0, a1, a2);
}
void android::widget::RadioGroup::check(jint a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(5),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(5),
void
>(get_jobject(), a0);
}
jint android::widget::RadioGroup::getCheckedRadioButtonId()
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(6),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(6),
jint
>(get_jobject());
}
void android::widget::RadioGroup::clearCheck()
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(7),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(7),
void
>(get_jobject());
}
void android::widget::RadioGroup::setOnCheckedChangeListener(local_ref< android::widget::RadioGroup_::OnCheckedChangeListener > const &a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(8),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(8),
void
>(get_jobject(), a0);
}
local_ref< android::widget::RadioGroup_::LayoutParams > android::widget::RadioGroup::generateLayoutParams(local_ref< android::util::AttributeSet > const &a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(9),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(9),
local_ref< android::widget::RadioGroup_::LayoutParams >
>(get_jobject(), a0);
}
local_ref< android::widget::LinearLayout_::LayoutParams > android::widget::RadioGroup::generateLayoutParams_1(local_ref< android::util::AttributeSet > const &a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(12),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(12),
local_ref< android::widget::LinearLayout_::LayoutParams >
>(get_jobject(), a0);
}
local_ref< android::view::ViewGroup_::LayoutParams > android::widget::RadioGroup::generateLayoutParams_2(local_ref< android::util::AttributeSet > const &a0)
{
return call_method<
android::widget::RadioGroup::J2CPP_CLASS_NAME,
android::widget::RadioGroup::J2CPP_METHOD_NAME(14),
android::widget::RadioGroup::J2CPP_METHOD_SIGNATURE(14),
local_ref< android::view::ViewGroup_::LayoutParams >
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(android::widget::RadioGroup,"android/widget/RadioGroup")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,0,"<init>","(Landroid/content/Context;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,1,"<init>","(Landroid/content/Context;Landroid/util/AttributeSet;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,2,"setOnHierarchyChangeListener","(Landroid/view/ViewGroup$OnHierarchyChangeListener;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,3,"onFinishInflate","()V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,4,"addView","(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,5,"check","(I)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,6,"getCheckedRadioButtonId","()I")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,7,"clearCheck","()V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,8,"setOnCheckedChangeListener","(Landroid/widget/RadioGroup$OnCheckedChangeListener;)V")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,9,"generateLayoutParams","(Landroid/util/AttributeSet;)Landroid/widget/RadioGroup$LayoutParams;")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,10,"checkLayoutParams","(Landroid/view/ViewGroup$LayoutParams;)Z")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,11,"generateDefaultLayoutParams","()Landroid/widget/LinearLayout$LayoutParams;")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,12,"generateLayoutParams","(Landroid/util/AttributeSet;)Landroid/widget/LinearLayout$LayoutParams;")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,13,"generateDefaultLayoutParams","()Landroid/view/ViewGroup$LayoutParams;")
J2CPP_DEFINE_METHOD(android::widget::RadioGroup,14,"generateLayoutParams","(Landroid/util/AttributeSet;)Landroid/view/ViewGroup$LayoutParams;")
} //namespace j2cpp
#endif //J2CPP_ANDROID_WIDGET_RADIOGROUP_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 37.573171 | 162 | 0.748718 | [
"object"
] |
bc8b2201c8c84279a25a44713e11fe2292ed7ffd | 4,319 | cpp | C++ | mergeBathy/Error_Estimator/mesh.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 4 | 2017-05-04T15:50:48.000Z | 2020-07-30T03:52:07.000Z | mergeBathy/Error_Estimator/mesh.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | null | null | null | mergeBathy/Error_Estimator/mesh.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 2 | 2017-01-11T09:53:26.000Z | 2020-07-30T03:52:09.000Z | /**********************************************************************
* CC0 License
**********************************************************************
* MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid.
* Written in 2015 by Samantha J.Zambo(samantha.zambo@gmail.com) while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory.
* To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty.
* You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
**********************************************************************/
/**
*
*
*/
#pragma once
#ifndef MESH_CPP
#define MESH_CPP
#include "fstream"
#include <vector>
#include <list>
#include <algorithm>
#include <cassert>
#include <iostream>
#include "mesh.h"
#include "geom.h"
#include "pointList.h"
using namespace std;
// Returns the entire list of positions
vector<Point> Mesh::getPositions() const { return positions; }
// Returns the entire list of indices
vector<int> Mesh::getIndices() const { return indices; }
// calls createIndicesFromPoint for all pings in the triangle
void Mesh::insertIndices(const Triangle& t)
{
insertIndices(t.v1);
insertIndices(t.v2);
insertIndices(t.v3);
}
// Requires that positions for all triangles being inserted already be present
// creates the indices for the triangle and inserts them
void Mesh::insertIndices(const Point& p)
{
int index, indexMove;
indexMove = (const int)positions.size() / 4;
index = (const int)positions.size() / 2;
while(true)
{
if(positions[index] == p)
break;
else if(positions[index] < p)
index += indexMove;
else
index -= indexMove;
if(indexMove != 1)
indexMove = indexMove / 2;
if(indexMove == 0)
indexMove++;
}
indices.push_back(index);
}
void Mesh::insertPoints(list<Point>& p)
{
p.sort();
p.unique();
positions.reserve(p.size());
positions.assign(p.begin(), p.end());
}
// inserts positions from a pre-sorted list (MUCH FASTER)
void Mesh::insertPoints(PointList& p)
{
p.sort();
p.unique();
positions.reserve(p.size());
for(int i = 0; i < p.size(); i++)
positions.push_back(p[i]);
}
// inserts positions from a pre-sorted list (MUCH FASTER)
void Mesh::insertPoints(vector<Point>& p)
{
sort(p.begin(), p.end());
unique(p.begin(), p.end());
positions = p;
}
// clears the mesh completely
void Mesh::clear()
{
positions.clear();
indices.clear();
}
// Returns the size of the mesh in number of triangles
int Mesh::size() const { return (const int)indices.size() / 3; }
// Operator for indexing specific triangles using []
Triangle Mesh::operator[](const int& index)
{
Point p(positions[indices[index*3]]);
Point v1(p);
p = positions[indices[index*3+1]];
Point v2(p);
p = positions[indices[index*3+2]];
Point v3(p);
Triangle t(v1, v2, v3);
return t;
}
void Mesh::write(string fileName) const
{
Point p;
ofstream outData;
string fn = fileName + ".positions";
outData.open(fn.c_str());
int k = 0;
for(int i = 0; i < (const int)positions.size(); i++)
{
p = positions[i];
outData << p.x << " " << p.y << " " << p.z << endl;
}
outData.close();
fn = fileName + ".indices";
outData.open(fn.c_str());
for(int i = 0; i < (const int)indices.size(); i++)
{
outData << indices[i++] << " ";
outData << indices[i++] << " ";
outData << indices[i] << endl;
}
}
#endif
| 28.793333 | 250 | 0.667053 | [
"mesh",
"vector"
] |
bc9198e27d42f5af5d02ee7a7ed4c807256c19bb | 26,480 | cpp | C++ | test/txpl/vm/eval_binary_eq_test.cpp | ptomulik/txpl | 109b5847abe0d46c598ada46f411f98ebe8dc4c8 | [
"BSL-1.0"
] | null | null | null | test/txpl/vm/eval_binary_eq_test.cpp | ptomulik/txpl | 109b5847abe0d46c598ada46f411f98ebe8dc4c8 | [
"BSL-1.0"
] | 14 | 2015-03-02T14:02:32.000Z | 2015-05-17T21:50:30.000Z | test/txpl/vm/eval_binary_eq_test.cpp | ptomulik/txpl | 109b5847abe0d46c598ada46f411f98ebe8dc4c8 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// 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 BOOST_TEST_MODULE test_txpl_vm_eval_binary_eq
#include <txpl/test_config.hpp>
#include <boost/test/unit_test.hpp>
#ifndef TXPL_TEST_SKIP_VM_EVAL_BINARY_EQ
#include <txpl/vm/eval_binary_op.hpp>
#include <txpl/vm/basic_types.hpp>
#include <txpl/vm/value.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/get.hpp>
#include <type_traits>
using namespace txpl::vm;
typedef basic_types<>::char_type char_type;
typedef basic_types<>::int_type int_type;
typedef basic_types<>::bool_type bool_type;
typedef basic_types<>::real_type real_type;
typedef basic_types<>::string_type string_type;
typedef basic_types<>::regex_type regex_type;
typedef basic_types<>::blank_type blank_type;
typedef array<value<> > array_type;
typedef object<value<> > object_type;
BOOST_AUTO_TEST_CASE(char__eq__char)
{
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'\0'};
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (char_type{'\0'} == char_type{'\0'}));
}
}
BOOST_AUTO_TEST_CASE(char__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'\0'};
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (char_type{'\0'} == int_type{0}));
}
}
BOOST_AUTO_TEST_CASE(char__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'\0'};
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (char_type{'\0'} == bool_type{false}));
}
}
BOOST_AUTO_TEST_CASE(char__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'\0'};
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (char_type{'\0'} == real_type{0.0}));
}
}
BOOST_AUTO_TEST_CASE(char__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'a'};
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(char__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'a'};
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(char__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'a'};
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(char__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = char_type{'a'};
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(int__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (int_type{0} == char_type{'\0'}));
}
}
BOOST_AUTO_TEST_CASE(int__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (int_type{0} == int_type{0}));
}
}
BOOST_AUTO_TEST_CASE(int__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (int_type{0} == bool_type{false}));
}
}
BOOST_AUTO_TEST_CASE(int__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (int_type{0} == real_type{0.0}));
}
}
BOOST_AUTO_TEST_CASE(int__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(int__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(int__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(int__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = int_type{0};
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (char_type{false} == bool_type{'\0'}));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{false} == int_type{0}));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{false} == bool_type{false}));
}
{
const value<> v1 = bool_type{false};
const value<> v2 = bool_type{true};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{false};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{false} == bool_type{true}));
}
{
const value<> v1 = bool_type{true};
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{false};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{true} == bool_type{false}));
}
{
const value<> v1 = bool_type{true};
const value<> v2 = bool_type{true};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{false};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{true} == bool_type{true}));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (bool_type{false} == bool_type{0.0}));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(bool__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = bool_type{false};
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(real__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (real_type{0.0} == char_type{'\0'}));
}
}
BOOST_AUTO_TEST_CASE(real__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (real_type{0.0} == int_type{0}));
}
}
BOOST_AUTO_TEST_CASE(real__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (real_type{0.0} == bool_type{false}));
}
}
BOOST_AUTO_TEST_CASE(real__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{true};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (real_type{0.0} == real_type{0.0}));
}
}
BOOST_AUTO_TEST_CASE(real__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(real__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(real__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(real__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = real_type{0.0};
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type("asd");
const value<> v2 = string_type("asd");
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{false};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (string_type("asd") == string_type("asd")));
}
{
const value<> v1 = string_type("asd");
const value<> v2 = string_type("qwe");
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
bool_type x = bool_type{false};
BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
BOOST_CHECK(x == (string_type("asd") == string_type("qwe")));
}
}
BOOST_AUTO_TEST_CASE(string__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(string__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = string_type();
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(regex__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = regex_type();
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
array_type x;
BOOST_CHECK_NO_THROW(x = boost::get<array_type>(r));
BOOST_CHECK_EQUAL(x.size(), 0);
}
{
array_type a1(3);
array_type a2(3);
a2[0] = a1[0] = char_type{'a'};
a2[1] = a1[1] = int_type{100};
a2[2] = real_type{321.0}; a1[2] = real_type{.123};
const value<> v1 = a1;
const value<> v2 = a2;
r = blank_type();
BOOST_CHECK(boost::apply_visitor(op, v1, v2));
array_type x;
BOOST_CHECK_NO_THROW(x = boost::get<array_type>(r));
BOOST_CHECK_EQUAL(x.size(), 3);
BOOST_CHECK(boost::get<bool_type>(x[0]));
BOOST_CHECK(boost::get<bool_type>(x[1]));
BOOST_CHECK(!boost::get<bool_type>(x[2]));
}
{
array_type a1(3);
array_type a2(2);
a2[0] = a1[0] = char_type{'a'};
a2[1] = a1[1] = int_type{100};
a1[2] = real_type{.123};
const value<> v1 = a1;
const value<> v2 = a2;
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(array__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = array_type();
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__char)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = char_type{'\0'};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__int)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = int_type{0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__bool)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = bool_type{false};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__real)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = real_type{0.0};
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__string)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = string_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__regex)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = regex_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__array)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = array_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
BOOST_AUTO_TEST_CASE(object__eq__object)
{
using namespace txpl::vm;
value<> r;
auto op = eval_binary_op<op_t::eq_>(r);
{
const value<> v1 = object_type();
const value<> v2 = object_type();
r = blank_type();
BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
}
}
#else
BOOST_AUTO_TEST_CASE(dummy)
{
BOOST_CHECK(true);
}
#endif
| 27.075665 | 65 | 0.650113 | [
"object"
] |
bc994a52362e3480fcd1eedb62f9cb17474e8745 | 3,610 | hpp | C++ | examples/addition/include/romeo_moveit_actions/simplepickplace.hpp | unl-nimbus-lab/phriky-units | 16c8cdd91de0899411b139e5a94fcb4ea8104ad2 | [
"MIT"
] | 22 | 2017-07-18T09:39:34.000Z | 2021-09-16T09:41:03.000Z | examples/addition/include/romeo_moveit_actions/simplepickplace.hpp | unl-nimbus-lab/phriky-units | 16c8cdd91de0899411b139e5a94fcb4ea8104ad2 | [
"MIT"
] | 9 | 2016-09-04T13:33:15.000Z | 2018-01-05T22:39:03.000Z | examples/addition/include/romeo_moveit_actions/simplepickplace.hpp | unl-nimbus-lab/phriky-units | 16c8cdd91de0899411b139e5a94fcb4ea8104ad2 | [
"MIT"
] | 4 | 2016-12-07T16:34:57.000Z | 2019-04-03T06:51:55.000Z | #ifndef SIMPLEACTIONS_HPP
#define SIMPLEACTIONS_HPP
#include <ros/ros.h>
#include <moveit_visual_tools/moveit_visual_tools.h>
#include "romeo_moveit_actions/metablock.hpp"
#include "romeo_moveit_actions/action.hpp"
#include "romeo_moveit_actions/objprocessing.hpp"
#include "romeo_moveit_actions/evaluation.hpp"
namespace moveit_simple_actions
{
class SimplePickPlace
{
public:
SimplePickPlace(const std::string robot_name,
const double test_step,
const double x_min,
const double x_max,
const double y_min,
const double y_max,
const double z_min,
const double z_max,
const std::string left_arm_name,
const std::string right_arm_name,
const bool verbose);
protected:
//main cycle
bool startRoutine();
//switch between the left and right arms
void switchArm(Action *action_now);
//create and publish an object
void createObj(const MetaBlock &block);
//re-draw the object at new position
void resetBlock(MetaBlock *block);
//get collision objects from the topic /collision_object
void getCollisionObjects(const moveit_msgs::CollisionObject::ConstPtr& msg);
//clean the object list based on the timestamp
void cleanObjects(std::vector<MetaBlock> *objects, const bool list_erase=true);
//publish the object at a new position
void publishCollisionObject(MetaBlock *block, const geometry_msgs::Pose &pose);
//publish the object
void publishCollisionObject(MetaBlock *block);
//check if teh block exists
bool checkObj(int &block_id);
// A shared node handle
ros::NodeHandle nh_, nh_priv_;
//the robot's name
std::string robot_name_;
const bool verbose_;
//robot's base_frame
std::string base_frame_;
//the dimenssion x of a default object
double block_size_x_;
//the dimenssion y of a default object
double block_size_y_;
//the shift of the robot's base to teh floor
double floor_to_base_height_;
//Object processing
Objprocessing objproc_;
//Evaluation of reaching/grasping
Evaluation evaluation_;
//the state of re-drawing the world
bool env_shown_;
//the working space of the robot
double x_min_;
double x_max_;
double y_min_;
double y_max_;
double z_min_;
double z_max_;
//the name of the current support surface
std::string support_surface_name_;
//instances of an Action class for each arm
Action *action_left_, *action_right_;
moveit_visual_tools::MoveItVisualToolsPtr visual_tools_;
//the set of available objects
std::vector<MetaBlock> blocks_;
//the set of available surfaces
std::vector<MetaBlock> blocks_surfaces_;
//the subscriber to get objects through the topic /collision_object
ros::Subscriber sub_obj_coll_;
//the publisher of objects poses
ros::Publisher pub_obj_poses_;
//the publisher of the current object pose
ros::Publisher pub_obj_pose_;
//the current object position
geometry_msgs::PoseStamped msg_obj_pose_;
//all objects positions
geometry_msgs::PoseArray msg_obj_poses_;
//the default object pose for the left arm
geometry_msgs::Pose pose_default_;
//the default object pose for the right arm
geometry_msgs::Pose pose_default_r_;
//the default object pose at zero
geometry_msgs::Pose pose_zero_;
//all successfully reached positions
std::vector <geometry_msgs::Pose> stat_poses_success_;
//publisher of the collision objects to the topic /collision_world
ros::Publisher pub_obj_moveit_;
};
}
#endif // SIMPLEACTIONS_HPP
| 25.422535 | 81 | 0.728532 | [
"object",
"vector"
] |
bc9cdd4e7367fd2b0308f85d5927ea241e0e9c51 | 2,176 | cc | C++ | smbprovider/proto.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | smbprovider/proto.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | smbprovider/proto.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "smbprovider/proto.h"
#include <base/check.h>
#include <base/logging.h>
#include <dbus/smbprovider/dbus-constants.h>
#include "smbprovider/constants.h"
#include "smbprovider/proto_bindings/directory_entry.pb.h"
namespace smbprovider {
ErrorType SerializeProtoToBlob(const google::protobuf::MessageLite& proto,
ProtoBlob* proto_blob) {
DCHECK(proto_blob);
proto_blob->resize(proto.ByteSizeLong());
bool success =
proto.SerializeToArray(proto_blob->data(), proto.ByteSizeLong());
if (!success) {
LOG(ERROR) << "Unable to serialise proto " << proto.GetTypeName()
<< " size " << proto.GetCachedSize();
}
return success ? ERROR_OK : ERROR_FAILED;
}
bool IsValidOptions(const GetSharesOptionsProto& options) {
return options.has_server_url();
}
std::string GetEntryPath(const GetSharesOptionsProto& options) {
return options.server_url();
}
const char* GetMethodName(const GetSharesOptionsProto& unused) {
return kGetSharesMethod;
}
template <>
int32_t GetMountId(const GetSharesOptionsProto& unused) {
return kInternalMountId;
}
void SerializeDirEntryVectorToProto(
const std::vector<DirectoryEntry>& entries_vector,
DirectoryEntryListProto* entries_proto) {
for (const auto& e : entries_vector) {
AddDirectoryEntry(e, entries_proto);
}
}
void AddDirectoryEntry(const DirectoryEntry& entry,
DirectoryEntryListProto* proto) {
DCHECK(proto);
DirectoryEntryProto* new_entry_proto = proto->add_entries();
ConvertToProto(entry, new_entry_proto);
}
void ConvertToProto(const DirectoryEntry& entry, DirectoryEntryProto* proto) {
DCHECK(proto);
proto->set_is_directory(entry.is_directory);
proto->set_name(entry.name);
proto->set_size(entry.size);
proto->set_last_modified_time(entry.last_modified_time);
}
void AddToHostnamesProto(const std::string& hostname, HostnamesProto* proto) {
DCHECK(proto);
proto->add_hostnames(hostname);
}
} // namespace smbprovider
| 29.013333 | 78 | 0.737132 | [
"vector"
] |
bca71130c4e18a54fd8452365aa7614261c27611 | 23,507 | cpp | C++ | src/Misc/Server.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 1 | 2021-04-28T20:32:57.000Z | 2021-04-28T20:32:57.000Z | src/Misc/Server.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 7 | 2021-08-24T14:09:33.000Z | 2021-08-30T12:47:40.000Z | src/Misc/Server.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <span.hpp>
#include <Enumerators/EMessageType.hpp>
#include <Enumerators/EPlayerRole.hpp>
#include <Exceptions/ENetInitializationFailedException.hpp>
#include <Exceptions/ENetPeerSendFailedException.hpp>
#include <Exceptions/InvalidNetworkPortException.hpp>
#include <Messages/AcceptPlayRequestMessage.hpp>
#include <Messages/AuthenticateMessage.hpp>
#include <Messages/DenyPlayRequestMessage.hpp>
#include <Messages/ErrorMessage.hpp>
#include <Messages/GetMatchHistoryMessage.hpp>
#include <Messages/HideMessage.hpp>
#include <Messages/HitMessage.hpp>
#include <Messages/LoadedGameMessage.hpp>
#include <Messages/LogMessage.hpp>
#include <Messages/LookMessage.hpp>
#include <Messages/MatchHistoryMessage.hpp>
#include <Messages/PingMessage.hpp>
#include <Messages/PlayWithRandomMessage.hpp>
#include <Messages/PlayWithSessionCodeMessage.hpp>
#include <Messages/PongMessage.hpp>
#include <Misc/MatchHistoryEntry.hpp>
#include <Misc/Message.hpp>
#include <Misc/MessageParser.hpp>
#include <Misc/Server.hpp>
#include <Static/ENetInitializer.hpp>
#include <Static/Defaults.hpp>
#include <Static/Rules.hpp>
#include <Static/SessionCodes.hpp>
#include <Static/UUIDs.hpp>
/// <summary>
/// Constructs a server
/// </summary>
/// <param name="port">Network port</param>
/// <param name="timeoutTime">Timeout time</param>
WhackAStoodentServer::Server::Server(std::uint16_t port, std::uint32_t timeoutTime) :
port(port),
timeoutTime(timeoutTime),
enetHost(nullptr),
networkingThread(nullptr),
isNetworkingThreadRunning(false)
{
if (!port)
{
throw WhackAStoodentServer::InvalidNetworkPortException(port);
}
WhackAStoodentServer::ENetInitializer::Initialize();
AddMessageParser<WhackAStoodentServer::Messages::ErrorMessage>
(
[](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::ErrorMessage& message)
{
peer->OnErrorReceived(message.GetErrorType(), message.GetErrorMessage());
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::AuthenticateMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::AuthenticateMessage& message)
{
uuids::uuid user_id(message.GetUserID());
std::wstring username(message.GetUsername());
if (lobby.IsPeerAnUser(peer))
{
peer->SendPeerMessage<WhackAStoodentServer::Messages::ErrorMessage>(EErrorType::InvalidMessageContext, L"You are already authenticated.");
}
else if (!user_id.is_nil() && lobby.IsUserIDOccupied(user_id))
{
peer->SendPeerMessage<WhackAStoodentServer::Messages::ErrorMessage>(EErrorType::Internal, L"User ID is already occupied.");
}
else
{
while (user_id.is_nil())
{
WhackAStoodentServer::UUIDs::CreateNewUUID(user_id);
if (lobby.IsUserIDOccupied(user_id))
{
user_id = uuids::uuid();
}
}
if (username.length() > WhackAStoodentServer::Rules::MaximalNameLength)
{
username = username.substr(static_cast<std::size_t>(0), WhackAStoodentServer::Rules::MaximalNameLength);
}
lobby.CreateUser(peer, user_id, username);
}
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::PingMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::PingMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[peer, messageData(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user)
{
std::int32_t ping_data(messageData.GetPingData());
user->OnPingReceived(ping_data);
peer->SendPeerMessage<WhackAStoodentServer::Messages::PongMessage>(ping_data);
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::PongMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::PongMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[messageData(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user)
{
std::int32_t pong_data(messageData.GetPongData());
user->OnPongReceived(pong_data);
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::GetMatchHistoryMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::GetMatchHistoryMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[peer](std::shared_ptr<WhackAStoodentServer::User> user)
{
std::vector<WhackAStoodentServer::MatchHistoryEntry> match_history;
user->OnMatchHistoryRequested();
// TODO: Get match history
peer->SendPeerMessage<WhackAStoodentServer::Messages::MatchHistoryMessage>(match_history);
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::PlayWithRandomMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::PlayWithRandomMessage& message)
{
AssertPeerIsAuthenticatedAndNotInGame
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user)
{
lobby.AddUserToSearch(user);
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::PlayWithSessionCodeMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::PlayWithSessionCodeMessage& message)
{
AssertPeerIsAuthenticatedAndNotInGame
(
peer,
[&, currentMessage(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user)
{
std::shared_ptr<WhackAStoodentServer::User> opposing_user;
if (lobby.TryGetUserFromSessionCode(currentMessage.GetSessionCode(), opposing_user))
{
lobby.RequestForPlaying(user, opposing_user);
}
else
{
std::wstringstream error_message;
error_message << L"Session code \"";
for (char character : currentMessage.GetSessionCode())
{
error_message << static_cast<wchar_t>(character);
}
error_message << L"\" does not exist.";
peer->SendPeerMessage<WhackAStoodentServer::Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, error_message.str());
}
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::AcceptPlayRequestMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::AcceptPlayRequestMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user)
{
lobby.AcceptPlayRequest(user);
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::DenyPlayRequestMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::DenyPlayRequestMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[&, messageData(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user)
{
lobby.DenyPlayRequest(user, messageData.GetReason());
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::LoadedGameMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::LoadedGameMessage& message)
{
AssertPeerIsInGame
(
peer,
[](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
user->SetGameLoadedState(true);
game->StartGame();
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::HitMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::HitMessage& message)
{
AssertPeerIsAHitter
(
peer,
[messageData(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
game->Hit(messageData.GetPosition());
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::LookMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::LookMessage& message)
{
AssertPeerIsAMole
(
peer,
[messageData(std::move(message))](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
game->Look(messageData.GetLookHole());
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::HideMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::HideMessage& message)
{
AssertPeerIsInGame
(
peer,
[](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
game->Hide();
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
AddMessageParser<WhackAStoodentServer::Messages::LogMessage>
(
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, const WhackAStoodentServer::Messages::LogMessage& message)
{
AssertPeerIsAuthenticated
(
peer,
[](std::shared_ptr<WhackAStoodentServer::User> user)
{
// TODO: Log message
}
);
},
[&](std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
HandleMessageParseFailedEvent(peer, message);
}
);
}
/// <summary>
/// Destroys server
/// </summary>
WhackAStoodentServer::Server::~Server()
{
Stop();
WhackAStoodentServer::ENetInitializer::Deinitialize();
}
/// <summary>
/// Starts this server
/// </summary>
/// <returns>"true" if starting server was successful, otherwise "false"</returns>
bool WhackAStoodentServer::Server::Start()
{
bool ret(!networkingThread);
if (ret)
{
std::size_t ban_count(bans.LoadFromFile(WhackAStoodentServer::Defaults::BansFilePath));
if (ban_count)
{
std::cout << "Successfully loaded " << ban_count << " " << ((ban_count == static_cast<std::size_t>(1)) ? "ban" : "bans") << " from \"" << WhackAStoodentServer::Defaults::BansFilePath << "\"." << std::endl;
}
isNetworkingThreadRunning = true;
networkingThread = new std::thread(NetworkingThread, this);
}
return ret;
}
/// <summary>
/// Stops this server
/// </summary>
void WhackAStoodentServer::Server::Stop()
{
if (networkingThread)
{
bans.SaveToFile(WhackAStoodentServer::Defaults::BansFilePath);
for (auto& peer : peers)
{
peer.second->Disconnect(WhackAStoodentServer::EDisconnectionReason::Stopped);
}
isNetworkingThreadRunning = false;
networkingThread->join();
networkingThread = nullptr;
}
}
/// <summary>
/// Is this server running
/// </summary>
/// <returns>"true" if this server is running, otherwise "false"</returns>
bool WhackAStoodentServer::Server::IsRunning() const
{
return !!enetHost;
}
/// <summary>
/// Processes messages
/// </summary>
/// <returns>"true" if server is still running, otherwise "false"</returns>
bool WhackAStoodentServer::Server::ProcessMessages()
{
bool ret(networkingThread);
if (ret)
{
{
ENetPeer* enet_peer;
while (connectedPeerQueue.TryDequeue(enet_peer))
{
std::shared_ptr<WhackAStoodentServer::Peer> peer(std::make_shared<WhackAStoodentServer::Peer>(enet_peer));
peers.insert_or_assign(enet_peer->incomingPeerID, peer);
peer->OnConnectionAttempted += [&, peer]()
{
std::cout << "Connection attempt from peer ID " << peer->GetIncomingPeerID() << " with IP " << peer->GetIPAddressString() << "." << std::endl;
OnPeerConnectionAttempted(peer);
};
peer->OnConnected += [&, peer]()
{
std::cout << "Peer ID " << peer->GetIncomingPeerID() << " with IP " << peer->GetIPAddressString() << " has connected." << std::endl;
OnPeerConnected(peer);
};
peer->OnDisconnected += [&, peer]()
{
std::cout << "Peer ID " << peer->GetIncomingPeerID() << " with IP " << peer->GetIPAddressString() << " has been disconnected." << std::endl;
OnPeerDisconnected(peer);
};
peer->OnMessageSent += [&, peer](std::shared_ptr<WhackAStoodentServer::Message> message)
{
outgoingMessages.Enqueue(std::make_pair(peer, message));
};
peer->OnConnectionAttempted();
if (bans.IsIPAddressBanned(peer->GetIPAddressString()))
{
peer->Disconnect(WhackAStoodentServer::EDisconnectionReason::Banned);
}
else
{
peer->OnConnected();
}
}
}
{
std::uint16_t incoming_peer_id;
while (disconnectedPeerQueue.TryDequeue(incoming_peer_id))
{
auto peers_iterator(peers.find(incoming_peer_id));
if (peers_iterator != peers.end())
{
std::shared_ptr<WhackAStoodentServer::User> user;
if (lobby.TryGetUserFromPeer(peers_iterator->second, user))
{
lobby.RemoveUser(user);
}
peers_iterator->second->OnDisconnected();
peers.erase(peers_iterator);
}
}
}
{
std::pair<std::uint16_t, std::shared_ptr<WhackAStoodentServer::Message>> received_messsage;
while (receivedMessageQueue.TryDequeue(received_messsage))
{
auto peers_iterator(peers.find(received_messsage.first));
if (peers_iterator != peers.end())
{
try
{
std::shared_ptr<WhackAStoodentServer::Peer> peer(peers_iterator->second);
WhackAStoodentServer::EMessageType message_type(received_messsage.second->GetMessageType());
auto message_parser_list_iterator(messageParserLists.find(message_type));
if (message_parser_list_iterator == messageParserLists.end())
{
peer->OnUnsupportedMessageTypeReceived(message_type);
peer->SendPeerMessage<Messages::ErrorMessage>(EErrorType::UnsupportedMessageType, L"Unsupported message type \"" + std::to_wstring(static_cast<int>(message_type)) + L"\" has been received.");
}
else
{
peer->OnMessageReceived(received_messsage.second);
for (const auto& message_parser : message_parser_list_iterator->second)
{
message_parser->ParsePeerMessage(peer, received_messsage.second);
}
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
}
}
lobby.ProcessTick();
}
return ret;
}
/// <summary>
/// Gets bans
/// </summary>
/// <returns>Bans</returns>
WhackAStoodentServer::Bans& WhackAStoodentServer::Server::GetBans()
{
return bans;
}
/// <summary>
/// Gets bans
/// </summary>
/// <returns>Bans</returns>
const WhackAStoodentServer::Bans& WhackAStoodentServer::Server::GetBans() const
{
return bans;
}
/// <summary>
/// Networking thread
/// </summary>
/// <param name="server">Server</param>
void WhackAStoodentServer::Server::NetworkingThread(Server* server)
{
ENetAddress enet_address;
enet_address_set_hostname(&enet_address, "localhost");
enet_address.port = server->port;
server->enetHost = enet_host_create
(
&enet_address,
static_cast<std::size_t>(ENET_PROTOCOL_MAXIMUM_PEER_ID),
static_cast<std::size_t>(ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT),
static_cast<std::uint32_t>(0),
static_cast<std::uint32_t>(0),
ENET_HOST_BUFFER_SIZE_MAX
);
if (server->enetHost)
{
ENetEvent enet_event;
std::pair<std::shared_ptr<WhackAStoodentServer::Peer>, std::shared_ptr<WhackAStoodentServer::Message>> outgoing_message;
bool is_polling;
while (server->isNetworkingThreadRunning)
{
while (server->outgoingMessages.TryDequeue(outgoing_message))
{
ENetPacket* packet(enet_packet_create(outgoing_message.second->GetData().data(), outgoing_message.second->GetData().size(), ENET_PACKET_FLAG_RELIABLE));
int error_code(enet_peer_send(outgoing_message.first->GetPeer(), 0, packet));
if (error_code)
{
throw WhackAStoodentServer::ENetPeerSendFailedException(outgoing_message.first.get(), error_code);
}
}
is_polling = true;
while (is_polling)
{
int host_service_result(enet_host_service(server->enetHost, &enet_event, server->timeoutTime));
is_polling = (host_service_result > 0);
if (is_polling)
{
switch (enet_event.type)
{
case ENET_EVENT_TYPE_NONE:
// ...
break;
case ENET_EVENT_TYPE_CONNECT:
server->connectedPeerQueue.Enqueue(enet_event.peer);
break;
case ENET_EVENT_TYPE_DISCONNECT:
case ENET_EVENT_TYPE_DISCONNECT_TIMEOUT:
server->disconnectedPeerQueue.Enqueue(enet_event.peer->incomingPeerID);
break;
case ENET_EVENT_TYPE_RECEIVE:
server->receivedMessageQueue.Enqueue(std::make_pair(enet_event.peer->incomingPeerID, std::make_shared<WhackAStoodentServer::Message>(nonstd::span<const std::uint8_t>(enet_event.packet->data, enet_event.packet->dataLength))));
enet_packet_destroy(enet_event.packet);
break;
default:
std::cerr << "Invalid ENet event type \"" << enet_event.type << "\"" << std::endl;
break;
}
}
else if (host_service_result < 0)
{
server->isNetworkingThreadRunning = false;
std::cerr << "Failed to poll events from ENet." << std::endl;
}
}
}
enet_host_destroy(server->enetHost);
server->enetHost = nullptr;
}
server->isNetworkingThreadRunning = false;
}
/// <summary>
/// Handles message parse failed event
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="message">Message</param>
void WhackAStoodentServer::Server::HandleMessageParseFailedEvent(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::shared_ptr<WhackAStoodentServer::Message> message)
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::MalformedMessage, L"Failed to parse message type \"" + std::to_wstring(static_cast<int>(message->GetMessageType())) + L"\"");
}
/// <summary>
/// Asserts that peer is authenticated
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="onPeerIsAuthenticated">USed to invoke when peer is authenticated</param>
void WhackAStoodentServer::Server::AssertPeerIsAuthenticated(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::function<void(std::shared_ptr<WhackAStoodentServer::User> user)> onPeerIsAuthenticated)
{
std::shared_ptr<WhackAStoodentServer::User> user;
if (lobby.TryGetUserFromPeer(peer, user))
{
onPeerIsAuthenticated(user);
}
else
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, L"You are not authenticated.");
}
}
/// <summary>
/// Asserts that peer is authenticated and is not in game
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="onPeerIsAuthenticatedAndNotInGame">Used to invoke when peer is authenticated as is in game</param>
void WhackAStoodentServer::Server::AssertPeerIsAuthenticatedAndNotInGame(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::function<void(std::shared_ptr<WhackAStoodentServer::User> user)> onPeerIsAuthenticatedAndNotInGame)
{
AssertPeerIsAuthenticated
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user)
{
if (lobby.IsUserInAGame(user))
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, L"You are already in a game.");
}
else
{
onPeerIsAuthenticatedAndNotInGame(user);
}
}
);
}
/// <summary>
/// Asserts that peer is in game
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="onPeerIsInGame">Used to invoke when peer is in game</param>
void WhackAStoodentServer::Server::AssertPeerIsInGame(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::function<void(std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)> onPeerIsInGame)
{
AssertPeerIsAuthenticated
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user)
{
std::shared_ptr<WhackAStoodentServer::Game> game;
if (lobby.TryGetUserGame(user, game))
{
onPeerIsInGame(user, game);
}
else
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, L"You are not in a game.");
}
}
);
}
/// <summary>
/// Asserts that peer is a hitter
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="onPeerIsAHitter">Used to invoke when peer is a hitter</param>
void WhackAStoodentServer::Server::AssertPeerIsAHitter(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::function<void(std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)> onPeerIsAHitter)
{
AssertPeerIsInGame
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
if (game->GetPlayerRole(user) == WhackAStoodentServer::EPlayerRole::Hitter)
{
onPeerIsAHitter(user, game);
}
else
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, L"You are not a hitter.");
}
}
);
}
/// <summary>
/// Asserts that peer is a mole
/// </summary>
/// <param name="peer">Peer</param>
/// <param name="onPeerIsAMole">Used to invoke when peer is a mole</param>
void WhackAStoodentServer::Server::AssertPeerIsAMole(std::shared_ptr<WhackAStoodentServer::Peer> peer, std::function<void(std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)> onPeerIsAMole)
{
AssertPeerIsInGame
(
peer,
[&](std::shared_ptr<WhackAStoodentServer::User> user, std::shared_ptr<WhackAStoodentServer::Game> game)
{
if (game->GetPlayerRole(user) == WhackAStoodentServer::EPlayerRole::Mole)
{
onPeerIsAMole(user, game);
}
else
{
peer->SendPeerMessage<Messages::ErrorMessage>(WhackAStoodentServer::EErrorType::InvalidMessageContext, L"You are not a mole.");
}
}
);
}
| 33.015449 | 241 | 0.719701 | [
"vector"
] |
bca809d637e52c23bde7e9cc1bb4d07c216c3e95 | 638 | hpp | C++ | src/KanjiBlockValueStrategy.hpp | Arthurmcarthur/MicrosoftCangjieTool | fb4efdc0ac5e01a03c09ba285f780fc2188e565f | [
"Apache-2.0"
] | 6 | 2020-10-18T05:02:56.000Z | 2021-03-31T10:18:06.000Z | src/KanjiBlockValueStrategy.hpp | Arthurmcarthur/MicrosoftCangjieTool | fb4efdc0ac5e01a03c09ba285f780fc2188e565f | [
"Apache-2.0"
] | null | null | null | src/KanjiBlockValueStrategy.hpp | Arthurmcarthur/MicrosoftCangjieTool | fb4efdc0ac5e01a03c09ba285f780fc2188e565f | [
"Apache-2.0"
] | 2 | 2021-02-05T10:26:13.000Z | 2021-07-04T01:13:02.000Z | //
// KanjiBlockValueStrategy.hpp
// mscjencodecpp
//
// Created by Qwetional on 19/6/2020.
// Copyright © 2020 Qwetional. All rights reserved.
//
#ifndef KanjiBlockValueStrategy_hpp
#define KanjiBlockValueStrategy_hpp
#include <vector>
#include <memory>
#include "MSCJKanji.hpp"
class KanjiBlockValueStrategy {
public:
static void kanjiBlockValueStrategyWithFirstTwoDuplicateCjCodeKanji(std::vector<std::shared_ptr<MSCJKanji>>& targetMSCJVector);
static void kanjiBlockValueStrategyWithFirstThreeDuplicateCjCodeKanji(std::vector<std::shared_ptr<MSCJKanji>>& targetMSCJVector);
};
#endif /* KanjiBlockValueStrategy_hpp */
| 27.73913 | 133 | 0.796238 | [
"vector"
] |
bcadf759287dcf5ee0391fce2a227d0134be4437 | 5,385 | cpp | C++ | src/psim/truth/orbit.cpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 5 | 2020-04-11T06:53:46.000Z | 2022-01-05T05:39:11.000Z | src/psim/truth/orbit.cpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 201 | 2019-09-05T03:46:21.000Z | 2022-01-08T04:44:16.000Z | src/psim/truth/orbit.cpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 10 | 2019-10-12T17:24:34.000Z | 2022-02-25T01:20:14.000Z | //
// MIT License
//
// Copyright (c) 2020 Pathfinder for Autonomous Navigation (PAN)
//
// 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.
//
/** @file psim/truth/orbit.cpp
* @author Kyle Krol
*/
#include <psim/truth/orbit.hpp>
#include <gnc/config.hpp>
#include <gnc/constants.hpp>
#include <gnc/utilities.hpp>
#include <lin/core.hpp>
#include <lin/generators.hpp>
#include <lin/math.hpp>
#include <lin/references.hpp>
#include <psim/truth/orbit_utilities.hpp>
namespace psim {
OrbitEcef::OrbitEcef(RandomsGenerator &randoms, Configuration const &config,
std::string const &satellite)
: Super(randoms, config, satellite, "ecef") {}
void OrbitEcef::step() {
this->Super::step();
struct IntegratorData {
Real const &m;
Real const &S;
Vector3 const &earth_w;
Vector3 const &earth_w_dot;
};
auto const &dt = truth_dt_s->get();
auto const &earth_w = truth_earth_w->get();
auto const &earth_w_dot = truth_earth_w_dot->get();
auto const &S = truth_satellite_S.get();
auto const &m = truth_satellite_m.get();
auto &r_ecef = truth_satellite_orbit_r.get();
auto &v_ecef = truth_satellite_orbit_v.get();
auto &J_ecef = truth_satellite_orbit_J_frame.get();
// Thruster firings are modelled here as instantaneous impulses. This removes
// thruster dependance from the state dot function in the integrator.
v_ecef = v_ecef + J_ecef / m;
J_ecef = lin::zeros<Vector3>();
// Prepare integrator inputs
Vector<6> x;
lin::ref<Vector3>(x, 0, 0) = r_ecef;
lin::ref<Vector3>(x, 3, 0) = v_ecef;
IntegratorData data = {m, S, earth_w, earth_w_dot};
// Simulate dynamics
x = ode(Real(0.0), dt, x, &data,
[](Real t, Vector<6> const &x, void *ptr) -> Vector<6> {
auto const *data = static_cast<IntegratorData *>(ptr);
auto const &m = data->m;
auto const &S = data->S;
auto const earth_w = (data->earth_w + t * data->earth_w_dot).eval();
auto const &earth_w_dot = data->earth_w_dot;
auto const r_ecef = lin::ref<Vector3>(x, 0, 0);
auto const v_ecef = lin::ref<Vector3>(x, 3, 0);
Vector3 const a_ecef = orbit::acceleration(
earth_w, earth_w_dot, r_ecef.eval(), v_ecef.eval(), S, m);
Vector<6> dx;
lin::ref<Vector3>(dx, 0, 0) = v_ecef;
lin::ref<Vector3>(dx, 3, 0) = a_ecef;
return dx;
});
// Write back to our state fields
r_ecef = lin::ref<Vector3>(x, 0, 0);
v_ecef = lin::ref<Vector3>(x, 3, 0);
}
Real OrbitEcef::truth_satellite_orbit_altitude() const {
auto const &r_ecef = truth_satellite_orbit_r.get();
return lin::norm(r_ecef) - gnc::constant::r_earth;
}
Vector3 OrbitEcef::truth_satellite_orbit_a_gravity() const {
auto const &r_ecef = truth_satellite_orbit_r.get();
return orbit::gravity(r_ecef);
}
Vector3 OrbitEcef::truth_satellite_orbit_a_drag() const {
auto const &S = truth_satellite_S.get();
auto const &m = truth_satellite_m.get();
auto const &r_ecef = truth_satellite_orbit_r.get();
auto const &v_ecef = truth_satellite_orbit_v.get();
return orbit::drag(r_ecef, v_ecef, S, m);
}
Vector3 OrbitEcef::truth_satellite_orbit_a_rot() const {
auto const &earth_w = truth_earth_w->get();
auto const &earth_w_dot = truth_earth_w_dot->get();
auto const &r_ecef = truth_satellite_orbit_r.get();
auto const &v_ecef = truth_satellite_orbit_v.get();
return orbit::rotational(earth_w, earth_w_dot, r_ecef, v_ecef);
}
Real OrbitEcef::truth_satellite_orbit_density() const {
auto const &r_ecef = truth_satellite_orbit_r.get();
return orbit::density(r_ecef);
};
Real OrbitEcef::truth_satellite_orbit_T() const {
static constexpr Real half = 0.5;
auto const &earth_w = truth_earth_w->get();
auto const &r_ecef = truth_satellite_orbit_r.get();
auto const &v_ecef = truth_satellite_orbit_v.get();
auto const &m = truth_satellite_m.get();
return half * m * lin::fro(v_ecef + lin::cross(earth_w, r_ecef));
}
Real OrbitEcef::truth_satellite_orbit_U() const {
auto const &r_ecef = truth_satellite_orbit_r.get();
auto const &m = truth_satellite_m.get();
Real U;
orbit::gravity(r_ecef, U);
return m * U;
}
Real OrbitEcef::truth_satellite_orbit_E() const {
auto const &T = this->Super::truth_satellite_orbit_T.get();
auto const &U = this->Super::truth_satellite_orbit_U.get();
return T - U;
}
} // namespace psim
| 31.491228 | 80 | 0.700836 | [
"vector"
] |
bcb027b627a7780f149cdc4d64188dcff149a9ef | 4,260 | cpp | C++ | src/ofxTPSprite.cpp | veketor/ofxTexturePacker | b2fc9605d6445c78df946c60288ee4213b2ec52d | [
"MIT"
] | null | null | null | src/ofxTPSprite.cpp | veketor/ofxTexturePacker | b2fc9605d6445c78df946c60288ee4213b2ec52d | [
"MIT"
] | null | null | null | src/ofxTPSprite.cpp | veketor/ofxTexturePacker | b2fc9605d6445c78df946c60288ee4213b2ec52d | [
"MIT"
] | null | null | null | // ------------------------------------------------------------------
// ofxTPSprite.cpp
// ofxTexturePacker - https://www.github.com/danoli3/ofxTexturePacker
// Created by Daniel Rosser and Colin Friend on 9/06/2014.
// ------------------------------------------------------------------
#include "ofxTPSprite.h"
ofxTPSprite::ofxTPSprite(ofxTPSpriteDataPtr theData) :
data(theData)
{
}
float ofxTPSprite::getWidth(){
return data->getW();
}
/*
ofxTPSpriteDataPtr ofxTPSprite::getData()
{
return data;
}
*/
float ofxTPSprite::getHeight()
{
return data->getHeight();
}
void ofxTPSprite::draw(int x, int y, int z) {
if(data->isRotated()) {
ofPushMatrix();
ofTranslate(x, y, z); // translate Draw position
x = y = z = 0;
ofPushMatrix();
// if(data->isDebugMode()){
// ofPushStyle(); //----------- Draw original unrotated texture
// ofSetColor(255, 0, 0, 128);
// ofNoFill();
// ofRect(x+data->getOffsetY(), y+data->getOffsetX(), data->getOffsetHeight(), data->getOffsetWidth());
// if(texture != NULL) {
// texture->drawSubsection(x+data->getOffsetY(), y+data->getOffsetX(), data->getW(), data->getH(), data->getX(), data->getY(), data->getW(), data->getH());
// }
// ofPopStyle();
// }
ofTranslate(data->getOffsetX(), data->getOffsetHeight()-data->getOffsetY());
ofRotateDeg(-90);
if(data->isDebugMode()){
ofPushStyle();
ofSetColor(0, 255, 0, 128);
ofNoFill();
ofDrawRectangle(x-data->getOffsetY(), y-data->getOffsetX(), data->getOffsetHeight(), data->getOffsetWidth());
ofPopStyle();
}
} else {
x += data->getOffsetX();
y += data->getOffsetY();
}
if(data->isDebugMode()){
if(!data->isRotated()){
ofPushStyle();
ofNoFill();
ofDrawRectangle(x-data->getOffsetX(), y-data->getOffsetY(), data->getOffsetWidth(), data->getOffsetHeight());
ofPopStyle();
}
}
if(texture != NULL) {
ofPushMatrix();
//ofLog() << data->getPX() << " " << data->getW();
ofTranslate(-data->getPX() * data->getW(), -data->getPY() * data->getH(), z);
texture->drawSubsection(x, y, data->getW(), data->getH(), data->getX(), data->getY(), data->getW(), data->getH());
ofNoFill();
//ofDrawRectangle(x, y, data->getW(), data->getH());
ofFill();
ofPopMatrix();
}
if(data->isRotated()) {
ofPopMatrix();
ofPopStyle();
ofPopMatrix();
}
}
ofMesh ofxTPSprite::getMesh()
{
ofMesh tempMesh;
if (data != NULL)
{
//Texture UV
float textureOffsetX = data->getX();
float textureOffsetY = data->getY();
float anchorX = data->getPX();
float anchorY = data->getPY();
//Mesh-Texture dimensions
float width = data->getW();
float height = data->getH();
//Mesh translation
float xOffset = data->getOffsetX() - anchorX*width;
float yOffset = data->getOffsetY() - anchorY*height;
tempMesh.setMode(OF_PRIMITIVE_TRIANGLES);
tempMesh.addVertex(ofDefaultVertexType(xOffset, yOffset, 0));
tempMesh.addTexCoord(ofVec2f(textureOffsetX, textureOffsetY));
tempMesh.addVertex(ofDefaultVertexType(xOffset, yOffset + height, 0));
tempMesh.addTexCoord(ofVec2f(textureOffsetX, textureOffsetY + height));
tempMesh.addVertex(ofDefaultVertexType(xOffset + width, yOffset, 0));
tempMesh.addTexCoord(ofVec2f(textureOffsetX + width, textureOffsetY));
tempMesh.addVertex(ofDefaultVertexType(xOffset + width, yOffset + height, 0));
tempMesh.addTexCoord(ofVec2f(textureOffsetX + width, textureOffsetY + height));
tempMesh.enableIndices();
tempMesh.addIndex(0);
tempMesh.addIndex(1);
tempMesh.addIndex(2);
tempMesh.addIndex(2);
tempMesh.addIndex(1);
tempMesh.addIndex(3);
}
return tempMesh;
}
of3dPrimitive ofxTPSprite::getPrimitive()
{
of3dPrimitive tempPrimitive;
ofMesh tempMesh = getMesh();
ofMesh *tempMeshOf3dPrimitivePTR = tempPrimitive.getMeshPtr();
tempMeshOf3dPrimitivePTR = &tempMesh;
return tempPrimitive;
}
| 32.769231 | 173 | 0.585915 | [
"mesh"
] |
bcb0b8c9a37b010a3ac5909798c35e22e3fc3ef3 | 10,630 | cpp | C++ | core/src/platform/Android/GCanvas2DContextAndroid.cpp | flyskywhy/GCanvas | b5e0109eedf6f278bde0bd5cbf2b193c8170f101 | [
"Apache-2.0"
] | 92 | 2020-12-23T09:56:00.000Z | 2022-03-31T19:45:55.000Z | core/src/platform/Android/GCanvas2DContextAndroid.cpp | flyskywhy/GCanvas | b5e0109eedf6f278bde0bd5cbf2b193c8170f101 | [
"Apache-2.0"
] | 33 | 2020-12-23T08:03:34.000Z | 2022-03-23T17:48:58.000Z | core/src/platform/Android/GCanvas2DContextAndroid.cpp | flyskywhy/GCanvas | b5e0109eedf6f278bde0bd5cbf2b193c8170f101 | [
"Apache-2.0"
] | 12 | 2020-12-23T08:02:45.000Z | 2022-03-24T06:43:30.000Z | /**
* Created by G-Canvas Open Source Team.
* Copyright (c) 2017, Alibaba, Inc. All rights reserved.
*
* This source code is licensed under the Apache Licence 2.0.
* For the full copyright and license information, please view
* the LICENSE file in the root directory of this source tree.
*/
#include "GCanvas2DContextAndroid.h"
#include "GFontCache.h"
#include "GPoint.h"
#include "GFontManagerAndroid.h"
#include "gcanvas/GFrameBufferObject.h"
#include "gcanvas/GShaderManager.h"
#include "support/Log.h"
GCanvas2DContextAndroid::GCanvas2DContextAndroid(uint32_t w, uint32_t h, GCanvasConfig &config) :
GCanvasContext(w, h, config) {
// init shader manager
mShaderManager = nullptr;
// init font cache
mFontCache = new GFontCache(*mFontManager);
GFontManagerAndroid *ptr = static_cast<GFontManagerAndroid *>(mFontManager);
if (ptr != nullptr) {
ptr->SetFontCache(mFontCache);
} else {
LOG_D("mFontManager init fail");
}
}
GCanvas2DContextAndroid::~GCanvas2DContextAndroid() {
// TODO 验证父类 delete 顺序
if (mFontCache != nullptr) {
delete mFontCache;
mFontCache = nullptr;
}
if (mShaderManager != nullptr) {
delete mShaderManager;
mShaderManager = nullptr;
}
}
bool GCanvas2DContextAndroid::InitializeGLShader() {
if (mShaderManager == nullptr) {
mShaderManager = new GShaderManager();
}
return GCanvasContext::InitializeGLShader();
}
GShader *GCanvas2DContextAndroid::FindShader(const char *name) {
return mShaderManager->programForKey(name);
}
void GCanvas2DContextAndroid::InitFBO() {
if (0 != mContextType) return;
if (!mConfig.useFbo) {
return;
}
if (!mIsFboSupported) {
return;
}
if (mFboMap.find(DefaultFboName) == mFboMap.end()) {
std::vector<GCanvasLog> logVec;
mIsFboSupported = mFboMap[DefaultFboName].InitFBO(mWidth, mHeight,
GColorTransparent, mEnableFboMsaa,
&logVec);
LOG_EXCEPTION_VECTOR(mHooks, mContextId.c_str(), logVec);
}
}
void GCanvas2DContextAndroid::ClearColor() {
GColorRGBA c = GColorTransparentWhite;
glClearColor(c.rgba.r, c.rgba.g, c.rgba.b, c.rgba.a);
glClear(GL_COLOR_BUFFER_BIT);
}
void GCanvas2DContextAndroid::GetRawImageData(int width, int height, uint8_t *pixels) {
SendVertexBufferToGPU();
glReadPixels(0, 0, width, height, GL_RGBA,
GL_UNSIGNED_BYTE, pixels);
}
//void GCanvas2DContextAndroid::GLBlend(GCompositeOperation op, GCompositeOperation alphaOp)
//{
// GBlendOperationFuncs funcs = GCompositeOperationFuncs(op);
// GBlendOperationFuncs alphaFuncs = GCompositeOperationFuncs(alphaOp);
//
// glBlendFuncSeparate(funcs.source, funcs.destination,
// alphaFuncs.source, alphaFuncs.destination);
//}
void GCanvas2DContextAndroid::BeginDraw(bool is_first_draw) {
if (mConfig.useFbo) {
// 深度test 一直开启
glEnable(GL_DEPTH_TEST);
BindFBO();
} else {
if (is_first_draw) {
// 非fbo模式下,首次渲染前执行一次清屏
ClearScreen();
}
}
}
void GCanvas2DContextAndroid::EndDraw() {
if (!mConfig.useFbo) {
return;
}
// FBO模式
UnbindFBO();
// 拷贝fbo前清空默认frameBuffer内容 (因为所有显示内容是叠加绘制在fbo上的)
ClearScreen();
// 拷贝FBO
DrawFBO(DefaultFboName);
}
GTexture *GCanvas2DContextAndroid::GetFBOTextureData() {
return &(mFboMap[DefaultFboName].mFboTexture);
}
/**
* 在改变canvas view大小时进行内容复制
* 新建fbo, 并进行fbo复制
*/
void GCanvas2DContextAndroid::ResizeCopyUseFbo(int width, int height) {
bool sizeChanged = mWidth != width || height != mHeight;
mWidth = width;
mHeight = height;
if (!sizeChanged) {
// LOG_D("execResizeWithGLStatus: not really changed, return");
return;
}
bool shouldChangeDimension = (mCanvasWidth <= 0 && mCanvasHeight <= 0);
if (0 == mContextType && mIsFboSupported) {
// 1.切换回主fbo
UnbindFBO();
// 2.新创建fbo
GFrameBufferObject *newFbo = new GFrameBufferObject();
mIsFboSupported = newFbo->InitFBO(mWidth, mHeight, GColorTransparent, mEnableFboMsaa,nullptr);
// 是否存在旧的fbo, 如果有则拷贝旧fbo并删除旧的
if (mFboMap.find(DefaultFboName) != mFboMap.end()) {
// 3.拷贝fbo
CopyFBO(mFboMap[DefaultFboName], *newFbo);
// 4.删除旧的fbo,并回收fbo资源
mFboMap.erase(DefaultFboName);
}
// 5.复制新FBO到map内(复制对象内存, 方法内的对象依然存在)
mFboMap[DefaultFboName] = *newFbo;
// 6.切换到新FBO上(可以绘制)
BindFBO();
// TODO newFbo对象也要想办法回收
// (直接释会导致FBO被删除,会导致功能异常)
}
// 如果画布尺寸为0,表示要跟随surface变换,继续以(0,0)更新dimension,计算新的变换矩阵
if (shouldChangeDimension) {
SetCanvasDimension(0, 0);
}
if (mContextType == 0) {
// 更新viewport变换
glViewport(0, 0, mWidth, mHeight);
}
}
void GCanvas2DContextAndroid::CopyFBO(GFrameBufferObject &srcFbo, GFrameBufferObject &destFbo) {
if (!mIsFboSupported) {
return;
}
if (nullptr == mCurrentState || nullptr == mCurrentState->mShader) {
return;
}
destFbo.BindFBO();
ResetGLBeforeCopyFrame(destFbo.mWidth, destFbo.mHeight);
GColorRGBA color = GColorWhite;
glBindTexture(GL_TEXTURE_2D, srcFbo.mFboTexture.GetTextureID());
PushRectangle(-1, -1, 2, 2, 0, 0, 1, 1, color);
glDrawArrays(GL_TRIANGLES, 0, mVertexBufferIndex);
mVertexBufferIndex = 0;
RestoreGLAfterCopyFrame();
// 拷贝完成,切回主fbo
UnbindFBO();
}
void
GCanvas2DContextAndroid::ResizeCopyUseImage(int width, int height, const unsigned char *rgbaData,
int imgWidth,
int imgHeight) {
bool sizeChanged = (mWidth != width) || (height != mHeight);
if (!sizeChanged) {
// LOGE("sizeChanged not changed");
return;
}
// 更新尺寸
mWidth = width;
mHeight = height;
bool shouldChangeDimension = (mCanvasWidth <= 0 && mCanvasHeight <= 0);
// 开始复制图像
if (rgbaData != nullptr) {
CopyImageToCanvas(width, height, rgbaData, imgWidth, imgHeight);
}
// 如果画布尺寸为0,表示要跟随surface变换,继续以(0,0)更新dimension,计算新的变换矩阵
if (shouldChangeDimension) {
SetCanvasDimension(0, 0);
}
// 更新viewport变换
glViewport(0, 0, width, height);
}
void GCanvas2DContextAndroid::CopyImageToCanvas(int width, int height,
const unsigned char *rgbaData, int imgWidth,
int imgHeight) {
ResetGLBeforeCopyFrame(width, height);
// 绑定图像纹理
GLuint glID = BindImage(rgbaData, GL_RGBA, (GLuint) imgWidth, (GLuint) imgHeight);
GColorRGBA color = GColorWhite;
PushRectangle(-1, -1, 2, 2, 0, 0, 1, 1, color);
mCurrentState->mShader->SetTransform(GTransformIdentity);
glDrawArrays(GL_TRIANGLES, 0, mVertexBufferIndex);
mVertexBufferIndex = 0;
glDeleteTextures(1, &glID);
RestoreGLAfterCopyFrame();
}
int
GCanvas2DContextAndroid::BindImage(const unsigned char *rgbaData, GLint format, unsigned int width,
unsigned int height) {
if (nullptr == rgbaData)
return (GLuint) -1;
GLenum glerror = 0;
GLuint glID;
glGenTextures(1, &glID);
glerror = glGetError();
if (glerror) {
// LOG_EXCEPTION("", "gen_texture_fail", "<function:%s, glGetError:%x>", __FUNCTION__,
// glerror);
}
glBindTexture(GL_TEXTURE_2D, glID);
glerror = glGetError();
if (glerror) {
// LOG_EXCEPTION("", "bind_texture_fail", "<function:%s, glGetError:%x>", __FUNCTION__,
// glerror);
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format,
GL_UNSIGNED_BYTE, rgbaData);
glerror = glGetError();
if (glerror) {
// LOG_EXCEPTION("", "glTexImage2D_failglTexImage2D_fail", "<function:%s, glGetError:%x>",
// __FUNCTION__, glerror);
}
return glID;
}
void
GCanvas2DContextAndroid::
DrawFBO(std::string fboName, GCompositeOperation compositeOp, float sx, float sy, float sw,
float sh, float dx, float dy, float dw, float dh) {
if (!mIsFboSupported) {
return;
}
if (nullptr == mCurrentState || nullptr == mCurrentState->mShader) {
return;
}
Save();
glViewport(mX, mY, mWidth, mHeight);
GFrameBufferObject &fbo = mFboMap[fboName];
UseDefaultRenderPipeline();
glDisable(GL_STENCIL_TEST);
glDisable(GL_DEPTH_TEST);
DoSetGlobalCompositeOperation(compositeOp, compositeOp);
GColorRGBA color = GColorWhite;
mCurrentState->mShader->SetOverideTextureColor(0);
mCurrentState->mShader->SetHasTexture(1);
fbo.mFboTexture.Bind();
PushRectangle(-1, -1, 2, 2, 0, 0, 1, 1, color);
mCurrentState->mShader->SetTransform(GTransformIdentity);
glDrawArrays(GL_TRIANGLES, 0, mVertexBufferIndex);
mVertexBufferIndex = 0;
if (HasClipRegion()) {
glEnable(GL_STENCIL_TEST);
glEnable(GL_DEPTH_TEST);
}
glViewport(0, 0, mWidth, mHeight);
Restore();
}
void GCanvas2DContextAndroid::ResetGLBeforeCopyFrame(int width, int height) {
Save();
GColorRGBA c = mClearColor;
SetClearColor(GColorTransparent);
ClearScreen();
SetClearColor(c);
glViewport(0, 0, width, height);
UseDefaultRenderPipeline();
glDisable(GL_STENCIL_TEST);
glDisable(GL_DEPTH_TEST);
GCompositeOperation compositeOp = COMPOSITE_OP_SOURCE_OVER;
DoSetGlobalCompositeOperation(compositeOp, compositeOp);
mCurrentState->mShader->SetOverideTextureColor(0);
mCurrentState->mShader->SetHasTexture(1);
mCurrentState->mShader->SetTransform(GTransformIdentity);
}
void GCanvas2DContextAndroid::RestoreGLAfterCopyFrame() {
if (HasClipRegion()) {
glEnable(GL_STENCIL_TEST);
}
glEnable(GL_DEPTH_TEST);
Restore();
}
void GCanvas2DContextAndroid::DrawFrame(bool clear) {
SendVertexBufferToGPU();
if (clear) {
ClearGeometryDataBuffers();
}
}
GShaderManager *GCanvas2DContextAndroid::GetShaderManager() {
return this->mShaderManager;
} | 27.53886 | 102 | 0.647037 | [
"vector"
] |
bcb2135a66eb3042228a3c1dcad9d51d1c693bc9 | 2,555 | cpp | C++ | ParticleEntities/ModelLoader.cpp | EdwinRy/ParticleGameEngine | fe3b049275277092507e10c97b3ad8783ba949c9 | [
"Apache-2.0"
] | null | null | null | ParticleEntities/ModelLoader.cpp | EdwinRy/ParticleGameEngine | fe3b049275277092507e10c97b3ad8783ba949c9 | [
"Apache-2.0"
] | null | null | null | ParticleEntities/ModelLoader.cpp | EdwinRy/ParticleGameEngine | fe3b049275277092507e10c97b3ad8783ba949c9 | [
"Apache-2.0"
] | null | null | null | #include "ModelLoader.h"
#include "FileStream.h"
#include <iostream>
using namespace Entity;
using namespace glm;
#define NEXT_INT(i, data) \
(i) = atoi(data); \
(data) = strchr(data, '/') + 1
inline void readVertexData(string vertex, int *v, int *t, int *n)
{
const char *data = vertex.data();
NEXT_INT(*v, data);
NEXT_INT(*t, data);
*n = atoi(data);
}
void ModelLoader::loadOBJ(string path)
{
// Open file stream and clear buffers
FileInputStream stream(path);
positions.clear();
textures.clear();
normals.clear();
isStartOfFile = true;
while (!stream.isEndOfFile())
{
string command = stream.readWord();
if (command == "v")
positions.push_back(stream.readVec3());
else if (command == "vt")
textures.push_back(stream.readVec2());
else if (command == "vn")
normals.push_back(stream.readVec3());
// Build face with data
else if (command == "f")
buildFace(&stream);
// Next object
else if (command == "o")
nextMesh(stream.readWord());
// If unkown or comment, then skip line
else
stream.readLine();
}
if (!isStartOfFile)
meshData.push_back(currMesh);
}
void ModelLoader::buildFace(FileInputStream *stream)
{
int v, t, n;
for (int i = 0; i < 3; i++)
{
// Read vertex data
string face = stream->readWord();
readVertexData(face, &v, &t, &n);
// Push data to mesh
vec3 position = positions[v - 1];
currMesh.positions.push_back(position.x);
currMesh.positions.push_back(position.y);
currMesh.positions.push_back(position.z);
vec2 texture = textures[t - 1];
currMesh.textures.push_back(texture.x);
currMesh.textures.push_back(texture.y);
vec3 normal = normals[n - 1];
currMesh.normals.push_back(normal.x);
currMesh.normals.push_back(normal.y);
currMesh.normals.push_back(normal.z);
// Push next index
currMesh.indices.push_back(currMesh.indices.size());
}
}
// Rotate to the next mesh
void ModelLoader::nextMesh(string name)
{
if (!isStartOfFile)
meshData.push_back(currMesh);
currMesh = {name};
isStartOfFile = false;
}
MeshData ModelLoader::popMesh()
{
MeshData mesh = meshData[meshData.size()-1];
meshData.pop_back();
return mesh;
}
bool ModelLoader::hasNextMesh()
{
return meshData.size() > 0;
}
| 24.103774 | 65 | 0.591389 | [
"mesh",
"object"
] |
bcb6d2ec8763fad6cf6a9d6b9e8228e208bb2b52 | 2,191 | hpp | C++ | include/fxt/static_feature.hpp | ten-blue-links/fxt | 938a9cbd0286999652c1601c8c0bf0989c992c4b | [
"MIT"
] | 11 | 2020-09-05T08:06:47.000Z | 2021-11-02T06:55:11.000Z | include/fxt/static_feature.hpp | lgrz/fxt | 92d369e1e32c349e94020d04b9e814daf8ee84a4 | [
"MIT"
] | 25 | 2019-01-15T04:45:06.000Z | 2020-06-02T03:49:50.000Z | include/fxt/static_feature.hpp | rmit-ir/tesserae | 938a9cbd0286999652c1601c8c0bf0989c992c4b | [
"MIT"
] | 5 | 2018-12-29T14:08:31.000Z | 2019-12-11T20:32:29.000Z | /*
* Copyright 2018 The Fxt authors.
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
#pragma once
#include <cstdint>
#include <iostream>
#include <vector>
#include "statdoc_entry.hpp"
#include "cereal/types/vector.hpp"
/*
* Static document feature list.
*/
class StaticFeature {
public:
statdoc_entry dentry;
StaticFeature() = default;
StaticFeature(const uint32_t l, const uint32_t tl, const uint32_t vtl,
const uint16_t ul, const uint16_t ud, const double avgtl,
const double ent, const double sc, const double fs,
const double fat, const double fvt, const double ftab,
const double ftd, const uint8_t wiki) {
// Avoid using a constructor for `statdoc_entry` becuase we have a crude
// code genreation process for statdoc_entry_flag.hpp and
// doc_entry_flag.hpp. See script/feat2struct.sh.
dentry.len = l;
dentry.title_len = tl;
dentry.visterm_len = vtl;
dentry.url_len = ul;
dentry.url_depth = ud;
dentry.avg_term_len = avgtl;
dentry.entropy = ent;
dentry.stop_cover = sc;
dentry.frac_stop = fs;
dentry.frac_anchor_text = fat;
dentry.frac_vis_text = fvt;
dentry.frac_table_text = ftab;
dentry.frac_td_text = ftd;
dentry.is_wikipedia = wiki;
}
StaticFeature(const statdoc_entry &de)
: StaticFeature(de.len, de.title_len, de.visterm_len, de.url_len,
de.url_depth, de.avg_term_len, de.entropy, de.stop_cover,
de.frac_stop, de.frac_anchor_text, de.frac_vis_text,
de.frac_table_text, de.frac_td_text, de.is_wikipedia) {}
template <class Archive>
void serialize(Archive &archive) {
archive(dentry.len, dentry.title_len, dentry.visterm_len, dentry.url_len,
dentry.url_depth, dentry.avg_term_len, dentry.entropy,
dentry.stop_cover, dentry.frac_stop, dentry.frac_anchor_text,
dentry.frac_vis_text, dentry.frac_table_text, dentry.frac_td_text,
dentry.is_wikipedia);
}
};
using StaticDocFeatureList = std::vector<StaticFeature>;
| 33.707692 | 79 | 0.68188 | [
"vector"
] |
344a93b358a60393e26ccf716ac8cda862c60015 | 12,422 | cpp | C++ | src/Project/Config.cpp | Electrux/ccp4m | 209b0d69e65824c27f01482ddf06c2de7dfaa91f | [
"BSD-3-Clause"
] | 2 | 2018-06-12T08:28:58.000Z | 2021-01-19T00:12:12.000Z | src/Project/Config.cpp | Electrux/CCP4M-Final | 209b0d69e65824c27f01482ddf06c2de7dfaa91f | [
"BSD-3-Clause"
] | null | null | null | src/Project/Config.cpp | Electrux/CCP4M-Final | 209b0d69e65824c27f01482ddf06c2de7dfaa91f | [
"BSD-3-Clause"
] | null | null | null | #include <vector>
#include <string>
#include <cstdlib>
#include <yaml-cpp/yaml.h>
#include "../../include/DisplayFuncs.hpp"
#include "../../include/FSFuncs.hpp"
#include "../../include/Environment.hpp"
#include "../../include/Vars.hpp"
#include "../../include/Core.hpp"
#include "../../include/Project/Licenses.hpp"
#include "../../include/Project/Config.hpp"
// Helper function to avoid crash of YAML-CPP
template< typename T > std::string GetString( T & t, const std::string & v )
{
if( t[ v ] ) return t[ v ].template as< std::string >();
return "";
}
template< typename T > std::string GetString( T & t, const std::string & v, const std::string & v2 )
{
if( t[ v ] && t[ v ][ v2 ] ) return t[ v ][ v2 ].template as< std::string >();
return "";
}
template< typename T > std::vector< std::string > GetStringVector( T & t, const std::string & v )
{
std::vector< std::string > res;
if( t[ v ] ) {
for( auto val : t[ v ] ) {
res.push_back( val.template as< std::string >() );
}
}
return res;
}
template< typename T > std::vector< std::string > GetStringVector( T & t, const std::string & v, const std::string & v2 )
{
std::vector< std::string > res;
if( t[ v ] && t[ v ][ v2 ] ) {
for( auto val : t[ v ][ v2 ] ) {
res.push_back( val.template as< std::string >() );
}
}
return res;
}
static std::string VarReplace( std::string && str, bool really_replace )
{
static auto v = Vars::GetSingleton();
if( really_replace ) v->Replace( str );
return str;
}
static std::vector< std::string > VarReplace( std::vector< std::string > && vec, bool really_replace )
{
static auto v = Vars::GetSingleton();
if( really_replace ) v->Replace( vec );
return vec;
}
void ProjectConfig::AddLibrary( const Config::Library & lib )
{
if( !lib.name.empty() ) pdata.libs.push_back( lib );
}
void ProjectConfig::AddBuild( const Config::Build & build )
{
if( !build.name.empty() ) pdata.builds.push_back( build );
}
std::string ProjectConfig::GetDefaultMainFile()
{
std::string res;
if( this->pdata.lang == "c" ) res = "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n\treturn 0;\n}";
else res = "#include <iostream>\n\nint main()\n{\n\treturn 0;\n}";
return res;
}
Config::ProjectData & ProjectConfig::GetData()
{
return this->pdata;
}
bool ProjectConfig::GetDefaultAuthor()
{
Core::logger.AddLogSection( "ProjectConfig" );
Core::logger.AddLogSection( "GetDefaultAuthor" );
Core::logger.AddLogString( LogLevels::ALL, "Fetching default author information from system configuration" );
YAML::Node conf = YAML::LoadFile( Env::CCP4M_CONFIG_FILE );
auto v = Vars::GetSingleton();
pdata.author.name = v->Replace( GetString( conf, "name" ) );
pdata.author.email = v->Replace( GetString( conf, "email" ) );
if( pdata.author.name.empty() || pdata.author.email.empty() ) {
Display( "{r}Unable to fetch name and email from system config.{0}" );
Core::logger.AddLogString( LogLevels::ALL, "Default author information fetch failed. Name and/or email does not exist" );
return Core::ReturnVar( false );
}
v->AddVar( "author", pdata.author.name );
Core::logger.AddLogString( LogLevels::ALL, "Default author information fetched successfully - Name: " + pdata.author.name + " Email: " + pdata.author.email );
return Core::ReturnVar( true );
}
bool ProjectConfig::GenerateDefaultConfig()
{
if( !this->GetDefaultAuthor() ) return false;
Core::logger.AddLogSection( "ProjectConfig" );
Core::logger.AddLogSection( "GenerateDefaultConfig" );
pdata.name = "UntitledProject";
pdata.version = "0.1";
pdata.lang = "c++";
pdata.std = "14";
pdata.compile_flags = "-O2";
pdata.license = License::LICENSES[ License::DEFAULT_LICENSE ];
Config::Build build;
build.name = "DefaultBuild";
build.type = "bin";
build.main_src = "src/main.cpp";
build.srcs.push_back( "src/(.*).cpp" );
pdata.builds.push_back( build );
return Core::ReturnVar( true );
}
bool ProjectConfig::LoadFile( const std::string & file, bool update_license, bool alter_vars )
{
if( !FS::LocExists( file ) ) return false;
Core::logger.AddLogSection( "ProjectConfig" );
Core::logger.AddLogSection( "LoadFile" );
Core::logger.AddLogString( LogLevels::ALL, "Loading configuration from file: " + file );
YAML::Node conf = YAML::LoadFile( file );
auto v = Vars::GetSingleton();
pdata.name = VarReplace( GetString( conf, "name" ), alter_vars );
pdata.version = VarReplace( GetString( conf, "version" ), alter_vars );
pdata.lang = VarReplace( GetString( conf, "lang" ), alter_vars );
pdata.std = VarReplace( GetString( conf, "std" ), alter_vars );
pdata.compile_flags = VarReplace( GetString( conf, "compile_flags" ), alter_vars );
for( auto vars : conf[ "vars" ] ) {
Config::Vars var;
var.name = VarReplace( GetString( vars, "name" ), alter_vars );
var.val = VarReplace( GetString( vars, "val" ), alter_vars );
pdata.vars.push_back( var );
v->AddVar( var.name, var.val );
}
pdata.license = VarReplace( GetString( conf, "license" ), alter_vars );
v->AddVar( "license", License::FetchLicenseFormalName( pdata.license ) );
if( !License::UpdateProjectLicenseFile( pdata.license, update_license ) ) return Core::ReturnVar( 1 );
pdata.author.name = VarReplace( GetString( conf, "author", "name" ), alter_vars );
pdata.author.email = VarReplace( GetString( conf, "author", "email" ), alter_vars );
if( ( pdata.author.name.empty() || pdata.author.email.empty() ) && !this->GetDefaultAuthor() ) {
Core::logger.AddLogString( LogLevels::ALL, "Configuration load failed. No author information in this file or in system configuration" );
return Core::ReturnVar( false );
}
v->AddVar( "name", pdata.name );
v->AddVar( "author", pdata.author.name );
for( auto libdata : conf[ "libs" ] ) {
Config::Library lib;
lib.name = VarReplace( GetString( libdata, "name" ), alter_vars );
lib.version = VarReplace( GetString( libdata, "version" ), alter_vars );
lib.inc_flags = VarReplace( GetString( libdata, "inc_flags" ), alter_vars );
lib.lib_flags = VarReplace( GetString( libdata, "lib_flags" ), alter_vars );
pdata.libs.push_back( lib );
}
for( auto builddata : conf[ "builds" ] ) {
Config::Build build;
build.name = VarReplace( GetString( builddata, "name" ), alter_vars );
build.type = VarReplace( GetString( builddata, "type" ), alter_vars );
build.build_type = VarReplace( GetString( builddata, "build_type" ), alter_vars );
build.inc_flags = VarReplace( GetString( builddata, "inc_flags" ), alter_vars );
build.lib_flags = VarReplace( GetString( builddata, "lib_flags" ), alter_vars );
build.pre_exec = VarReplace( GetString( builddata, "pre_exec" ), alter_vars );
build.main_src = VarReplace( GetString( builddata, "main_src" ), alter_vars );
build.srcs = VarReplace( GetStringVector( builddata, "other_src" ), alter_vars );
build.exclude = VarReplace( GetStringVector( builddata, "exclude" ), alter_vars );
pdata.builds.push_back( build );
}
// Update local environment
pdata.local_env = VarReplace( GetStringVector( conf, "env" ), alter_vars );
for( auto env : pdata.local_env ) {
putenv( &env[0] );
}
Core::logger.AddLogString( LogLevels::ALL, "Loaded configuration file successfully" );
return Core::ReturnVar( true );
}
bool ProjectConfig::SaveFile( const std::string & file )
{
if( !FS::CreateFile( file ) ) return false;
Core::logger.AddLogSection( "ProjectConfig" );
Core::logger.AddLogSection( "SaveFile" );
Core::logger.AddLogString( LogLevels::ALL, "Saving configuration for: " + pdata.name + " to file: " + file );
auto v = Vars::GetSingleton();
v->AddVar( "name", pdata.name );
v->AddVar( "author", pdata.author.name );
v->AddVar( "license", License::FetchLicenseFormalName( pdata.license ) );
YAML::Emitter o;
o << YAML::BeginMap;
o << YAML::Key << "name" << YAML::Value << pdata.name;
o << YAML::Key << "version" << YAML::Value << pdata.version;
o << YAML::Key << "lang" << YAML::Value << pdata.lang;
o << YAML::Key << "std" << YAML::Value << pdata.std;
o << YAML::Key << "compile_flags" << YAML::Value << pdata.compile_flags;
o << YAML::Key << "vars" << YAML::Value;
o << YAML::BeginSeq;
for( auto & var : pdata.vars ) {
o << YAML::BeginMap;
o << YAML::Key << "name" << YAML::Value << var.name;
o << YAML::Key << "val" << YAML::Value << var.val;
o << YAML::EndMap;
}
o << YAML::EndSeq;
o << YAML::Key << "license" << YAML::Value << pdata.license;
o << YAML::Key << "author" << YAML::Value;
o << YAML::BeginMap;
o << YAML::Key << "name" << YAML::Value << pdata.author.name;
o << YAML::Key << "email" << YAML::Value << pdata.author.email;
o << YAML::EndMap;
o << YAML::Key << "libs" << YAML::Value;
o << YAML::BeginSeq;
for( auto & lib : pdata.libs ) {
o << YAML::BeginMap;
o << YAML::Key << "name" << YAML::Value << lib.name;
o << YAML::Key << "version" << YAML::Value << lib.version;
o << YAML::Key << "inc_flags" << YAML::Value << lib.inc_flags;
o << YAML::Key << "lib_flags" << YAML::Value << lib.lib_flags;
o << YAML::EndMap;
}
o << YAML::EndSeq;
o << YAML::Key << "builds" << YAML::Value;
o << YAML::BeginSeq;
for( auto & build : pdata.builds ) {
o << YAML::BeginMap;
o << YAML::Key << "name" << YAML::Value << build.name;
o << YAML::Key << "type" << YAML::Value << build.type;
if( build.type == "lib" ) o << YAML::Key << "build_type" << YAML::Value << build.build_type;
o << YAML::Key << "inc_flags" << YAML::Value << build.inc_flags;
o << YAML::Key << "lib_flags" << YAML::Value << build.lib_flags;
o << YAML::Key << "pre_exec" << YAML::Value << build.pre_exec;
o << YAML::Key << "main_src" << YAML::Value << build.main_src;
o << YAML::Key << "other_src" << YAML::Value;
o << YAML::BeginSeq;
for( auto src : build.srcs ) o << src;
o << YAML::EndSeq;
o << YAML::Key << "exclude" << YAML::Value;
o << YAML::BeginSeq;
for( auto exc : build.exclude ) o << exc;
o << YAML::EndSeq;
o << YAML::EndMap;
}
o << YAML::EndSeq;
o << YAML::Key << "env" << YAML::Value;
o << YAML::BeginSeq;
for( auto & env : pdata.local_env ) o << env;
o << YAML::EndSeq;
o << YAML::EndMap;
if( FS::CreateFile( file, o.c_str() ) ) {
Core::logger.AddLogString( LogLevels::ALL, "Configuration file successfully saved" );
return Core::ReturnVar( true );
}
Core::logger.AddLogString( LogLevels::ALL, "Configuration file save failed" );
return Core::ReturnVar( false );
}
void ProjectConfig::DisplayAll( const std::string & dir )
{
Display( "{by}-------------------------------------------------\n\n" );
Display( "{sc}=> {bm}Author{0}: {bg}" + pdata.author.name + " {0}< {bg}" + pdata.author.email + " {0}>\n" );
if( !dir.empty() ) Display( "{sc}=> {bm}Directory{0}: {bg}" + dir + "\n" );
Display( "{sc}=> {bm}Name{0}: {bg}" + pdata.name + "\n" );
Display( "{sc}=> {bm}Version{0}: {bg}" + pdata.version + "\n" );
Display( "{sc}=> {bm}Lang{0}: {bg}" + pdata.lang + "\n" );
Display( "{sc}=> {bm}Std{0}: {bg}" + pdata.std + "\n" );
Display( "{sc}=> {bm}Compile_Flags{0}: {bg}" + pdata.compile_flags + "\n" );
Display( "{sc}=> {bm}Vars{0}:\n" );
for( auto v : pdata.vars ) {
Display( "{sc}===> {bm}Name{0}: {bg}" + v.name + "\n" );
Display( "{sc}===> {bm}Value{0}: {bg}" + v.val + "\n\n" );
}
Display( "{sc}=> {bm}License{0}: {bg}" + pdata.license + "\n\n" );
Display( "{sc}=> {bm}Libs{0}:\n" );
for( auto lib : pdata.libs ) {
Display( "{sc}===> {bm}Name{0}: {bg}" + lib.name + "\n" );
Display( "{sc}===> {bm}Version{0}: {bg}" + lib.version + "\n" );
Display( "{sc}===> {bm}Inc_Flags{0}: {bg}" + lib.inc_flags + "\n" );
Display( "{sc}===> {bm}Lib_Flags{0}: {bg}" + lib.lib_flags + "\n\n" );
}
Display( "{sc}=> {bm}Builds{0}:\n" );
for( auto build : pdata.builds ) {
Display( "{sc}===> {bm}Name{0}: {bg}" + build.name + "\n" );
Display( "{sc}===> {bm}Type{0}: {bg}" + build.type + "\n" );
if( build.type == "lib" ) Display( "{sc}===> {bm}Build Type{0}: {bg}" + build.build_type + "\n" );
Display( "{sc}===> {bm}Inc_Flags: {bg}" + build.inc_flags + "\n" );
Display( "{sc}===> {bm}Lib_Flags: {bg}" + build.lib_flags + "\n" );
Display( "{sc}===> {bm}Pre_Exec: {bg}" + build.pre_exec + "\n" );
Display( "{sc}===> {bm}Main source{0}: {bg}" + build.main_src + "\n" );
Display( "{sc}===> {bm}Other sources{0}:\n" );
for( auto s : build.srcs ) Display( "{sc}=====> {bg}" + s + "\n" );
}
Display( "\n{by}--------------------------------------------------{0}\n");
}
| 33.939891 | 159 | 0.621559 | [
"vector"
] |
34508bb463cc2135cb4580f87807487b00b8e377 | 549 | cpp | C++ | atcoder/abc124/B/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc124/B/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc124/B/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int N;
vector<int> H;
cin >> N;
H.assign(N, 0);
for (int i = 0; i < N; ++i) {
cin >> H[i];
}
int ans = 1;
for (int i = 1; i < N; ++i) {
bool ok = true;
for (int j = 0; j < i; ++j) {
if (H[j] > H[i]) {
ok = false;
break;
}
}
if (ok) ans++;
}
cout << ans << endl;
return 0;
} | 17.15625 | 37 | 0.378871 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.