hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
4051c11acd99748fc57755afe3ffd9517d1af0d6
14,461
cc
C++
cpp/platform/pipe_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
cpp/platform/pipe_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
cpp/platform/pipe_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "platform/pipe.h" #include <pthread.h> #include <cstring> #include "platform/api/platform.h" #include "platform/port/string.h" #include "platform/prng.h" #include "platform/ptr.h" #include "platform/runnable.h" #include "gtest/gtest.h" #include "absl/time/clock.h" namespace location { namespace nearby { namespace { using SamplePipe = Pipe; TEST(PipeTest, SimpleWriteRead) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); std::string data("ABCD"); ASSERT_EQ(Exception::NONE, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream->read(); ASSERT_TRUE(read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_read_data(read_data.result()); ASSERT_EQ(data.size(), scoped_read_data->size()); ASSERT_EQ(0, memcmp(data.data(), scoped_read_data->getData(), scoped_read_data->size())); } TEST(PipeTest, WriteEndClosedBeforeRead) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); std::string data("ABCD"); ASSERT_EQ(Exception::NONE, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); // Close the write end before the read end has even begun reading. ASSERT_EQ(Exception::NONE, output_stream->close()); // We should still be able to read what was written. ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream->read(); ASSERT_TRUE(read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_read_data(read_data.result()); ASSERT_EQ(data.size(), scoped_read_data->size()); ASSERT_EQ(0, memcmp(data.data(), scoped_read_data->getData(), scoped_read_data->size())); // And after that, we should get our indication that all the data that could // ever be read, has already been read. read_data = input_stream->read(); ASSERT_TRUE(read_data.ok()); ASSERT_TRUE(read_data.result().isNull()); } TEST(PipeTest, ReadEndClosedBeforeWrite) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); // Close the read end before the write end has even begun writing. ASSERT_EQ(Exception::NONE, input_stream->close()); std::string data("ABCD"); ASSERT_EQ(Exception::IO, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); } TEST(PipeTest, SizedReadMoreThanFirstChunkSize) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); std::string data("ABCD"); ASSERT_EQ(Exception::NONE, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); // Even though we ask for double of what's there in the first chunk, we should // get back only what's there in that first chunk, and that's alright. ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream->read(data.size() * 2); ASSERT_TRUE(read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_read_data(read_data.result()); ASSERT_EQ(data.size(), scoped_read_data->size()); ASSERT_EQ(0, memcmp(data.data(), scoped_read_data->getData(), scoped_read_data->size())); } TEST(PipeTest, SizedReadLessThanFirstChunkSize) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); // Compose 'data' of 2 parts, to make it easier to validate our expectations. std::string data_first_part("ABCD"); std::string data_second_part("EFGHIJ"); std::string data = data_first_part + data_second_part; ASSERT_EQ(Exception::NONE, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); // When we ask for less than what's there in the first chunk, we should get // back exactly what we asked for, with the remainder still being available // for the next read. std::int64_t desired_size = data_first_part.size(); ExceptionOr<ConstPtr<ByteArray>> first_read_data = input_stream->read(desired_size); ASSERT_TRUE(first_read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_first_read_data( first_read_data.result()); ASSERT_EQ(desired_size, scoped_first_read_data->size()); ASSERT_EQ(0, memcmp(data_first_part.data(), scoped_first_read_data->getData(), scoped_first_read_data->size())); // Now read the remainder, and get everything that ought to have been left. std::int64_t remaining_size = data_second_part.size(); ExceptionOr<ConstPtr<ByteArray>> second_read_data = input_stream->read(); ASSERT_TRUE(second_read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_second_read_data( second_read_data.result()); ASSERT_EQ(remaining_size, scoped_second_read_data->size()); ASSERT_EQ(0, memcmp(data_second_part.data(), scoped_second_read_data->getData(), scoped_second_read_data->size())); } TEST(PipeTest, ReadAfterInputStreamClosed) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); input_stream->close(); ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream->read(); ASSERT_TRUE(!read_data.ok()); ASSERT_EQ(Exception::IO, read_data.exception()); } TEST(PipeTest, WriteAfterOutputStreamClosed) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); output_stream->close(); std::string data("ABCD"); ASSERT_EQ(Exception::IO, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); } TEST(PipeTest, RepeatedClose) { auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<InputStream>> input_stream(SamplePipe::createInputStream(pipe)); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); ASSERT_EQ(Exception::NONE, output_stream->close()); ASSERT_EQ(Exception::NONE, output_stream->close()); ASSERT_EQ(Exception::NONE, output_stream->close()); ASSERT_EQ(Exception::NONE, input_stream->close()); ASSERT_EQ(Exception::NONE, input_stream->close()); ASSERT_EQ(Exception::NONE, input_stream->close()); } class Thread { public: Thread() : thread_(), attr_(), runnable_() { pthread_attr_init(&attr_); pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_JOINABLE); } ~Thread() { pthread_attr_destroy(&attr_); } void start(Ptr<Runnable> runnable) { runnable_ = runnable; pthread_create(&thread_, &attr_, Thread::body, this); } void join() { pthread_join(thread_, nullptr); runnable_.destroy(); } private: static void* body(void* args) { reinterpret_cast<Thread*>(args)->runnable_->run(); return nullptr; } pthread_t thread_; pthread_attr_t attr_; Ptr<Runnable> runnable_; }; TEST(PipeTest, ReadBlockedUntilWrite) { typedef volatile bool CrossThreadBool; class ReaderRunnable : public Runnable { public: ReaderRunnable(Ptr<InputStream> input_stream, const std::string& expected_read_data, CrossThreadBool* ok_for_read_to_unblock) : input_stream_(input_stream), expected_read_data_(expected_read_data), ok_for_read_to_unblock_(ok_for_read_to_unblock) {} ~ReaderRunnable() override {} void run() override { ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream_->read(); // Make sure read() doesn't return before it's appropriate. if (!*ok_for_read_to_unblock_) { FAIL() << "read() unblocked before it was supposed to."; } // And then run our normal set of checks to make sure the read() was // successful. ASSERT_TRUE(read_data.ok()); ScopedPtr<ConstPtr<ByteArray>> scoped_read_data(read_data.result()); ASSERT_EQ(expected_read_data_.size(), scoped_read_data->size()); ASSERT_EQ(0, memcmp(expected_read_data_.data(), scoped_read_data->getData(), scoped_read_data->size())); } private: ScopedPtr<Ptr<InputStream>> input_stream_; const std::string& expected_read_data_; CrossThreadBool* ok_for_read_to_unblock_; }; auto pipe = MakeRefCountedPtr(new SamplePipe()); ScopedPtr<Ptr<OutputStream>> output_stream( SamplePipe::createOutputStream(pipe)); // State shared between this thread (the writer) and reader_thread. CrossThreadBool ok_for_read_to_unblock = false; std::string data("ABCD"); // Kick off reader_thread. Thread reader_thread; reader_thread.start(MakePtr(new ReaderRunnable( SamplePipe::createInputStream(pipe), data, &ok_for_read_to_unblock))); // Introduce a delay before we actually write anything. absl::SleepFor(absl::Seconds(5)); // Mark that we're done with the delay, and that the write is about to occur // (this is slightly earlier than it ought to be, but there's no way to // atomically set this from within the implementation of write(), and doing it // after is too late for the purposes of this test). ok_for_read_to_unblock = true; // Perform the actual write. ASSERT_EQ(Exception::NONE, output_stream->write(MakeConstPtr( new ByteArray(data.data(), data.size())))); // And wait for reader_thread to finish. reader_thread.join(); } TEST(PipeTest, ConcurrentWriteAndRead) { class BaseRunnable : public Runnable { protected: explicit BaseRunnable(const std::vector<std::string>& chunks) : chunks_(chunks), prng_() {} ~BaseRunnable() override {} void randomSleep() { // Generate a random sleep between 100 and 1000 milliseconds. absl::SleepFor(absl::Milliseconds(boundedUInt32(100, 1000))); } const std::vector<std::string>& chunks_; private: // Both ends of the bounds are inclusive. std::uint32_t boundedUInt32(std::uint32_t lower_bound, std::uint32_t upper_bound) { return (prng_.nextUInt32() % (upper_bound - lower_bound + 1)) + lower_bound; } Prng prng_; }; class WriterRunnable : public BaseRunnable { public: WriterRunnable(Ptr<OutputStream> output_stream, const std::vector<std::string>& chunks) : BaseRunnable(chunks), output_stream_(output_stream) {} ~WriterRunnable() override {} void run() override { for (std::vector<std::string>::const_iterator it = chunks_.begin(); it != chunks_.end(); ++it) { const std::string& chunk = *it; randomSleep(); // Random pauses before each write. ASSERT_EQ(Exception::NONE, output_stream_->write( MakeConstPtr(new ByteArray(chunk.data(), chunk.size())))); } randomSleep(); // A random pause before closing the writer end. ASSERT_EQ(Exception::NONE, output_stream_->close()); } private: ScopedPtr<Ptr<OutputStream>> output_stream_; }; class ReaderRunnable : public BaseRunnable { public: ReaderRunnable(Ptr<InputStream> input_stream, const std::vector<std::string>& chunks) : BaseRunnable(chunks), input_stream_(input_stream) {} ~ReaderRunnable() override {} void run() override { // First, calculate what we expect to receive, in total. std::string expected_data; for (std::vector<std::string>::const_iterator it = chunks_.begin(); it != chunks_.end(); ++it) { expected_data += *it; } // Then, start actually receiving. std::string actual_data; while (true) { randomSleep(); // Random pauses before each read. ExceptionOr<ConstPtr<ByteArray>> read_data = input_stream_->read(); if (read_data.ok()) { ScopedPtr<ConstPtr<ByteArray>> scoped_read_data(read_data.result()); if (scoped_read_data.isNull()) { break; // Normal exit from the read loop. } actual_data += std::string(scoped_read_data->getData(), scoped_read_data->size()); } else { break; // Erroneous exit from the read loop. } } // And once we're done, check that we got everything we expected. ASSERT_EQ(expected_data, actual_data); } private: ScopedPtr<Ptr<InputStream>> input_stream_; }; auto pipe = MakeRefCountedPtr(new SamplePipe()); std::vector<std::string> chunks; chunks.push_back("ABCD"); chunks.push_back("EFGH"); chunks.push_back("IJKL"); Thread writer_thread; Thread reader_thread; writer_thread.start(MakePtr( new WriterRunnable(SamplePipe::createOutputStream(pipe), chunks))); reader_thread.start( MakePtr(new ReaderRunnable(SamplePipe::createInputStream(pipe), chunks))); writer_thread.join(); reader_thread.join(); } } // namespace } // namespace nearby } // namespace location
35.099515
80
0.687504
jdapena
4052f94ed4582727334e91367fc20b8af62e8d34
4,958
cc
C++
wrspice/src/misc/time.cc
bernardventer/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
3
2020-01-26T14:18:52.000Z
2020-12-09T20:07:22.000Z
wrspice/src/misc/time.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
null
null
null
wrspice/src/misc/time.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
2
2020-01-26T14:19:02.000Z
2021-08-14T16:33:28.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool * * * *========================================================================* $Id:$ *========================================================================*/ /*************************************************************************** JSPICE3 adaptation of Spice3e2 - Copyright (c) Stephen R. Whiteley 1992 Copyright 1990 Regents of the University of California. All rights reserved. Authors: UCB CAD Group 1992 Stephen R. Whiteley ****************************************************************************/ // // Date and time utility functions // #include "config.h" #include "misc.h" #include <sys/types.h> #include <sys/time.h> #include <time.h> #ifdef HAVE_FTIME #include <sys/timeb.h> #endif // Return the date. Return value is static data. // char * datestring() { #ifdef HAVE_GETTIMEOFDAY struct timeval tv; gettimeofday(&tv, 0); struct tm *tp = localtime((time_t *) &tv.tv_sec); char *ap = asctime(tp); #else time_t tloc; time(&tloc); struct tm *tp = localtime(&tloc); char *ap = asctime(tp); #endif static char tbuf[40]; strcpy(tbuf,ap); int i = strlen(tbuf); tbuf[i - 1] = '\0'; return (tbuf); } // Return the elapsed time in milliseconds from the first call. // unsigned long millisec() { static long long init_time; unsigned long elapsed = 0; #ifdef HAVE_GETTIMEOFDAY struct timeval tv; gettimeofday(&tv, 0); if (!init_time) init_time = ((long long)tv.tv_sec)*1000 + tv.tv_usec/1000; else elapsed = ((long long)tv.tv_sec)*1000 + tv.tv_usec/1000 - init_time; #else #ifdef HAVE_FTIME struct timeb tb; ftime(&tb); if (!init_time) init_time = ((long long)tb.time)*1000 + tb.millitm; else elapsed = ((long long)tb.time)*1000 + tb.millitm - init_time; #else NO TIMER PACKAGE #endif #endif return (elapsed); } // How many seconds have elapsed since epoch. // double seconds() { #ifdef HAVE_GETTIMEOFDAY struct timeval tv; gettimeofday(&tv, 0); return (tv.tv_sec + tv.tv_usec/1000000.0); #else #ifdef HAVE_FTIME struct timeb timenow; ftime(&timenow); return (timenow.time + timenow.millitm/1000.0); #else // don't know how to do this in general. return (-1.0); // Obvious error condition #endif #endif }
36.189781
77
0.488302
bernardventer
40574854a6ebfc44d7e87b5865e88e126d5d426d
9,138
cpp
C++
src/hardware/Timer.cpp
teknoman117/ts-3100-kvm-emulator
782c9440e9d40e536b8fc4c9b017ddd1ddea727f
[ "BSD-3-Clause" ]
1
2020-05-07T19:28:47.000Z
2020-05-07T19:28:47.000Z
src/hardware/Timer.cpp
teknoman117/ts-3100-kvm-emulator
782c9440e9d40e536b8fc4c9b017ddd1ddea727f
[ "BSD-3-Clause" ]
null
null
null
src/hardware/Timer.cpp
teknoman117/ts-3100-kvm-emulator
782c9440e9d40e536b8fc4c9b017ddd1ddea727f
[ "BSD-3-Clause" ]
null
null
null
#include "Timer.hpp" #include <cstdio> #include <cstring> #include <cassert> ProgrammableIntervalTimer::ProgrammableIntervalTimer() : timerPrescaler(2), state{} { // initialize the last updated timer auto now = std::chrono::high_resolution_clock::now(); state[0].lastRecord = now; state[1].lastRecord = now; state[2].lastRecord = now; state[0].waitingForLoad = true; state[1].waitingForLoad = true; state[2].waitingForLoad = true; state[0].accessMode = AccessMode::LowByteHighByte; state[1].accessMode = AccessMode::LowByteHighByte; state[2].accessMode = AccessMode::LowByteHighByte; } ProgrammableIntervalTimer::~ProgrammableIntervalTimer() {} // prescaler register uses "divisor - 2", we store the adjusted one void ProgrammableIntervalTimer::setPrescaler(uint16_t prescaler) { resolveTimers(); timerPrescaler = prescaler; } void ProgrammableIntervalTimer::writeCommand(ChannelCommand command) { resolveTimers(); if (command.standard.channel == 3) { // READBACK COMMAND for (int i = 0; i < 3; i++) { // skip channel if not selected if ((i == 0 && !command.readback.readChannel0) || (i == 1 && !command.readback.readChannel1) || (i == 2 && !command.readback.readChannel2)) continue; // setup byte select state machine if (!command.readback.latchStatus) { state[i].accessByte = ByteSelect::StatusByte; } else { state[i].accessByte = (state[i].accessMode == AccessMode::HighByteOnly) ? ByteSelect::HighByte : ByteSelect::LowByte; } // latch value if requested if (!command.readback.latchCount) { state[i].latch = state[i].value; state[i].latched = true; } } } else if (command.standard.accessMode == AccessMode::LatchCountValue) { // COUNTER LATCH COMMAND state[command.standard.channel].latch = state[command.standard.channel].value; state[command.standard.channel].latched = true; } else { // CONFIGURE TIMER COMMAND state[command.standard.channel].accessMode = command.standard.accessMode; state[command.standard.channel].operatingMode = command.standard.operatingMode; state[command.standard.channel].numberFormat = command.standard.numberFormat; // setup timer to be reset (timer is paused until load, waits for one virtual timer clock) state[command.standard.channel].waitingForLoad = true; switch (command.standard.accessMode) { // reset the access byte state machine case AccessMode::LowByteHighByte: case AccessMode::LowByteOnly: state[command.standard.channel].accessByte = ByteSelect::LowByte; state[command.standard.channel].writeByte = ByteSelect::LowByte; break; case AccessMode::HighByteOnly: state[command.standard.channel].accessByte = ByteSelect::HighByte; state[command.standard.channel].writeByte = ByteSelect::HighByte; break; } } } void ProgrammableIntervalTimer::writeRegister(uint8_t timer, uint8_t value) { assert(timer < 3); auto& selectedState = state[timer]; // setup the reload value selectedState.pendingLoad = true; uint16_t currentReload = selectedState.reload; switch (selectedState.writeByte) { case ByteSelect::LowByte: if (selectedState.numberFormat == NumberFormat::Binary) { selectedState.reload = (currentReload & 0xFF00) | (uint16_t) value; } else { selectedState.reload = (currentReload - (currentReload % 100)) + value; } if (selectedState.accessMode == AccessMode::LowByteHighByte) { // there's another byte in set reload operation selectedState.writeByte = ByteSelect::HighByte; } else { // final byte in set reload operation if (selectedState.waitingForLoad) { selectedState.waitingForLoad = false; selectedState.pendingLoad = false; selectedState.value = selectedState.reload; selectedState.lastRecord = std::chrono::high_resolution_clock::now(); } } break; case ByteSelect::HighByte: if (selectedState.numberFormat == NumberFormat::Binary) { selectedState.reload = (currentReload & 0x00FF) | ((uint16_t) value << 8); } else { selectedState.reload = (100 * (uint16_t) value) + (currentReload % 100); } if (selectedState.accessMode == AccessMode::LowByteHighByte) { // reset to low byte if we use a two byte reload operation selectedState.writeByte = ByteSelect::LowByte; } // always the final byte in set reload operation if (selectedState.waitingForLoad) { selectedState.waitingForLoad = false; selectedState.pendingLoad = false; selectedState.value = selectedState.reload; selectedState.lastRecord = std::chrono::high_resolution_clock::now(); } break; } } uint8_t ProgrammableIntervalTimer::readRegister(uint8_t timer) { assert(timer < 3); auto& selectedState = state[timer]; uint16_t value = selectedState.latched ? selectedState.latch : selectedState.value; ReadBackCommandResult ret{}; // resolve the result resolveTimers(); switch (selectedState.accessByte) { case ByteSelect::LowByte: if (selectedState.numberFormat == NumberFormat::Binary) { ret.value = value & 0x00ff; } else { // BCD format ret.value = value % 100; } break; case ByteSelect::HighByte: if (selectedState.numberFormat == NumberFormat::Binary) { ret.value = (value >> 8) & 0x00ff; } else { // BCD format ret.value = value / 100; } break; case ByteSelect::StatusByte: ret.numberFormat = selectedState.numberFormat; ret.operatingMode = selectedState.operatingMode; ret.accessMode = selectedState.accessMode; ret.pendingLoad = selectedState.pendingLoad || selectedState.waitingForLoad; ret.outputState = selectedState.outputState; break; } // figure out the next byte to access switch (selectedState.accessByte) { case ByteSelect::LowByte: if (selectedState.accessMode == AccessMode::LowByteOnly) { selectedState.latched = false; } else { selectedState.accessByte = ByteSelect::HighByte; } break; case ByteSelect::HighByte: // high byte is always the last in the read state machine selectedState.latched = false; if (selectedState.accessMode != AccessMode::HighByteOnly) { selectedState.accessByte = ByteSelect::LowByte; } break; case ByteSelect::StatusByte: if (selectedState.accessMode == AccessMode::HighByteOnly) { // high byte only is the only "" selectedState.accessByte = ByteSelect::HighByte; } else { selectedState.accessByte = ByteSelect::LowByte; } break; } return ret.value; } // resolve the state of the timers void ProgrammableIntervalTimer::resolveTimers() { auto now = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 3; i++) { // no operation if timer is paused if (state[i].waitingForLoad) continue; // get elapsed ticks auto elapsed = now - state[i].lastRecord; state[i].lastRecord = now; uint64_t ticks = elapsed.count() / (SourceClockPeriod * timerPrescaler); // did timer overflow? if (ticks > state[i].value) { ticks -= state[i].value; ticks %= (state[i].reload + 1); state[i].value = state[i].reload - ticks; state[i].pendingLoad = false; } else { state[i].value -= ticks; } // output value //printf("timer %d value: %u\n", i, state[i].value); } } // DevicePio 8 bit interface void ProgrammableIntervalTimer::iowrite8(uint16_t address, uint8_t data) { if ((address & 0x3) == 0x03) { writeCommand(ChannelCommand{ .value = data }); } else { writeRegister(address & 0x3, data); } } uint8_t ProgrammableIntervalTimer::ioread8(uint16_t address) { if ((address & 0x3) != 0x03) { return readRegister(address & 0x3); } return 0; }
38.394958
98
0.588094
teknoman117
405784a7e205a322d0311e7a3c78a081435d385d
16,808
cpp
C++
editor/editor_plugin.cpp
27thLiz/godo
0029440955f6d500a0c97bf7348a7b5353db0cea
[ "CC-BY-3.0", "MIT" ]
2
2021-11-08T02:48:48.000Z
2021-11-08T09:40:55.000Z
editor/editor_plugin.cpp
27thLiz/godot
0029440955f6d500a0c97bf7348a7b5353db0cea
[ "CC-BY-3.0", "MIT" ]
2
2015-12-08T14:13:40.000Z
2016-05-27T20:16:07.000Z
editor/editor_plugin.cpp
Hinsbart/godot
0029440955f6d500a0c97bf7348a7b5353db0cea
[ "CC-BY-3.0", "MIT" ]
null
null
null
/*************************************************************************/ /* editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "editor_plugin.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor_resource_preview.h" #include "plugins/canvas_item_editor_plugin.h" #include "plugins/spatial_editor_plugin.h" #include "scene/3d/camera.h" #include "scene/gui/popup_menu.h" void EditorPlugin::add_custom_type(const String &p_type, const String &p_base, const Ref<Script> &p_script, const Ref<Texture> &p_icon) { EditorNode::get_editor_data().add_custom_type(p_type, p_base, p_script, p_icon); } void EditorPlugin::remove_custom_type(const String &p_type) { EditorNode::get_editor_data().remove_custom_type(p_type); } ToolButton *EditorPlugin::add_control_to_bottom_panel(Control *p_control, const String &p_title) { return EditorNode::get_singleton()->add_bottom_panel_item(p_title, p_control); } void EditorPlugin::add_control_to_dock(DockSlot p_slot, Control *p_control) { ERR_FAIL_NULL(p_control); EditorNode::get_singleton()->add_control_to_dock(EditorNode::DockSlot(p_slot), p_control); } void EditorPlugin::remove_control_from_docks(Control *p_control) { ERR_FAIL_NULL(p_control); EditorNode::get_singleton()->remove_control_from_dock(p_control); } void EditorPlugin::remove_control_from_bottom_panel(Control *p_control) { ERR_FAIL_NULL(p_control); EditorNode::get_singleton()->remove_bottom_panel_item(p_control); } Control *EditorPlugin::get_editor_viewport() { return EditorNode::get_singleton()->get_viewport(); } void EditorPlugin::edit_resource(const Ref<Resource> &p_resource) { EditorNode::get_singleton()->edit_resource(p_resource); } void EditorPlugin::add_control_to_container(CustomControlContainer p_location, Control *p_control) { switch (p_location) { case CONTAINER_TOOLBAR: { EditorNode::get_menu_hb()->add_child(p_control); } break; case CONTAINER_SPATIAL_EDITOR_MENU: { SpatialEditor::get_singleton()->add_control_to_menu_panel(p_control); } break; case CONTAINER_SPATIAL_EDITOR_SIDE: { SpatialEditor::get_singleton()->get_palette_split()->add_child(p_control); SpatialEditor::get_singleton()->get_palette_split()->move_child(p_control, 0); } break; case CONTAINER_SPATIAL_EDITOR_BOTTOM: { SpatialEditor::get_singleton()->get_shader_split()->add_child(p_control); } break; case CONTAINER_CANVAS_EDITOR_MENU: { CanvasItemEditor::get_singleton()->add_control_to_menu_panel(p_control); } break; case CONTAINER_CANVAS_EDITOR_SIDE: { CanvasItemEditor::get_singleton()->get_palette_split()->add_child(p_control); CanvasItemEditor::get_singleton()->get_palette_split()->move_child(p_control, 0); } break; case CONTAINER_CANVAS_EDITOR_BOTTOM: { CanvasItemEditor::get_singleton()->get_bottom_split()->add_child(p_control); } break; case CONTAINER_PROPERTY_EDITOR_BOTTOM: { EditorNode::get_singleton()->get_property_editor_vb()->add_child(p_control); } break; } } void EditorPlugin::add_tool_menu_item(const String &p_name, Object *p_handler, const String &p_callback, const Variant &p_ud) { //EditorNode::get_singleton()->add_tool_menu_item(p_name, p_handler, p_callback, p_ud); } void EditorPlugin::add_tool_submenu_item(const String &p_name, Object *p_submenu) { ERR_FAIL_NULL(p_submenu); PopupMenu *submenu = p_submenu->cast_to<PopupMenu>(); ERR_FAIL_NULL(submenu); //EditorNode::get_singleton()->add_tool_submenu_item(p_name, submenu); } void EditorPlugin::remove_tool_menu_item(const String &p_name) { //EditorNode::get_singleton()->remove_tool_menu_item(p_name); } Ref<SpatialEditorGizmo> EditorPlugin::create_spatial_gizmo(Spatial *p_spatial) { //?? if (get_script_instance() && get_script_instance()->has_method("create_spatial_gizmo")) { return get_script_instance()->call("create_spatial_gizmo", p_spatial); } return Ref<SpatialEditorGizmo>(); } bool EditorPlugin::forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { if (get_script_instance() && get_script_instance()->has_method("forward_canvas_gui_input")) { return get_script_instance()->call("forward_canvas_gui_input", p_canvas_xform, p_event); } return false; } void EditorPlugin::forward_draw_over_canvas(const Transform2D &p_canvas_xform, Control *p_canvas) { if (get_script_instance() && get_script_instance()->has_method("forward_draw_over_canvas")) { get_script_instance()->call("forward_draw_over_canvas", p_canvas_xform, p_canvas); } } void EditorPlugin::update_canvas() { CanvasItemEditor::get_singleton()->get_viewport_control()->update(); } bool EditorPlugin::forward_spatial_gui_input(Camera *p_camera, const InputEvent &p_event) { if (get_script_instance() && get_script_instance()->has_method("forward_spatial_gui_input")) { return get_script_instance()->call("forward_spatial_gui_input", p_camera, p_event); } return false; } String EditorPlugin::get_name() const { if (get_script_instance() && get_script_instance()->has_method("get_name")) { return get_script_instance()->call("get_name"); } return String(); } bool EditorPlugin::has_main_screen() const { if (get_script_instance() && get_script_instance()->has_method("has_main_screen")) { return get_script_instance()->call("has_main_screen"); } return false; } void EditorPlugin::make_visible(bool p_visible) { if (get_script_instance() && get_script_instance()->has_method("make_visible")) { get_script_instance()->call("make_visible", p_visible); } } void EditorPlugin::edit(Object *p_object) { if (get_script_instance() && get_script_instance()->has_method("edit")) { get_script_instance()->call("edit", p_object); } } bool EditorPlugin::handles(Object *p_object) const { if (get_script_instance() && get_script_instance()->has_method("handles")) { return get_script_instance()->call("handles", p_object); } return false; } Dictionary EditorPlugin::get_state() const { if (get_script_instance() && get_script_instance()->has_method("get_state")) { return get_script_instance()->call("get_state"); } return Dictionary(); } void EditorPlugin::set_state(const Dictionary &p_state) { if (get_script_instance() && get_script_instance()->has_method("set_state")) { get_script_instance()->call("set_state", p_state); } } void EditorPlugin::clear() { if (get_script_instance() && get_script_instance()->has_method("clear")) { get_script_instance()->call("clear"); } } // if editor references external resources/scenes, save them void EditorPlugin::save_external_data() { if (get_script_instance() && get_script_instance()->has_method("save_external_data")) { get_script_instance()->call("save_external_data"); } } // if changes are pending in editor, apply them void EditorPlugin::apply_changes() { if (get_script_instance() && get_script_instance()->has_method("apply_changes")) { get_script_instance()->call("apply_changes"); } } void EditorPlugin::get_breakpoints(List<String> *p_breakpoints) { if (get_script_instance() && get_script_instance()->has_method("get_breakpoints")) { PoolStringArray arr = get_script_instance()->call("get_breakpoints"); for (int i = 0; i < arr.size(); i++) p_breakpoints->push_back(arr[i]); } } bool EditorPlugin::get_remove_list(List<Node *> *p_list) { return false; } void EditorPlugin::restore_global_state() {} void EditorPlugin::save_global_state() {} void EditorPlugin::set_window_layout(Ref<ConfigFile> p_layout) { if (get_script_instance() && get_script_instance()->has_method("set_window_layout")) { get_script_instance()->call("set_window_layout", p_layout); } } void EditorPlugin::get_window_layout(Ref<ConfigFile> p_layout) { if (get_script_instance() && get_script_instance()->has_method("get_window_layout")) { get_script_instance()->call("get_window_layout", p_layout); } } void EditorPlugin::queue_save_layout() const { EditorNode::get_singleton()->save_layout(); } EditorSelection *EditorPlugin::get_selection() { return EditorNode::get_singleton()->get_editor_selection(); } EditorSettings *EditorPlugin::get_editor_settings() { return EditorSettings::get_singleton(); } EditorResourcePreview *EditorPlugin::get_resource_previewer() { return EditorResourcePreview::get_singleton(); } Control *EditorPlugin::get_base_control() { return EditorNode::get_singleton()->get_gui_base(); } void EditorPlugin::make_bottom_panel_item_visible(Control *p_item) { EditorNode::get_singleton()->make_bottom_panel_item_visible(p_item); } void EditorPlugin::hide_bottom_panel() { EditorNode::get_singleton()->hide_bottom_panel(); } void EditorPlugin::inspect_object(Object *p_obj, const String &p_for_property) { EditorNode::get_singleton()->push_item(p_obj, p_for_property); } EditorFileSystem *EditorPlugin::get_resource_file_system() { return EditorFileSystem::get_singleton(); } void EditorPlugin::_bind_methods() { ClassDB::bind_method(D_METHOD("add_control_to_container", "container", "control:Control"), &EditorPlugin::add_control_to_container); ClassDB::bind_method(D_METHOD("add_control_to_bottom_panel:ToolButton", "control:Control", "title"), &EditorPlugin::add_control_to_bottom_panel); ClassDB::bind_method(D_METHOD("add_control_to_dock", "slot", "control:Control"), &EditorPlugin::add_control_to_dock); ClassDB::bind_method(D_METHOD("remove_control_from_docks", "control:Control"), &EditorPlugin::remove_control_from_docks); ClassDB::bind_method(D_METHOD("remove_control_from_bottom_panel", "control:Control"), &EditorPlugin::remove_control_from_bottom_panel); //ClassDB::bind_method(D_METHOD("add_tool_menu_item", "name", "handler", "callback", "ud"),&EditorPlugin::add_tool_menu_item,DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("add_tool_submenu_item", "name", "submenu:PopupMenu"), &EditorPlugin::add_tool_submenu_item); //ClassDB::bind_method(D_METHOD("remove_tool_menu_item", "name"),&EditorPlugin::remove_tool_menu_item); ClassDB::bind_method(D_METHOD("add_custom_type", "type", "base", "script:Script", "icon:Texture"), &EditorPlugin::add_custom_type); ClassDB::bind_method(D_METHOD("remove_custom_type", "type"), &EditorPlugin::remove_custom_type); ClassDB::bind_method(D_METHOD("get_editor_viewport:Control"), &EditorPlugin::get_editor_viewport); ClassDB::bind_method(D_METHOD("get_resource_previewer:EditorResourcePreview"), &EditorPlugin::get_resource_previewer); ClassDB::bind_method(D_METHOD("get_resource_filesystem:EditorFileSystem"), &EditorPlugin::get_resource_file_system); ClassDB::bind_method(D_METHOD("inspect_object", "object", "for_property"), &EditorPlugin::inspect_object, DEFVAL(String())); ClassDB::bind_method(D_METHOD("update_canvas"), &EditorPlugin::update_canvas); ClassDB::bind_method(D_METHOD("make_bottom_panel_item_visible", "item:Control"), &EditorPlugin::make_bottom_panel_item_visible); ClassDB::bind_method(D_METHOD("hide_bottom_panel"), &EditorPlugin::hide_bottom_panel); ClassDB::bind_method(D_METHOD("get_base_control:Control"), &EditorPlugin::get_base_control); ClassDB::bind_method(D_METHOD("get_undo_redo:UndoRedo"), &EditorPlugin::_get_undo_redo); ClassDB::bind_method(D_METHOD("get_selection:EditorSelection"), &EditorPlugin::get_selection); ClassDB::bind_method(D_METHOD("get_editor_settings:EditorSettings"), &EditorPlugin::get_editor_settings); ClassDB::bind_method(D_METHOD("queue_save_layout"), &EditorPlugin::queue_save_layout); ClassDB::bind_method(D_METHOD("edit_resource"), &EditorPlugin::edit_resource); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "forward_canvas_gui_input", PropertyInfo(Variant::TRANSFORM2D, "canvas_xform"), PropertyInfo(Variant::INPUT_EVENT, "event"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo("forward_draw_over_canvas", PropertyInfo(Variant::TRANSFORM2D, "canvas_xform"), PropertyInfo(Variant::OBJECT, "canvas:Control"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "forward_spatial_gui_input", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::INPUT_EVENT, "event"))); MethodInfo gizmo = MethodInfo(Variant::OBJECT, "create_spatial_gizmo", PropertyInfo(Variant::OBJECT, "for_spatial:Spatial")); gizmo.return_val.hint = PROPERTY_HINT_RESOURCE_TYPE; gizmo.return_val.hint_string = "EditorSpatialGizmo"; ClassDB::add_virtual_method(get_class_static(), gizmo); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_name")); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "has_main_screen")); ClassDB::add_virtual_method(get_class_static(), MethodInfo("make_visible", PropertyInfo(Variant::BOOL, "visible"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo("edit", PropertyInfo(Variant::OBJECT, "object"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles", PropertyInfo(Variant::OBJECT, "object"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::DICTIONARY, "get_state")); ClassDB::add_virtual_method(get_class_static(), MethodInfo("set_state", PropertyInfo(Variant::DICTIONARY, "state"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo("clear")); ClassDB::add_virtual_method(get_class_static(), MethodInfo("save_external_data")); ClassDB::add_virtual_method(get_class_static(), MethodInfo("apply_changes")); ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_breakpoints")); ClassDB::add_virtual_method(get_class_static(), MethodInfo("set_window_layout", PropertyInfo(Variant::OBJECT, "layout", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile"))); ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_window_layout", PropertyInfo(Variant::OBJECT, "layout", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile"))); BIND_CONSTANT(CONTAINER_TOOLBAR); BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_MENU); BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_SIDE); BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_BOTTOM); BIND_CONSTANT(CONTAINER_CANVAS_EDITOR_MENU); BIND_CONSTANT(CONTAINER_CANVAS_EDITOR_SIDE); BIND_CONSTANT(CONTAINER_PROPERTY_EDITOR_BOTTOM); BIND_CONSTANT(DOCK_SLOT_LEFT_UL); BIND_CONSTANT(DOCK_SLOT_LEFT_BL); BIND_CONSTANT(DOCK_SLOT_LEFT_UR); BIND_CONSTANT(DOCK_SLOT_LEFT_BR); BIND_CONSTANT(DOCK_SLOT_RIGHT_UL); BIND_CONSTANT(DOCK_SLOT_RIGHT_BL); BIND_CONSTANT(DOCK_SLOT_RIGHT_UR); BIND_CONSTANT(DOCK_SLOT_RIGHT_BR); BIND_CONSTANT(DOCK_SLOT_MAX); } EditorPlugin::EditorPlugin() { undo_redo = NULL; } EditorPlugin::~EditorPlugin() { } EditorPluginCreateFunc EditorPlugins::creation_funcs[MAX_CREATE_FUNCS]; int EditorPlugins::creation_func_count = 0;
40.599034
230
0.740778
27thLiz
4066e4beafcffe053e6c6147f0837c9c353eb0bd
17,646
cpp
C++
src/stage/credits-stage.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
2
2019-02-28T00:28:08.000Z
2019-10-20T14:39:48.000Z
src/stage/credits-stage.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
src/stage/credits-stage.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ---------------------------------------------------------------------------- // "THE BEER-WARE LICENSE" (Revision 42): // <ztn@zurreal.com> 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. Ziesche Til Newman // ---------------------------------------------------------------------------- // // credits-stage.cpp // #include "credits-stage.hpp" #include "gui/gui-images.hpp" #include "gui/menu-image-enum.hpp" #include "gui/music-enum.hpp" #include "gui/sound-manager.hpp" #include "gui/text-info.hpp" #include "gui/text-region.hpp" #include "misc/config-file.hpp" #include "misc/log-macros.hpp" #include "misc/real.hpp" #include "sfutil/display.hpp" #include "sfutil/fitting.hpp" #include "sfutil/position.hpp" #include "sfutil/primitives.hpp" #include <SFML/Graphics/RenderTarget.hpp> namespace heroespath { namespace stage { const float CreditsStage::DEFAULT_SCROLL_SPEED_(45.0f); const float CreditsStage::SCROLL_SPEED_MULT_(100.0f); const float CreditsStage::SCROLL_SPEED_MAX_(600.0f); CreditsStage::CreditsStage() : StageBase( "Credits", { gui::GuiFont::Default, gui::GuiFont::DefaultBoldFlavor, gui::GuiFont::Number, gui::GuiFont::System, gui::GuiFont::SystemCondensed, gui::GuiFont::SignThinTallNarrow, gui::GuiFont::SignBoldShortWide, gui::GuiFont::Handwriting, gui::GuiFont::DialogModern, gui::GuiFont::DialogMedieval, }) , stageTitle_(gui::MenuImage::Title) , boxUPtr_() , boxBorderUPtr_() , creditUVec_() , scrollSpeed_(DEFAULT_SCROLL_SPEED_) , isKeyHeldArrowUp_(false) , isKeyHeldArrowDown_(false) , keyPressClock_() , blackRectUpper_() , blackRectLower_() { gui::SoundManager::Instance()->MusicStart(gui::music::Credits); } CreditsStage::~CreditsStage() { gui::SoundManager::Instance()->MusicStop(gui::music::Credits); StageBase::ClearAllEntities(); } void CreditsStage::Setup() { const auto TITLE_VERT_PAD { sfutil::ScreenRatioToPixelsVert(0.022f) }; const auto CREDITS_BOX_REGION = [&]() { sf::FloatRect rect; rect.width = sfutil::ScreenRatioToPixelsHoriz(0.4f); rect.left = (StageRegion().width * 0.5f) - (rect.width * 0.5f); rect.top = sfutil::Bottom(stageTitle_.Region()) + TITLE_VERT_PAD; rect.height = (StageRegion().height - rect.top) - (TITLE_VERT_PAD * 2.0f); return rect; }(); // rune background gui::BoxEntityInfo boxInfo; boxInfo.SetupImage( gui::CachedTexture( "media-image-background-tile-runes", gui::ImageOpt::Default | gui::ImageOpt::Repeated), sfutil::ScreenRatioToPixelsHoriz(0.15f)); boxInfo.SetupColor( sf::Color::Transparent, sf::Color(0, 0, 0, 200), gui::Side::None, gui::Corner::TopLeft | gui::Corner::BottomRight); boxInfo.focus_colors = gui::FocusColors( sfutil::color::GrayLight, sf::Color::Transparent, sfutil::color::GrayLight, sf::Color::Transparent); boxUPtr_ = std::make_unique<gui::BoxEntity>("Credits", CREDITS_BOX_REGION, boxInfo); gui::BoxEntityInfo boxBorderInfo; boxBorderInfo.SetupBorder(true); boxBorderUPtr_ = std::make_unique<gui::BoxEntity>("CreditsBorder", CREDITS_BOX_REGION, boxBorderInfo); // draw solid black rectangles above and below the credits box to hide the // scrolling credits when they move outside the box blackRectUpper_.Setup( sf::FloatRect(0.0f, 0.0f, StageRegion().width, boxUPtr_->OuterRegion().top), sf::Color::Black); blackRectLower_.Setup( sf::FloatRect( 0.0f, sfutil::Bottom(boxUPtr_->OuterRegion()), StageRegion().width, StageRegion().height), sf::Color::Black); const auto CREDIT_BOX_INNER_PAD { sfutil::ScreenRatioToPixelsHoriz(0.0333f) }; const auto CREDIT_MAX_WIDTH { CREDITS_BOX_REGION.width - (CREDIT_BOX_INNER_PAD * 2.0f) }; creditUVec_.emplace_back( std::make_unique<Credit>(CREDIT_MAX_WIDTH, "Game Design", "Ziesche Til Newman")); creditUVec_.emplace_back( std::make_unique<Credit>(CREDIT_MAX_WIDTH, "Programming", "Ziesche Til Newman")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "", "Special thanks to Laurent Gomila for the Simple Fast Multimedia Library. This " "project came together quickly thanks to the power and simplicity of this library." "\n\nwww.sfml-dev.org\nwww.opensource.org/licenses/zlib\n\n", "media-image-misc-logos-sfml", sfutil::ScreenRatioToPixelsHoriz(0.146f))); creditUVec_.emplace_back( std::make_unique<Credit>(CREDIT_MAX_WIDTH, "Art", "Ziesche Til Newman")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Rune Symbols and Other Designs", "Angela Diegel")); creditUVec_.emplace_back(std::make_unique<Credit>(CREDIT_MAX_WIDTH, "Art", "Nel Carlson")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Terrain Art", "Daniel Cook\nA beautiful (and free!) (for any use) set of " "tiles.\nwww.lostgarden.com", "media-image-misc-logos-terrain", sfutil::ScreenRatioToPixelsHoriz(0.117f))); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Map Editing Software", "Thorbjorn Lindeijer for Tiled\nAn incredible free mapping " "utility.\nwww.mapeditor.org", "media-image-misc-logos-tiled", sfutil::ScreenRatioToPixelsHoriz(0.15f))); const auto SOUND_IMAGE_WIDTH { sfutil::ScreenRatioToPixelsHoriz(0.05f) }; creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "\"Battle\"\n\"Castlecall\"\n\"Deal with the Devil\"\n\"Menu Loop\"\n\"Mini Epic " "Theme\"\n\"Runaway\"\n\"Steeps of Destiny\"\n\"Treasures of Ancient " "Dungeon\"\n\"We " "Are So Close\"", "Alexandr Zhelanov\nwww.soundcloud.com/alexandr-zhelanov\n\nUnder the Attribution " "3.0 " "Unported License\nwwww.creativecommons.org/licenses/by/3.0\nThe original music " "was " "trimmed and normalized.", "media-image-misc-logos-sound", SOUND_IMAGE_WIDTH)); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "\"Old Crypt\"\n\"Dramatic Event 2\"\n\"Radakan Menu\"", "Janne Hanhisuanto for Radakan\nUnder the Attribution-ShareAlike Unported 3.0 " "License\nwww.creativecommons.org/licenses/by-sa/3.0\nThe original music was " "trimmed " "and normalized.", "media-image-misc-logos-sound", SOUND_IMAGE_WIDTH)); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "\"Omens\"\n\"The Plot Thickens\"", "Eliot Corley from Chaos is Harmony\nUnder the Attribution Unported 3.0 " "License\nwww.creativecommons.org/licenses/by/3.0\nThe original music was trimmed " "and " "normalized.", "media-image-misc-logos-sound", SOUND_IMAGE_WIDTH)); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "\"Something is Near\"\n\"Intro of Dragons\"\n\"Small Epic\"\n\"PYC\"", "Music by Marcelo " "Fernandez\nwww.marcelofernandezmusic.com\nwww.soundcloud.com/" "marcelofernandezmusic\nFound at www.opengameart.org/users/marcelofg55\nUnder the " "Attribution Unported 4.0 License\nwww.creativecommons.org/licenses/by/4.0\nThe " "original music was trimmed and normalized.", "media-image-misc-logos-sound", SOUND_IMAGE_WIDTH)); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Neo Euler\"", gui::GuiFont::Default, "Hermann Zapf\nCopyright (c) 2009, 2010 Khaled Hosny\nkhaledhosny@eglug.org\nUnder " "the " "SIL Open Font " "License v1.1\nwww.scripts.sil.org/OFL\nFound at www.fontlibrary.org")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Modern Antiqua\"", gui::GuiFont::DefaultBoldFlavor, "Copyright (c) 2011, wmk69 (wmk69@o2.pl)\nFrom www.openfontlibrary.org\nUnder the " "SIL " "Open Font License v1.1\nwww.scripts.sil.org/OFL\nFound at www.fontlibrary.org")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Gentium Plus\"", gui::GuiFont::System, "J.Victor Gaultney\nAnnie Olsen\nIska Routamaa\nBecca " "Hirsbrunner\nCopyright (c) SIL International, " "2003-2014\nwww.scripts.sil.org/Gentium\nUnder the " "SIL Open Font License v1.1\nwww.scripts.sil.org/OFL\nFound at " "www.fontlibrary.org")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Goudy Bookletter 1911\"", gui::GuiFont::SystemCondensed, "by Barry Schwartz\nwww.crudfactory.com\nUnder the public domain (no copyright)")); /* creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Quill Sword\"", gui::GuiFont::Number, "by Daniel Zadorozny\n2015 Iconian Fonts\nwww.iconian.com\n\"free for all " "non-commercial uses\"\nThis font is e-mailware. If you like it,\nplease e-mail the " "author at iconian@aol.com.")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Queen & Country\"", gui::GuiFont::SignBoldShortWide, "by Daniel Zadorozny\n2009 Iconian Fonts\nwww.iconian.com\nThis font is e-mailware. " "If you like it,\nplease e-mail the author at iconian@aol.com.")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Valley Forge\"", gui::GuiFont::System, "by Daniel Zadorozny\n2008 Iconian Fonts\nwww.iconian.com\n\"free for all " "non-commercial uses\"\nThis font is e-mailware. If you like it,\nplease e-mail the " "author at iconian@aol.com.")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Square Antiqua\"", gui::GuiFont::DialogModern, "Copyright (c) 2011, wmk69 (wmk69@o2.pl)\nFrom www.openfontlibrary.org\nUnder the SIL " "Open Font License v1.1\nwww.scripts.sil.org/OFL\nFound at www.fontlibrary.org")); creditUVec_.emplace_back(std::make_unique<Credit>( CREDIT_MAX_WIDTH, "Font \"Mops Antiqua\"", gui::GuiFont::DialogModern, "Created by Uwe Borchert\nUnder the SIL " "Open Font License v1.1\nwww.scripts.sil.org/OFL\nFound at www.fontlibrary.org")); */ MoveCreditsToStartPos(); } void CreditsStage::UpdateTime(const float ELAPSED_TIME_SECONDS) { StageBase::UpdateTime(ELAPSED_TIME_SECONDS); UpdateCreditAnimations(ELAPSED_TIME_SECONDS); UpdateCreditPositions(ELAPSED_TIME_SECONDS); UpdateScrollSpeed(ELAPSED_TIME_SECONDS); } void CreditsStage::draw(sf::RenderTarget & target, sf::RenderStates states) const { target.draw(*boxUPtr_, states); StageBase::draw(target, states); for (const auto & CREDIT_UPTR : creditUVec_) { if (IsCreditVisible(*CREDIT_UPTR)) { target.draw(*CREDIT_UPTR, states); } } // draw solid black rectangles above and below the credits box to hide the // scrolling credits when outside the box target.draw(blackRectUpper_, states); target.draw(blackRectLower_, states); target.draw(stageTitle_, states); target.draw(*boxBorderUPtr_, states); } bool CreditsStage::KeyPress(const sf::Event::KeyEvent & KE) { keyPressClock_.restart(); if (KE.code == sf::Keyboard::Up) { isKeyHeldArrowUp_ = true; } else if (KE.code == sf::Keyboard::Down) { isKeyHeldArrowDown_ = true; } else { gui::SoundManager::Instance()->PlaySfx_Keypress(); TransitionTo(stage::Stage::Menu); } return true; } bool CreditsStage::KeyRelease(const sf::Event::KeyEvent & KE) { keyPressClock_.restart(); if (KE.code == sf::Keyboard::Up) { isKeyHeldArrowUp_ = false; return true; } else if (KE.code == sf::Keyboard::Down) { isKeyHeldArrowDown_ = false; return true; } else { return false; } } void CreditsStage::UpdateMouseDown(const sf::Vector2f &) { TransitionTo(stage::Stage::Menu); } void CreditsStage::UpdateScrollSpeed(const float ELAPSED_TIME_SECONDS) { const auto SPEED_ADJ { ( (ELAPSED_TIME_SECONDS * SCROLL_SPEED_MULT_) + std::pow((1.0f + keyPressClock_.getElapsedTime().asSeconds()), 2.35f)) }; // accelerate/decelerate when pressing/releasing the down arrow key if ((isKeyHeldArrowUp_ == false) && (isKeyHeldArrowDown_ == false) && (std::abs(scrollSpeed_ - DEFAULT_SCROLL_SPEED_) > 5.0f)) { if (scrollSpeed_ < DEFAULT_SCROLL_SPEED_) { scrollSpeed_ += SPEED_ADJ; } else { scrollSpeed_ -= SPEED_ADJ; } } else if (isKeyHeldArrowUp_) { scrollSpeed_ += SPEED_ADJ; } else if (isKeyHeldArrowDown_) { scrollSpeed_ -= SPEED_ADJ; } if (scrollSpeed_ > SCROLL_SPEED_MAX_) { scrollSpeed_ = SCROLL_SPEED_MAX_; } else if (scrollSpeed_ < -SCROLL_SPEED_MAX_) { scrollSpeed_ = -SCROLL_SPEED_MAX_; } } void CreditsStage::UpdateCreditAnimations(const float ELAPSED_TIME_SECONDS) { for (auto & creditUPtr : creditUVec_) { if (IsCreditVisible(*creditUPtr)) { creditUPtr->UpdateTime(ELAPSED_TIME_SECONDS); } } } void CreditsStage::UpdateCreditPositions(const float ELAPSED_TIME_SECONDS) { const float MOVE_AMOUNT(ELAPSED_TIME_SECONDS * scrollSpeed_); for (auto & creditUPtr : creditUVec_) { creditUPtr->Move(0.0f, -MOVE_AMOUNT); } const auto TOP_OF_FIRST_CREDIT { creditUVec_.front()->Region().top }; if (TOP_OF_FIRST_CREDIT > sfutil::DisplaySize().y) { MoveCreditsToReverseStartPos(); } else { const auto BOTTOM_OF_LAST_CREDIT { sfutil::Bottom(creditUVec_.back()->Region()) }; if (BOTTOM_OF_LAST_CREDIT < 0.0f) { MoveCreditsToStartPos(); } } } bool CreditsStage::IsCreditVisible(const Credit & CREDIT) const { return CREDIT.Region().intersects(boxUPtr_->OuterRegion()); } void CreditsStage::MoveCreditsToStartPos() { auto iter { std::begin(creditUVec_) }; const auto FIRST_CREDIT_START_POS_TOP { ( sfutil::Bottom(boxUPtr_->OuterRegion()) + sfutil::ScreenRatioToPixelsVert(0.022f)) }; (*iter)->SetVerticalPosition(FIRST_CREDIT_START_POS_TOP); const auto BETWEEN_CREDIT_SPACER { sfutil::ScreenRatioToPixelsVert(0.08f) }; while (iter != std::end(creditUVec_)) { const auto BOTTOM_OF_PREV_CREDIT { sfutil::Bottom((*iter)->Region()) }; ++iter; if (iter == std::end(creditUVec_)) { break; } else { (*iter)->SetVerticalPosition(BOTTOM_OF_PREV_CREDIT + BETWEEN_CREDIT_SPACER); } } } void CreditsStage::MoveCreditsToReverseStartPos() { const auto VERT_MOVE_OF_LAST_CREDIT_TO_SET_REVERSE_START { ( 0.0f - sfutil::Bottom(creditUVec_.back()->Region())) }; for (auto & creditUPtr : creditUVec_) { creditUPtr->Move(0.0f, VERT_MOVE_OF_LAST_CREDIT_TO_SET_REVERSE_START); } } } // namespace stage } // namespace heroespath
36.234086
99
0.590445
tilnewman
40673444d5518a8199103c2027477c5829849fd6
4,531
cpp
C++
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_core/network/juce_WebInputStream.cpp
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
10
2017-07-16T04:50:47.000Z
2022-02-14T06:10:45.000Z
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_core/network/juce_WebInputStream.cpp
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
199
2016-07-28T07:30:48.000Z
2017-10-14T06:15:40.000Z
UI/JuceLibraryCode/modules/juce_core/network/juce_WebInputStream.cpp
subutai-io/launcher
d8397995e18200b12d60781ed485af04f70bff03
[ "Apache-2.0" ]
3
2017-11-07T14:44:14.000Z
2021-03-16T02:45:57.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2016 - ROLI Ltd. Permission is granted to use this software under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license/ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ----------------------------------------------------------------------------- To release a closed-source product which uses other parts of JUCE not licensed under the ISC terms, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ WebInputStream::WebInputStream (const URL& url, const bool usePost) : pimpl (new Pimpl(*this, url, usePost)), hasCalledConnect (false) {} WebInputStream::~WebInputStream() { delete pimpl; } WebInputStream& WebInputStream::withExtraHeaders (const String& extra) { pimpl->withExtraHeaders (extra); return *this; } WebInputStream& WebInputStream::withCustomRequestCommand (const String& cmd) { pimpl->withCustomRequestCommand(cmd); return *this; } WebInputStream& WebInputStream::withConnectionTimeout (int t) { pimpl->withConnectionTimeout (t); return *this; } WebInputStream& WebInputStream::withNumRedirectsToFollow (int num) { pimpl->withNumRedirectsToFollow (num); return *this; } StringPairArray WebInputStream::getRequestHeaders() const { return pimpl->getRequestHeaders(); } StringPairArray WebInputStream::getResponseHeaders() { connect (nullptr); return pimpl->getResponseHeaders(); } bool WebInputStream::isError() const { return pimpl->isError(); } void WebInputStream::cancel() { pimpl->cancel(); } bool WebInputStream::isExhausted() { return pimpl->isExhausted(); } int64 WebInputStream::getPosition() { return pimpl->getPosition(); } int64 WebInputStream::getTotalLength() { connect (nullptr); return pimpl->getTotalLength(); } int WebInputStream::read (void* buffer, int bytes) { connect (nullptr); return pimpl->read (buffer, bytes); } bool WebInputStream::setPosition (int64 pos) { return pimpl->setPosition (pos); } int WebInputStream::getStatusCode() { connect (nullptr); return pimpl->getStatusCode(); } bool WebInputStream::connect (Listener* listener) { if (hasCalledConnect) return ! isError(); hasCalledConnect = true; return pimpl->connect (listener); } StringPairArray WebInputStream::parseHttpHeaders (const String& headerData) { StringPairArray headerPairs; StringArray headerLines = StringArray::fromLines (headerData); // ignore the first line as this is the status line for (int i = 1; i < headerLines.size(); ++i) { const String& headersEntry = headerLines[i]; if (headersEntry.isNotEmpty()) { const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false)); const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false)); const String previousValue (headerPairs [key]); headerPairs.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value)); } } return headerPairs; } void WebInputStream::createHeadersAndPostData (const URL& aURL, String& headers, MemoryBlock& data) { aURL.createHeadersAndPostData (headers, data); }
50.344444
138
0.612889
rc-h
406910e2b30648cb4a04f6eab02eecf930109ab6
1,950
cpp
C++
test/unit/readpipe/read_transformer_tests.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
278
2016-10-03T16:30:49.000Z
2022-03-25T05:59:32.000Z
test/unit/readpipe/read_transformer_tests.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
229
2016-10-13T14:07:35.000Z
2022-03-19T18:59:58.000Z
test/unit/readpipe/read_transformer_tests.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
37
2016-10-28T22:47:54.000Z
2022-03-20T07:28:43.000Z
// Copyright (c) 2017 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include <iostream> #include <vector> #include <algorithm> #include <iterator> #include "basics/genomic_region.hpp" #include "io/read/read_manager.hpp" #include "readpipe/transformers/read_transformer.hpp" #include "readpipe/transformers/read_transform.hpp" #include "test_common.hpp" using std::cout; using std::endl; BOOST_AUTO_TEST_SUITE(Components) //BOOST_AUTO_TEST_CASE(read_transform_test) //{ // BOOST_REQUIRE(test_file_exists(NA12878_low_coverage)); // // ReadManager read_manager {NA12878_low_coverage}; // // const auto sample = read_manager.samples().front(); // // GenomicRegion region1 {"10", 1'000'000, 1'000'100}; // // auto reads = read_manager.fetch_reads(sample, region1); // // BOOST_REQUIRE(std::is_sorted(std::cbegin(reads), std::cend(reads))); // BOOST_REQUIRE(reads.size() == 7); // // const auto& a_read = reads[0]; // // BOOST_CHECK(is_back_soft_clipped(a_read.cigar_string())); // // octopus::ReadTransform transformer {}; // transformer.register_transform(octopus::ReadTransforms::trim_adapters()); // transformer.register_transform(octopus::ReadTransforms::trim_soft_clipped()); // // transform_reads(reads, transformer); // // BOOST_CHECK(std::all_of(a_read.qualities().rbegin(), a_read.qualities().rbegin() + 13, // [] (const auto q) { return q == 0; })); // // GenomicRegion region2 {"3", 100'000, 100'100}; // // reads = read_manager.fetch_reads(sample, region2); // // BOOST_REQUIRE(std::is_sorted(std::cbegin(reads), std::cend(reads))); // BOOST_REQUIRE(reads.size() == 21); // // transform_reads(reads, transformer); // // // TODO //} BOOST_AUTO_TEST_SUITE_END()
30
96
0.673333
gunjanbaid
406fdd256e7e0f2849190c80af43b9228d510bf3
8,910
cpp
C++
Tools/sitl_gazebo/src/gazebo_uuv_plugin.cpp
666cats/Px4forVTOL
65965fb5eda3b6bbfab0daae8a1dc9bbbe1407d5
[ "BSD-3-Clause" ]
10
2021-03-15T03:58:06.000Z
2021-12-30T15:33:38.000Z
Tools/sitl_gazebo/src/gazebo_uuv_plugin.cpp
666cats/Px4forVTOL
65965fb5eda3b6bbfab0daae8a1dc9bbbe1407d5
[ "BSD-3-Clause" ]
4
2021-05-03T16:58:53.000Z
2021-12-21T21:01:02.000Z
Tools/sitl_gazebo/src/gazebo_uuv_plugin.cpp
666cats/Px4forVTOL
65965fb5eda3b6bbfab0daae8a1dc9bbbe1407d5
[ "BSD-3-Clause" ]
9
2021-04-28T15:26:34.000Z
2021-12-21T20:41:30.000Z
/* * Copyright 2020 Daniel Duecker, TU Hamburg, Germany * Copyright 2020 Philipp Hastedt, TU Hamburg, Germany * based on prior work by Nils Rottmann and Austin Buchan * * 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. */ /** * This plugin is an extension with regard to hydrodynamic effects. * It * - computes the hydrodynamic effects (according to FOSSEN 2011 - Handbook of Marine Craft Hydrodynamics and Motion Control) * - applies the Hydro effects as forces/moments and are than applied to the vehicle * - computes the forces/moments based on the motor commands */ #include "gazebo_uuv_plugin.h" #include <ignition/math.hh> #include <iostream> #include <iomanip> namespace gazebo { GazeboUUVPlugin::~GazeboUUVPlugin() { updateConnection_->~Connection(); } void GazeboUUVPlugin::InitializeParams() {} void GazeboUUVPlugin::Publish() {} void GazeboUUVPlugin::ParseBuoyancy(sdf::ElementPtr _sdf) { for (auto buoyancy_element = _sdf->GetFirstElement(); buoyancy_element != NULL; buoyancy_element = buoyancy_element->GetNextElement()) { // skip element if it is not a buoyancy-element if (buoyancy_element->GetName() != "buoyancy") { continue; } physics::LinkPtr link_ptr; std::string link_name = ""; // check if link_name is specified. Otherwise skip this buoyancy-element. if (!getSdfParam(buoyancy_element, "link_name", link_name, link_name)) { gzwarn << "Skipping buoyancy element with unspecified 'link_name' tag!\n"; continue; } link_ptr = model_->GetChildLink(link_name); // Check if link with specified name exists. Otherwise skip this // buoyancy-element. if (link_ptr == NULL) { gzerr << "Model has no link with name '" << link_name << "'!\n"; continue; } buoyancy_s buoyancy_link; buoyancy_link.model_name = model_->GetName(); buoyancy_link.link = link_ptr; buoyancy_link.buoyancy_force = ignition::math::Vector3d(0, 0, 0); buoyancy_link.cob = ignition::math::Vector3d(0, 0, 0); buoyancy_link.height_scale_limit = 0.1; double compensation = 0.0; if (buoyancy_element->HasElement("origin")) { buoyancy_link.cob = buoyancy_element->Get<ignition::math::Vector3d>("origin"); } if (buoyancy_element->HasElement("compensation")) { compensation = buoyancy_element->Get<double>("compensation"); } if (buoyancy_element->HasElement("height_scale_limit")) { buoyancy_link.height_scale_limit = std::abs(buoyancy_element->Get<double>("height_scale_limit")); } #if GAZEBO_MAJOR_VERSION >= 9 buoyancy_link.buoyancy_force = -compensation * link_ptr->GetInertial()->Mass() * model_->GetWorld()->Gravity(); #else buoyancy_link.buoyancy_force = -compensation * link_ptr->GetInertial()->GetMass() * model_->GetWorld()->Gravity(); #endif buoyancy_links_.push_back(buoyancy_link); gzmsg << "Added buoyancy element for link '" << model_->GetName() << "::" << link_name << "'.\n"; } } void GazeboUUVPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { model_ = _model; namespace_.clear(); namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>(); node_handle_ = transport::NodePtr(new transport::Node()); node_handle_->Init(namespace_); //Get links link_base_ = _sdf->GetElement("baseLinkName")->Get<std::string>(); baseLink_ = model_->GetLink(link_base_); ParseBuoyancy(_sdf); //Get parameters for added mass and damping ignition::math::Vector3d added_mass_linear(0,0,0); getSdfParam<ignition::math::Vector3d>(_sdf, "addedMassLinear", added_mass_linear, added_mass_linear); X_udot_ = added_mass_linear[0]; Y_vdot_ = added_mass_linear[1]; Z_wdot_ = added_mass_linear[2]; ignition::math::Vector3d added_mass_angular(0,0,0); getSdfParam<ignition::math::Vector3d>( _sdf, "addedMassAngular", added_mass_angular, added_mass_angular); K_pdot_ = added_mass_angular[0]; M_qdot_ = added_mass_angular[1]; N_rdot_ = added_mass_angular[2]; ignition::math::Vector3d damping_linear(0,0,0); getSdfParam<ignition::math::Vector3d>(_sdf, "dampingLinear", damping_linear, damping_linear); X_u_ = damping_linear[0]; Y_v_ = damping_linear[1]; Z_w_ = damping_linear[2]; ignition::math::Vector3d damping_angular(0,0,0); getSdfParam<ignition::math::Vector3d>(_sdf, "dampingAngular", damping_angular, damping_angular); K_p_ = damping_angular[0]; M_q_ = damping_angular[1]; N_r_ = damping_angular[2]; // Listen to the update event. This event is broadcast every // simulation iteration. updateConnection_ = event::Events::ConnectWorldUpdateBegin(boost::bind(&GazeboUUVPlugin::OnUpdate, this, _1)); } // This gets called by the world update start event. void GazeboUUVPlugin::OnUpdate(const common::UpdateInfo& _info) { ApplyBuoyancy(); UpdateForcesAndMoments(); // Hydrodynamics are computed here Publish(); } void GazeboUUVPlugin::ApplyBuoyancy() { ignition::math::Vector3d force, cob; for (std::vector<buoyancy_s>::iterator entry = buoyancy_links_.begin(); entry != buoyancy_links_.end(); ++entry) { #if GAZEBO_MAJOR_VERSION >= 9 ignition::math::Pose3d pose = entry->link->WorldPose(); #else ignition::math::Pose3d pose = ignitionFromGazeboMath(entry->link->GetWorldPose()); #endif cob = pose.Pos() + pose.Rot().RotateVector(entry->cob); force = entry->buoyancy_force; // apply linear scaling on buoyancy force if center of buoyancy z-coordinate // is in range [-height_scale_limit, +height_scale limit]. double scale = std::abs((cob.Z()-entry->height_scale_limit) / (2*entry->height_scale_limit)); if (cob.Z() > entry->height_scale_limit) scale = 0.0; scale = ignition::math::clamp(scale, 0.0, 1.0); force *= scale; entry->link->AddForceAtWorldPosition(force, cob); } } void GazeboUUVPlugin::UpdateForcesAndMoments() { /** * This method: * - computes the hydrodynamic effects (according to FOSSEN 2011 - Handbook of Marine Craft Hydrodynamics and Motion Control) * - applies the Hydro effects as forces/moments and are than applied to the vehicle * - computes the forces/moments based on the motor commands */ //Calculate and add hydrodynamic forces #if GAZEBO_MAJOR_VERSION >= 9 ignition::math::Vector3d linear_velocity = baseLink_->RelativeLinearVel(); ignition::math::Vector3d angular_velocity = baseLink_->RelativeAngularVel(); #else ignition::math::Vector3d linear_velocity = ignitionFromGazeboMath(baseLink_->GetRelativeLinearVel()); ignition::math::Vector3d angular_velocity = ignitionFromGazeboMath(baseLink_->GetRelativeAngularVel()); #endif double u = linear_velocity[0]; double v = linear_velocity[1]; double w = linear_velocity[2]; double p = angular_velocity[0]; double q = angular_velocity[1]; double r = angular_velocity[2]; // Linear Damping Matrix, with minus already multiplied ignition::math::Matrix3d D_FL( -X_u_, 0, 0, 0, -Y_v_, 0, 0, 0, -Z_w_ ); // Angular Damping Matrix, with minus already multiplied ignition::math::Matrix3d D_FA( -K_p_, 0, 0, 0, -M_q_, 0, 0, 0, -N_r_ ); ignition::math::Vector3d damping_force = D_FL*linear_velocity; ignition::math::Vector3d damping_torque = D_FA*angular_velocity; // Corriolis Forces and Torques // upper right and bottom left matrix, with minus already multiplied ignition::math::Matrix3d C_AD_FA( 0, Z_wdot_ * w, -Y_vdot_ * v, -Z_wdot_ * w, 0, X_udot_ * u, Y_vdot_ * v, -X_udot_ * u, 0 ); // Torques from angular velocity, with minus already multiplied ignition::math::Matrix3d C_AD_TA( 0, N_rdot_ * r, -M_qdot_ * q, -N_rdot_ * r, 0, K_pdot_ * p, M_qdot_ * q, -K_pdot_ * p, 0 ); ignition::math::Vector3d coriolis_force = C_AD_FA*angular_velocity; ignition::math::Vector3d coriolis_torque = (C_AD_FA*linear_velocity) + (C_AD_TA*angular_velocity); //std::cout << C_AD_FA << "\n"; //std::cout << "Linear:" << coriolis_force << "\n"; //std::cout << "Angular:" << angular_velocity << "\n"; baseLink_->AddRelativeForce(damping_force + coriolis_force); baseLink_->AddRelativeTorque(damping_torque + coriolis_torque); } GZ_REGISTER_MODEL_PLUGIN(GazeboUUVPlugin); }
38.73913
138
0.697194
666cats
4079dd1ca990e40a6fde7ac7faa692666aaa8589
19,176
cpp
C++
Source/Core/Visualization/Object/PointObject.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
42
2015-07-24T23:05:07.000Z
2022-03-16T01:31:04.000Z
Source/Core/Visualization/Object/PointObject.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
4
2015-03-17T05:42:49.000Z
2020-08-09T15:21:45.000Z
Source/Core/Visualization/Object/PointObject.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
29
2015-01-03T05:56:32.000Z
2021-10-05T15:28:33.000Z
/*****************************************************************************/ /** * @file PointObject.cpp * @author Naohisa Sakamoto */ /*****************************************************************************/ #include "PointObject.h" #include <cstring> #include <kvs/KVSMLPointObject> #include <kvs/LineObject> #include <kvs/PolygonObject> #include <kvs/Assert> namespace { /*===========================================================================*/ /** * @brief Returns a writing data type. * @param ascii [in] ascii (true = default) or binary (true) * @param external [in] external (true) or internal (false = default) * @return writing data type */ /*===========================================================================*/ kvs::KVSMLPointObject::WritingDataType GetWritingDataType( const bool ascii, const bool external ) { if ( ascii ) { if ( external ) { return kvs::KVSMLPointObject::ExternalAscii; } else { return kvs::KVSMLPointObject::Ascii; } } else { return kvs::KVSMLPointObject::ExternalBinary; } } } namespace kvs { /*===========================================================================*/ /** * @brief Constructs a new PointObject class. */ /*===========================================================================*/ PointObject::PointObject() { BaseClass::setGeometryType( Point ); this->setSize( 1 ); } /*===========================================================================*/ /** * @brief Constructs a new PointObject class. * @param line [in] line object */ /*===========================================================================*/ PointObject::PointObject( const kvs::LineObject& line ) { BaseClass::setGeometryType( Point ); BaseClass::setCoords( line.coords() ); if ( line.colorType() == kvs::LineObject::VertexColor ) { BaseClass::setColors( line.colors() ); } else { BaseClass::setColor( line.color() ); } this->setSize( line.size() ); BaseClass::setMinMaxObjectCoords( line.minObjectCoord(), line.maxObjectCoord() ); BaseClass::setMinMaxExternalCoords( line.minExternalCoord(), line.maxExternalCoord() ); } /*===========================================================================*/ /** * @brief Constructs a new PointObject class. * @param polygon [in] polygon object */ /*===========================================================================*/ PointObject::PointObject( const kvs::PolygonObject& polygon ) { BaseClass::setGeometryType( Point ); BaseClass::setCoords( polygon.coords() ); if ( polygon.colorType() == kvs::PolygonObject::VertexColor ) { BaseClass::setColors( polygon.colors() ); } else { BaseClass::setColor( polygon.color() ); } if ( polygon.normalType() == kvs::PolygonObject::VertexNormal ) { BaseClass::setNormals( polygon.normals() ); } this->setSize( 1.0f ); BaseClass::setMinMaxObjectCoords( polygon.minObjectCoord(), polygon.maxObjectCoord() ); BaseClass::setMinMaxExternalCoords( polygon.minExternalCoord(), polygon.maxExternalCoord() ); } /*===========================================================================*/ /** * @brief Add the point object. * @param other [in] point object */ /*===========================================================================*/ void PointObject::add( const PointObject& other ) { if ( this->coords().size() == 0 ) { // Copy the object. BaseClass::setCoords( other.coords() ); BaseClass::setNormals( other.normals() ); BaseClass::setColors( other.colors() ); this->setSizes( other.sizes() ); BaseClass::setMinMaxObjectCoords( other.minObjectCoord(), other.maxObjectCoord() ); BaseClass::setMinMaxExternalCoords( other.minExternalCoord(), other.maxExternalCoord() ); } else { if ( !BaseClass::hasMinMaxObjectCoords() ) { BaseClass::updateMinMaxCoords(); } kvs::Vec3 min_object_coord( BaseClass::minObjectCoord() ); kvs::Vec3 max_object_coord( BaseClass::maxObjectCoord() ); min_object_coord.x() = kvs::Math::Min( min_object_coord.x(), other.minObjectCoord().x() ); min_object_coord.y() = kvs::Math::Min( min_object_coord.y(), other.minObjectCoord().y() ); min_object_coord.z() = kvs::Math::Min( min_object_coord.z(), other.minObjectCoord().z() ); max_object_coord.x() = kvs::Math::Max( max_object_coord.x(), other.maxObjectCoord().x() ); max_object_coord.y() = kvs::Math::Max( max_object_coord.y(), other.maxObjectCoord().y() ); max_object_coord.z() = kvs::Math::Max( max_object_coord.z(), other.maxObjectCoord().z() ); BaseClass::setMinMaxObjectCoords( min_object_coord, max_object_coord ); BaseClass::setMinMaxExternalCoords( min_object_coord, max_object_coord ); // Integrate the coordinate values. kvs::ValueArray<kvs::Real32> coords; const size_t ncoords = this->coords().size() + other.coords().size(); coords.allocate( ncoords ); kvs::Real32* pcoords = coords.data(); // x,y,z, ... + x,y,z, ... = x,y,z, ... ,x,y,z, ... memcpy( pcoords, this->coords().data(), this->coords().byteSize() ); memcpy( pcoords + this->coords().size(), other.coords().data(), other.coords().byteSize() ); BaseClass::setCoords( coords ); // Integrate the normal vectors. kvs::ValueArray<kvs::Real32> normals; if ( this->normals().size() > 0 ) { if ( other.normals().size() > 0 ) { // nx,ny,nz, ... + nx,ny,nz, ... = nx,ny,nz, ... ,nx,ny,nz, ... const size_t nnormals = this->normals().size() + other.normals().size(); normals.allocate( nnormals ); kvs::Real32* pnormals = normals.data(); memcpy( pnormals, this->normals().data(), this->normals().byteSize() ); memcpy( pnormals + this->normals().size(), other.normals().data(), other.normals().byteSize() ); } else { // nx,ny,nz, ... + (none) = nx,ny,nz, ... ,0,0,0, ... const size_t nnormals = this->normals().size() + other.coords().size(); normals.allocate( nnormals ); kvs::Real32* pnormals = normals.data(); memcpy( pnormals, this->normals().data(), this->normals().byteSize() ); memset( pnormals + this->normals().size(), 0, other.coords().byteSize() ); } } else { if ( other.normals().size() > 0 ) { const size_t nnormals = this->coords().size() + other.normals().size(); normals.allocate( nnormals ); kvs::Real32* pnormals = normals.data(); // (none) + nx,ny,nz, ... = 0,0,0, ... ,nz,ny,nz, ... memset( pnormals, 0, this->coords().byteSize() ); memcpy( pnormals + this->coords().size(), other.normals().data(), other.normals().byteSize() ); } } BaseClass::setNormals( normals ); // Integrate the color values. kvs::ValueArray<kvs::UInt8> colors; if ( this->colors().size() > 1 ) { if ( other.colors().size() > 1 ) { // r,g,b, ... + r,g,b, ... = r,g,b, ... ,r,g,b, ... const size_t ncolors = this->colors().size() + other.colors().size(); colors.allocate( ncolors ); kvs::UInt8* pcolors = colors.data(); memcpy( pcolors, this->colors().data(), this->colors().byteSize() ); memcpy( pcolors + this->colors().size(), other.colors().data(), other.colors().byteSize() ); } else { // r,g,b, ... + R,G,B = r,g,b, ... ,R,G,B, ... ,R,G,B const size_t ncolors = this->colors().size() + other.coords().size(); colors.allocate( ncolors ); kvs::UInt8* pcolors = colors.data(); memcpy( pcolors, this->colors().data(), this->colors().byteSize() ); pcolors += this->colors().size(); const kvs::RGBColor color = other.color(); for ( size_t i = 0; i < other.coords().size(); i += 3 ) { *(pcolors++) = color.r(); *(pcolors++) = color.g(); *(pcolors++) = color.b(); } } } else { if ( other.colors().size() > 1 ) { // R,G,B + r,g,b, ... = R,G,B, ... ,R,G,B, r,g,b, ... const size_t ncolors = this->coords().size() + other.colors().size(); colors.allocate( ncolors ); kvs::UInt8* pcolors = colors.data(); const kvs::RGBColor color = this->color(); for ( size_t i = 0; i < this->coords().size(); i += 3 ) { *(pcolors++) = color.r(); *(pcolors++) = color.g(); *(pcolors++) = color.b(); } memcpy( pcolors, other.colors().data(), other.colors().byteSize() ); } else { const kvs::RGBColor color1 = this->color(); const kvs::RGBColor color2 = other.color(); if ( color1 == color2 ) { // R,G,B + R,G,B = R,G,B const size_t ncolors = 3; colors.allocate( ncolors ); kvs::UInt8* pcolors = colors.data(); *(pcolors++) = color1.r(); *(pcolors++) = color1.g(); *(pcolors++) = color1.b(); } else { // R,G,B + R,G,B = R,G,B, ... ,R,G,B, ... const size_t ncolors = this->coords().size() + other.coords().size(); colors.allocate( ncolors ); kvs::UInt8* pcolors = colors.data(); for ( size_t i = 0; i < this->coords().size(); i += 3 ) { *(pcolors++) = color1.r(); *(pcolors++) = color1.g(); *(pcolors++) = color1.b(); } for ( size_t i = 0; i < other.coords().size(); i += 3 ) { *(pcolors++) = color2.r(); *(pcolors++) = color2.g(); *(pcolors++) = color2.b(); } } } } BaseClass::setColors( colors ); // Integrate the size values. kvs::ValueArray<kvs::Real32> sizes; if ( this->sizes().size() > 1 ) { if ( other.sizes().size() > 1 ) { // s, ... + s, ... = s, ... ,s, ... const size_t nsizes = this->sizes().size() + other.sizes().size(); sizes.allocate( nsizes ); kvs::Real32* psizes = sizes.data(); memcpy( psizes, this->sizes().data(), this->sizes().byteSize() ); memcpy( psizes + this->sizes().size(), other.sizes().data(), other.sizes().byteSize() ); } else { // s, ... + S = s, ... ,S, ... ,S const size_t nsizes = this->sizes().size() + other.coords().size(); sizes.allocate( nsizes ); kvs::Real32* psizes = sizes.data(); memcpy( psizes, this->sizes().data(), this->sizes().byteSize() ); psizes += this->colors().size(); const kvs::Real32 size = other.size(); for ( size_t i = 0; i < other.coords().size(); i++ ) { *(psizes++) = size; } } } else { if ( other.sizes().size() > 1 ) { // S + s, ... = S, ... ,S, s, ... const size_t nsizes = this->coords().size() + other.sizes().size(); sizes.allocate( nsizes ); kvs::Real32* psizes = sizes.data(); const kvs::Real32 size = this->size(); for ( size_t i = 0; i < this->coords().size(); i++ ) { *(psizes++) = size; } memcpy( psizes, other.sizes().data(), other.sizes().byteSize() ); } else { const kvs::Real32 size1 = this->size(); const kvs::Real32 size2 = other.size(); if ( size1 == size2 ) { // S + S = S const size_t nsizes = 1; sizes.allocate( nsizes ); kvs::Real32* psizes = sizes.data(); *(psizes++) = size1; } else { // S + S = S, ... , S, ... const size_t nsizes = this->coords().size() + other.coords().size(); sizes.allocate( nsizes ); kvs::Real32* psizes = sizes.data(); for ( size_t i = 0; i < this->coords().size(); i++ ) { *(psizes++) = size1; } for ( size_t i = 0; i < other.coords().size(); i++ ) { *(psizes++) = size2; } } } } this->setSizes( sizes ); } } /*===========================================================================*/ /** * @brief Shallow copy the point object. * @param other [in] point object */ /*===========================================================================*/ void PointObject::shallowCopy( const PointObject& other ) { BaseClass::shallowCopy( other ); m_sizes = other.sizes(); } /*===========================================================================*/ /** * @brief Deep copy the point object. * @param other [in] point object */ /*===========================================================================*/ void PointObject::deepCopy( const PointObject& other ) { BaseClass::deepCopy( other ); m_sizes = other.sizes().clone(); } /*===========================================================================*/ /** * @brief Clear the point object. */ /*===========================================================================*/ void PointObject::clear() { BaseClass::clear(); m_sizes.release(); } /*===========================================================================*/ /** * @brief Prints information of the point object. * @param os [in] output stream * @param indent [in] indent */ /*===========================================================================*/ void PointObject::print( std::ostream& os, const kvs::Indent& indent ) const { os << indent << "Object type : " << "point object" << std::endl; BaseClass::print( os, indent ); os << indent << "Number of sizes : " << this->numberOfSizes() << std::endl; } /*===========================================================================*/ /** * @brief Read a point object from the specified file in KVSML. * @param filename [in] input filename * @return true, if the reading process is done successfully */ /*===========================================================================*/ bool PointObject::read( const std::string& filename ) { if ( !kvs::KVSMLPointObject::CheckExtension( filename ) ) { kvsMessageError("%s is not a point object file in KVSML.", filename.c_str()); return false; } kvs::KVSMLPointObject kvsml; if ( !kvsml.read( filename ) ) { return false; } this->setCoords( kvsml.coords() ); this->setColors( kvsml.colors() ); this->setNormals( kvsml.normals() ); this->setSizes( kvsml.sizes() ); if ( kvsml.hasExternalCoord() ) { const kvs::Vec3 min_coord( kvsml.minExternalCoord() ); const kvs::Vec3 max_coord( kvsml.maxExternalCoord() ); this->setMinMaxExternalCoords( min_coord, max_coord ); } if ( kvsml.hasObjectCoord() ) { const kvs::Vec3 min_coord( kvsml.minObjectCoord() ); const kvs::Vec3 max_coord( kvsml.maxObjectCoord() ); this->setMinMaxObjectCoords( min_coord, max_coord ); } else { this->updateMinMaxCoords(); } return true; } /*===========================================================================*/ /** * @brief Write the point object to the specfied file in KVSML. * @param filename [in] output filename * @param ascii [in] ascii (true = default) or binary (true) * @param external [in] external (true) or internal (false = default) * @return true, if the writing process is done successfully */ /*===========================================================================*/ bool PointObject::write( const std::string& filename, const bool ascii, const bool external ) const { kvs::KVSMLPointObject kvsml; kvsml.setWritingDataType( ::GetWritingDataType( ascii, external ) ); kvsml.setCoords( this->coords() ); kvsml.setColors( this->colors() ); kvsml.setNormals( this->normals() ); kvsml.setSizes( this->sizes() ); if ( this->hasMinMaxObjectCoords() ) { kvsml.setMinMaxObjectCoords( this->minObjectCoord(), this->maxObjectCoord() ); } if ( this->hasMinMaxExternalCoords() ) { kvsml.setMinMaxExternalCoords( this->minExternalCoord(), this->maxExternalCoord() ); } return kvsml.write( filename ); } /*===========================================================================*/ /** * @brief Sets a size value. * @param size [in] size value */ /*===========================================================================*/ void PointObject::setSize( const kvs::Real32 size ) { m_sizes.allocate( 1 ); m_sizes[0] = size; } /*===========================================================================*/ /** * @brief '<<' operator */ /*===========================================================================*/ std::ostream& operator << ( std::ostream& os, const PointObject& object ) { os << "Object type: " << "point object" << std::endl; #ifdef KVS_COMPILER_VC #if KVS_COMPILER_VERSION_LESS_OR_EQUAL( 8, 0 ) // @TODO Cannot instance the object that is a abstract class here (error:C2259). #endif #else // os << static_cast<const kvs::GeometryObjectBase&>( object ) << std::endl; static_cast<const kvs::GeometryObjectBase&>( object ).print( os ); #endif os << "Number of sizes: " << object.numberOfSizes(); return os; } } // end of namespace kvs
36.045113
112
0.448112
X1aoyueyue
407ac86c18e4be8bce020a1fb5d9874a96d7bfb2
738
hpp
C++
include/tdc/test/assert.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2021-05-06T13:39:22.000Z
2021-05-06T13:39:22.000Z
include/tdc/test/assert.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2020-03-07T08:05:20.000Z
2020-03-07T08:05:20.000Z
include/tdc/test/assert.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
2
2020-05-27T07:54:43.000Z
2021-11-18T13:29:14.000Z
#include <cstdlib> #include <iostream> #define ASSERT_FAIL_STR "Assertion failed: " #define ASSERT_TRUE(x) \ { \ if(!x) { \ std::cerr \ << ASSERT_FAIL_STR \ << __FILE__ << ":" << __LINE__ \ << " in " << __PRETTY_FUNCTION__ \ << std::endl; \ std::flush(std::cerr); \ std::abort(); \ } \ } #define ASSERT_FALSE(x) \ ASSERT_TRUE((!x)) #define ASSERT_EQ(x, y) \ ASSERT_TRUE((x == y)) #define ASSERT_NEQ(x, y) \ ASSERT_TRUE((x != y)) #define ASSERT_GT(x, y) \ ASSERT_TRUE((x > y)) #define ASSERT_GEQ(x, y) \ ASSERT_TRUE((x >= y)) #define ASSERT_LT(x, y) \ ASSERT_TRUE((x < y)) #define ASSERT_LEQ(x, y) \ ASSERT_TRUE((x <= y))
18.923077
46
0.5271
herlez
407b81392447b8682efc00641682fb59925a47fc
1,660
cc
C++
impl/components/editing/content/renderer/editorclient_agent.cc
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
impl/components/editing/content/renderer/editorclient_agent.cc
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
impl/components/editing/content/renderer/editorclient_agent.cc
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2013 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/editing/content/renderer/editorclient_agent.h" #include "third_party/WebKit/public/web/WebView.h" #include "content/public/renderer/render_view.h" #include "components/editing/content/common/editing_messages.h" namespace editing { EditorClientAgent::EditorClientAgent(content::RenderView* render_view) : content::RenderViewObserver(render_view) { #if !defined(EWK_BRINGUP) render_view->GetWebView()->setEditorClient(this); #endif } bool EditorClientAgent::OnMessageReceived(const IPC::Message& message) { return false; } void EditorClientAgent::registerUndoStep(size_t undoStackSize) { Send(new EditingHostMsg_NotifyRegisterUndo(routing_id(), routing_id(), undoStackSize)); } void EditorClientAgent::registerRedoStep(size_t redoStackSize) { Send(new EditingHostMsg_NotifyRegisterRedo(routing_id(), routing_id(), redoStackSize)); } void EditorClientAgent::clearUndoRedoOperations(const std::string& command, size_t stackSize) { if (command == "Undo") Send(new EditingHostMsg_NotifyClearUndo(routing_id(), routing_id(), stackSize)); else if (command == "Redo") Send(new EditingHostMsg_NotifyClearRedo(routing_id(), routing_id(), stackSize)); } void EditorClientAgent::Undo(size_t undoStackSize) { Send(new EditingHostMsg_NotifyUndo(routing_id(), routing_id(), undoStackSize)); } void EditorClientAgent::Redo(size_t redoStackSize) { Send(new EditingHostMsg_NotifyRedo(routing_id(), routing_id(), redoStackSize)); } } // namespace editing
34.583333
95
0.784337
Jabawack
407c78f68d99e273e46b5a315c687b827f18d526
185
cpp
C++
engine/src/graphics/texture.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
engine/src/graphics/texture.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
engine/src/graphics/texture.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
#include "texture.h" namespace prev { DEFINE_OBJECT_START(Texture2D, Vec2i size, TextureParams params) DEFINE_OBJECT_BODY(Texture2D, size, params); DEFINE_OBJECT_END(Texture2D) }
20.555556
65
0.794595
anujv99
407d76d1bd7404d9dae9320c82b36f1318e4b159
797
hpp
C++
wire/core/subscription.hpp
wagnercotta/is-wire
15812227b57b814fbc9317465b6918375bc89c92
[ "MIT" ]
1
2018-05-04T16:27:49.000Z
2018-05-04T16:27:49.000Z
wire/core/subscription.hpp
wagnercotta/is-wire
15812227b57b814fbc9317465b6918375bc89c92
[ "MIT" ]
2
2018-05-25T16:15:19.000Z
2018-05-25T16:20:09.000Z
wire/core/subscription.hpp
wagnercotta/is-wire
15812227b57b814fbc9317465b6918375bc89c92
[ "MIT" ]
5
2018-05-30T10:02:28.000Z
2021-10-29T19:00:30.000Z
#pragma once #include <chrono> #include <string> #include <vector> #include "boost/optional.hpp" namespace AmqpClient { class Channel; } namespace is { class Message; class Channel; using namespace std::chrono; class Subscription { boost::shared_ptr<AmqpClient::Channel> impl; std::string exchange; std::string queue; std::string tag; public: Subscription(Channel& channel, std::string const& name = ""); Subscription(Subscription const&) = default; Subscription(Subscription&&) = default; std::string id() const; std::string name() const; void subscribe(std::string const& topic); void subscribe(std::vector<std::string> const& topics); void unsubscribe(std::string const& topic); void unsubscribe(std::vector<std::string> const& topics); }; } // namespace is
20.973684
63
0.716437
wagnercotta
407fb0873cabafb6a76ea98a76ff099c0755cd1f
1,610
cpp
C++
class11/reduce_sum_blocks.cpp
profmdipierro/cpsc445
5ff4164b78ff4a5f0285e28b60fb615072d45829
[ "BSD-3-Clause" ]
3
2021-09-14T03:21:58.000Z
2021-11-13T00:11:11.000Z
class11/reduce_sum_blocks.cpp
profmdipierro/cpsc445
5ff4164b78ff4a5f0285e28b60fb615072d45829
[ "BSD-3-Clause" ]
null
null
null
class11/reduce_sum_blocks.cpp
profmdipierro/cpsc445
5ff4164b78ff4a5f0285e28b60fb615072d45829
[ "BSD-3-Clause" ]
2
2021-09-04T18:08:00.000Z
2021-11-19T18:38:25.000Z
#include <stdio.h> __global__ void reduce_sum_step1(int * da, int N) { int B = gridDim.x; int W = blockDim.x; int shift = W * B; __shared__ int tmp[1024]; int tid = threadIdx.x; int gid = blockIdx.x * blockDim.x + threadIdx.x; tmp[tid] = da[gid]; for(int i=gid+shift; i<N; i+=shift) { tmp[tid]+=da[i]; } __syncthreads(); for(int delta=1; delta<W; delta*=2) { int i = threadIdx.x; if (i + delta < W) { tmp[i] += tmp[i+delta]; } __syncthreads(); } shift = blockDim.x * blockIdx.x; da[shift] = tmp[0]; } __global__ void reduce_sum_step2(int * da, int W) { int B = blockDim.x; int shift = B; int tid = threadIdx.x; __shared__ int tmp[1024]; for(int i=0; i<W; i++) tmp[i] = da[i*W]; for(int delta=1; delta<B; delta*=2) { int i = tid*2*delta; if (i + delta < B) { tmp[i] += tmp[i+delta]; } __syncthreads(); } da[0] = tmp[0]; } int main() { //INPUTS int N = 1000; int *ha = new int[N]; int *hb = new int[N]; int *da; cudaMalloc((void **)&da, N*sizeof(int)); // set problem input (b) for (int i = 0; i<N; ++i) { ha[i] = i*i; } cudaMemcpy(da, ha, N*sizeof(int), cudaMemcpyHostToDevice); int B = 3; int W = 16; reduce_sum_step1<<<B,W>>>(da, N); cudaDeviceSynchronize(); reduce_sum_step2<<<1,B>>>(da, W); cudaDeviceSynchronize(); int sum; cudaMemcpy(&sum, da, sizeof(int), cudaMemcpyDeviceToHost); int expected_sum = (N-1)*N*(2*N-1)/6; printf("%i (should be %i)", sum, expected_sum); cudaFree(da); free(ha); free(hb); return 0; }
18.505747
60
0.557764
profmdipierro
407ffbfaf9205a1cc8e5c7ca07babc6136067b32
49,767
cpp
C++
tests/test_http_server_cb/test_http_server_cb.cpp
DG12/ruuvi.gateway_esp.c
cf22748af0c0a37287f08b49477f06f56456f72f
[ "BSD-3-Clause" ]
null
null
null
tests/test_http_server_cb/test_http_server_cb.cpp
DG12/ruuvi.gateway_esp.c
cf22748af0c0a37287f08b49477f06f56456f72f
[ "BSD-3-Clause" ]
null
null
null
tests/test_http_server_cb/test_http_server_cb.cpp
DG12/ruuvi.gateway_esp.c
cf22748af0c0a37287f08b49477f06f56456f72f
[ "BSD-3-Clause" ]
null
null
null
/** * @file test_bin2hex.cpp * @author TheSomeMan * @date 2020-08-27 * @copyright Ruuvi Innovations Ltd, license BSD-3-Clause. */ #include "http_server_cb.h" #include <cstring> #include <utility> #include "gtest/gtest.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log_wrapper.hpp" #include "gw_cfg.h" #include "json_ruuvi.h" #include "flashfatfs.h" using namespace std; /*** Google-test class implementation * *********************************************************************************/ class TestHttpServerCb; static TestHttpServerCb *g_pTestClass; struct flash_fat_fs_t { string mount_point; string partition_label; flash_fat_fs_num_files_t max_files; }; extern "C" { const char * os_task_get_name(void) { static const char g_task_name[] = "main"; return const_cast<char *>(g_task_name); } } // extern "C" class MemAllocTrace { vector<void *> allocated_mem; std::vector<void *>::iterator find(void *ptr) { for (auto iter = this->allocated_mem.begin(); iter != this->allocated_mem.end(); ++iter) { if (*iter == ptr) { return iter; } } return this->allocated_mem.end(); } public: void add(void *ptr) { auto iter = find(ptr); assert(iter == this->allocated_mem.end()); // ptr was found in the list of allocated memory blocks this->allocated_mem.push_back(ptr); } void remove(void *ptr) { auto iter = find(ptr); assert(iter != this->allocated_mem.end()); // ptr was not found in the list of allocated memory blocks this->allocated_mem.erase(iter); } bool is_empty() { return this->allocated_mem.empty(); } }; class FileInfo { public: string fileName; string content; bool flag_fail_to_open; FileInfo(string fileName, string content, const bool flag_fail_to_open) : fileName(std::move(fileName)) , content(std::move(content)) , flag_fail_to_open(flag_fail_to_open) { } FileInfo(string fileName, string content) : FileInfo(std::move(fileName), std::move(content), false) { } }; class TestHttpServerCb : public ::testing::Test { private: protected: void SetUp() override { esp_log_wrapper_init(); g_pTestClass = this; this->m_malloc_cnt = 0; this->m_malloc_fail_on_cnt = 0; this->m_flag_settings_saved_to_flash = false; this->m_flag_settings_sent_to_nrf = false; this->m_flag_settings_ethernet_ip_updated = false; } void TearDown() override { http_server_cb_deinit(); this->m_files.clear(); this->m_fd = -1; g_pTestClass = nullptr; esp_log_wrapper_deinit(); } public: TestHttpServerCb(); ~TestHttpServerCb() override; MemAllocTrace m_mem_alloc_trace; uint32_t m_malloc_cnt; uint32_t m_malloc_fail_on_cnt; bool m_flag_settings_saved_to_flash; bool m_flag_settings_sent_to_nrf; bool m_flag_settings_ethernet_ip_updated; flash_fat_fs_t m_fatfs; bool m_is_fatfs_mounted; bool m_is_fatfs_mount_fail; vector<FileInfo> m_files; file_descriptor_t m_fd; }; TestHttpServerCb::TestHttpServerCb() : m_malloc_cnt(0) , m_malloc_fail_on_cnt(0) , m_flag_settings_saved_to_flash(false) , m_flag_settings_sent_to_nrf(false) , m_flag_settings_ethernet_ip_updated(false) , m_is_fatfs_mounted(false) , m_is_fatfs_mount_fail(false) , m_fd(-1) , Test() { } extern "C" { void * os_malloc(const size_t size) { if (++g_pTestClass->m_malloc_cnt == g_pTestClass->m_malloc_fail_on_cnt) { return nullptr; } void *ptr = malloc(size); assert(nullptr != ptr); g_pTestClass->m_mem_alloc_trace.add(ptr); return ptr; } void os_free_internal(void *ptr) { g_pTestClass->m_mem_alloc_trace.remove(ptr); free(ptr); } void * os_calloc(const size_t nmemb, const size_t size) { if (++g_pTestClass->m_malloc_cnt == g_pTestClass->m_malloc_fail_on_cnt) { return nullptr; } void *ptr = calloc(nmemb, size); assert(nullptr != ptr); g_pTestClass->m_mem_alloc_trace.add(ptr); return ptr; } char * ruuvi_get_metrics(void) { const char *p_metrics_str = "metrics_info"; char * p_buf = static_cast<char *>(os_malloc(strlen(p_metrics_str) + 1)); if (nullptr != p_buf) { strcpy(p_buf, p_metrics_str); } return p_buf; } void settings_save_to_flash(const ruuvi_gateway_config_t *p_config) { g_pTestClass->m_flag_settings_saved_to_flash = true; } void ethernet_update_ip(void) { g_pTestClass->m_flag_settings_ethernet_ip_updated = true; } void ruuvi_send_nrf_settings(const ruuvi_gateway_config_t *p_config) { g_pTestClass->m_flag_settings_sent_to_nrf = true; } const flash_fat_fs_t * flashfatfs_mount(const char *mount_point, const char *partition_label, const flash_fat_fs_num_files_t max_files) { assert(!g_pTestClass->m_is_fatfs_mounted); if (g_pTestClass->m_is_fatfs_mount_fail) { return nullptr; } g_pTestClass->m_fatfs.mount_point.assign(mount_point); g_pTestClass->m_fatfs.partition_label.assign(partition_label); g_pTestClass->m_fatfs.max_files = max_files; g_pTestClass->m_is_fatfs_mounted = true; return &g_pTestClass->m_fatfs; } bool flashfatfs_unmount(const flash_fat_fs_t **pp_ffs) { assert(nullptr != pp_ffs); assert(*pp_ffs == &g_pTestClass->m_fatfs); assert(g_pTestClass->m_is_fatfs_mounted); g_pTestClass->m_is_fatfs_mounted = false; g_pTestClass->m_fatfs.mount_point.assign(""); g_pTestClass->m_fatfs.partition_label.assign(""); g_pTestClass->m_fatfs.max_files = 0; *pp_ffs = nullptr; return true; } bool flashfatfs_get_file_size(const flash_fat_fs_t *p_ffs, const char *file_path, size_t *p_size) { assert(p_ffs == &g_pTestClass->m_fatfs); for (auto &file : g_pTestClass->m_files) { if (0 == strcmp(file_path, file.fileName.c_str())) { *p_size = file.content.size(); return true; } } *p_size = 0; return false; } file_descriptor_t flashfatfs_open(const flash_fat_fs_t *p_ffs, const char *file_path) { assert(p_ffs == &g_pTestClass->m_fatfs); for (auto &file : g_pTestClass->m_files) { if (0 == strcmp(file_path, file.fileName.c_str())) { if (file.flag_fail_to_open) { return (file_descriptor_t)-1; } return g_pTestClass->m_fd; } } return (file_descriptor_t)-1; } } // extern "C" TestHttpServerCb::~TestHttpServerCb() = default; #define TEST_CHECK_LOG_RECORD_HTTP_SERVER(level_, msg_) \ ESP_LOG_WRAPPER_TEST_CHECK_LOG_RECORD("http_server", level_, msg_) #define TEST_CHECK_LOG_RECORD_GW_CFG(level_, msg_) ESP_LOG_WRAPPER_TEST_CHECK_LOG_RECORD("gw_cfg", level_, msg_) /*** Unit-Tests * *******************************************************************************************************/ TEST_F(TestHttpServerCb, http_server_cb_init_ok_deinit_ok) // NOLINT { ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); ASSERT_TRUE(http_server_cb_init()); ASSERT_TRUE(g_pTestClass->m_is_fatfs_mounted); ASSERT_TRUE(esp_log_wrapper_is_empty()); http_server_cb_deinit(); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); } TEST_F(TestHttpServerCb, http_server_cb_deinit_of_not_initialized) // NOLINT { ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); http_server_cb_deinit(); ASSERT_TRUE(esp_log_wrapper_is_empty()); ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); } TEST_F(TestHttpServerCb, http_server_cb_init_failed) // NOLINT { ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); this->m_is_fatfs_mount_fail = true; ASSERT_FALSE(http_server_cb_init()); ASSERT_FALSE(g_pTestClass->m_is_fatfs_mounted); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "flashfatfs_mount: failed to mount partition 'fatfs_gwui'"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_json_ruuvi_ok) // NOLINT { const char *expected_json = "{\n" "\t\"eth_dhcp\":\ttrue,\n" "\t\"eth_static_ip\":\t\"\",\n" "\t\"eth_netmask\":\t\"\",\n" "\t\"eth_gw\":\t\"\",\n" "\t\"eth_dns1\":\t\"\",\n" "\t\"eth_dns2\":\t\"\",\n" "\t\"use_http\":\tfalse,\n" "\t\"http_url\":\t\"https://network.ruuvi.com/record\",\n" "\t\"http_user\":\t\"\",\n" "\t\"use_mqtt\":\ttrue,\n" "\t\"mqtt_server\":\t\"test.mosquitto.org\",\n" "\t\"mqtt_port\":\t1883,\n" "\t\"mqtt_prefix\":\t\"ruuvi/30:AE:A4:02:84:A4\",\n" "\t\"mqtt_user\":\t\"\",\n" "\t\"gw_mac\":\t\"11:22:33:44:55:66\",\n" "\t\"use_filtering\":\ttrue,\n" "\t\"company_id\":\t\"0x0499\",\n" "\t\"coordinates\":\t\"\",\n" "\t\"use_coded_phy\":\tfalse,\n" "\t\"use_1mbit_phy\":\ttrue,\n" "\t\"use_extended_payload\":\ttrue,\n" "\t\"use_channel_37\":\ttrue,\n" "\t\"use_channel_38\":\ttrue,\n" "\t\"use_channel_39\":\ttrue\n" "}"; ASSERT_TRUE(json_ruuvi_parse_http_body( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}", &g_gateway_config)); snprintf(gw_mac_sta.str_buf, sizeof(gw_mac_sta.str_buf), "11:22:33:44:55:66"); esp_log_wrapper_clear(); const http_server_resp_t resp = http_server_resp_json_ruuvi(); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_HEAP, resp.content_location); ASSERT_TRUE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_JSON, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_json), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_json), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("ruuvi.json: ") + string(expected_json)); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_json_ruuvi_malloc_failed) // NOLINT { ASSERT_TRUE(json_ruuvi_parse_http_body( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}", &g_gateway_config)); snprintf(gw_mac_sta.str_buf, sizeof(gw_mac_sta.str_buf), "11:22:33:44:55:66"); cJSON_Hooks hooks = { .malloc_fn = &os_malloc, .free_fn = &os_free_internal, }; g_pTestClass->m_malloc_fail_on_cnt = 1; cJSON_InitHooks(&hooks); esp_log_wrapper_clear(); const http_server_resp_t resp = http_server_resp_json_ruuvi(); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_ERROR, string("Can't create json object")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_json_ok) // NOLINT { const char *expected_json = "{\n" "\t\"eth_dhcp\":\ttrue,\n" "\t\"eth_static_ip\":\t\"\",\n" "\t\"eth_netmask\":\t\"\",\n" "\t\"eth_gw\":\t\"\",\n" "\t\"eth_dns1\":\t\"\",\n" "\t\"eth_dns2\":\t\"\",\n" "\t\"use_http\":\tfalse,\n" "\t\"http_url\":\t\"https://network.ruuvi.com/record\",\n" "\t\"http_user\":\t\"\",\n" "\t\"use_mqtt\":\ttrue,\n" "\t\"mqtt_server\":\t\"test.mosquitto.org\",\n" "\t\"mqtt_port\":\t1883,\n" "\t\"mqtt_prefix\":\t\"ruuvi/30:AE:A4:02:84:A4\",\n" "\t\"mqtt_user\":\t\"\",\n" "\t\"gw_mac\":\t\"11:22:33:44:55:66\",\n" "\t\"use_filtering\":\ttrue,\n" "\t\"company_id\":\t\"0x0499\",\n" "\t\"coordinates\":\t\"\",\n" "\t\"use_coded_phy\":\tfalse,\n" "\t\"use_1mbit_phy\":\ttrue,\n" "\t\"use_extended_payload\":\ttrue,\n" "\t\"use_channel_37\":\ttrue,\n" "\t\"use_channel_38\":\ttrue,\n" "\t\"use_channel_39\":\ttrue\n" "}"; ASSERT_TRUE(json_ruuvi_parse_http_body( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}", &g_gateway_config)); snprintf(gw_mac_sta.str_buf, sizeof(gw_mac_sta.str_buf), "11:22:33:44:55:66"); esp_log_wrapper_clear(); const http_server_resp_t resp = http_server_resp_json("ruuvi.json"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_HEAP, resp.content_location); ASSERT_TRUE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_JSON, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_json), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_json), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("ruuvi.json: ") + string(expected_json)); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_json_unknown) // NOLINT { const http_server_resp_t resp = http_server_resp_json("unknown.json"); ASSERT_EQ(HTTP_RESP_CODE_404, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_WARN, string("Request to unknown json: unknown.json")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_metrics_ok) // NOLINT { const char * expected_resp = "metrics_info"; const http_server_resp_t resp = http_server_resp_metrics(); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_HEAP, resp.content_location); ASSERT_TRUE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_PLAIN, resp.content_type); ASSERT_NE(nullptr, resp.p_content_type_param); ASSERT_EQ(string("version=0.0.4"), string(resp.p_content_type_param)); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_resp), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("metrics: ") + string(expected_resp)); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_metrics_malloc_failed) // NOLINT { g_pTestClass->m_malloc_fail_on_cnt = 1; const http_server_resp_t resp = http_server_resp_metrics(); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, string("Not enough memory")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_get_content_type_by_ext) // NOLINT { ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, http_get_content_type_by_ext(".html")); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_CSS, http_get_content_type_by_ext(".css")); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_CSS, http_get_content_type_by_ext(".scss")); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_JAVASCRIPT, http_get_content_type_by_ext(".js")); ASSERT_EQ(HTTP_CONENT_TYPE_IMAGE_PNG, http_get_content_type_by_ext(".png")); ASSERT_EQ(HTTP_CONENT_TYPE_IMAGE_SVG_XML, http_get_content_type_by_ext(".svg")); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_OCTET_STREAM, http_get_content_type_by_ext(".ttf")); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_OCTET_STREAM, http_get_content_type_by_ext(".unk")); } TEST_F(TestHttpServerCb, resp_file_index_html_fail_partition_not_ready) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; FileInfo fileInfo = FileInfo("index.html", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("index.html"); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "Try to find file: index.html"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "GWUI partition is not ready"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_index_html_fail_file_name_too_long) // NOLINT { const char * file_name = "a1234567890123456789012345678901234567890123456789012345678901234567890"; const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo(file_name, expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file(file_name); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: ") + string(file_name)); TEST_CHECK_LOG_RECORD_HTTP_SERVER( ESP_LOG_ERROR, string("Temporary buffer is not enough for the file path '") + string(file_name) + string("'")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_index_html) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("index.html", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("index.html"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "Try to find file: index.html"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File index.html was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_index_html_gzipped) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 2; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("index.html.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("index.html"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: index.html")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File index.html.gz was opened successfully, fd=2"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_app_js_gzipped) // NOLINT { const char * expected_resp = "app_js_gzipped"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("app.js.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("app.js"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_JAVASCRIPT, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: app.js")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File app.js.gz was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_app_css_gzipped) // NOLINT { const char * expected_resp = "slyle_css_gzipped"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("style.css.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("style.css"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_CSS, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: style.css")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File style.css.gz was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_binary_without_extension) // NOLINT { const char * expected_resp = "binary_data"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("binary", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("binary"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_OCTET_STREAM, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: binary")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File binary was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_unknown_html) // NOLINT { ASSERT_TRUE(http_server_cb_init()); const http_server_resp_t resp = http_server_resp_file("unknown.html"); ASSERT_EQ(HTTP_RESP_CODE_404, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: unknown.html")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, string("Can't find file: unknown.html")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, resp_file_index_html_failed_on_open) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("index.html", expected_resp, true); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_resp_file("index.html"); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "Try to find file: index.html"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, string("Can't open file: index.html")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_get_default) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("index.html.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_cb_on_get(""); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("GET /")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: index.html")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File index.html.gz was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_get_index_html) // NOLINT { const char * expected_resp = "index_html_content"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("index.html.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_cb_on_get("index.html"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("GET /index.html")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: index.html")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File index.html.gz was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_get_app_js) // NOLINT { const char * expected_resp = "app_js_gzipped"; const file_descriptor_t fd = 1; ASSERT_TRUE(http_server_cb_init()); FileInfo fileInfo = FileInfo("app.js.gz", expected_resp); this->m_files.emplace_back(fileInfo); this->m_fd = fd; const http_server_resp_t resp = http_server_cb_on_get("app.js"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FATFS, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_JAVASCRIPT, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_GZIP, resp.content_encoding); ASSERT_EQ(fd, resp.select_location.fatfs.fd); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("GET /app.js")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("Try to find file: app.js")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "File app.js.gz was opened successfully, fd=1"); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_get_ruuvi_json) // NOLINT { const char *expected_json = "{\n" "\t\"eth_dhcp\":\ttrue,\n" "\t\"eth_static_ip\":\t\"\",\n" "\t\"eth_netmask\":\t\"\",\n" "\t\"eth_gw\":\t\"\",\n" "\t\"eth_dns1\":\t\"\",\n" "\t\"eth_dns2\":\t\"\",\n" "\t\"use_http\":\tfalse,\n" "\t\"http_url\":\t\"https://network.ruuvi.com/record\",\n" "\t\"http_user\":\t\"\",\n" "\t\"use_mqtt\":\ttrue,\n" "\t\"mqtt_server\":\t\"test.mosquitto.org\",\n" "\t\"mqtt_port\":\t1883,\n" "\t\"mqtt_prefix\":\t\"ruuvi/30:AE:A4:02:84:A4\",\n" "\t\"mqtt_user\":\t\"\",\n" "\t\"gw_mac\":\t\"11:22:33:44:55:66\",\n" "\t\"use_filtering\":\ttrue,\n" "\t\"company_id\":\t\"0x0499\",\n" "\t\"coordinates\":\t\"\",\n" "\t\"use_coded_phy\":\tfalse,\n" "\t\"use_1mbit_phy\":\ttrue,\n" "\t\"use_extended_payload\":\ttrue,\n" "\t\"use_channel_37\":\ttrue,\n" "\t\"use_channel_38\":\ttrue,\n" "\t\"use_channel_39\":\ttrue\n" "}"; ASSERT_TRUE(json_ruuvi_parse_http_body( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}", &g_gateway_config)); snprintf(gw_mac_sta.str_buf, sizeof(gw_mac_sta.str_buf), "11:22:33:44:55:66"); esp_log_wrapper_clear(); const http_server_resp_t resp = http_server_cb_on_get("ruuvi.json"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_HEAP, resp.content_location); ASSERT_TRUE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_JSON, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_json), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_json), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("GET /ruuvi.json")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("ruuvi.json: ") + string(expected_json)); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_get_metrics) // NOLINT { const char * expected_resp = "metrics_info"; const http_server_resp_t resp = http_server_cb_on_get("metrics"); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_HEAP, resp.content_location); ASSERT_TRUE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_PLAIN, resp.content_type); ASSERT_NE(nullptr, resp.p_content_type_param); ASSERT_EQ(string("version=0.0.4"), string(resp.p_content_type_param)); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_resp), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("GET /metrics")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_INFO, string("metrics: ") + string(expected_resp)); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_post_ruuvi_ok) // NOLINT { const char *expected_resp = "{}"; memset(&g_gateway_config, 0, sizeof(g_gateway_config)); const http_server_resp_t resp = http_server_cb_on_post_ruuvi( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}"); ASSERT_TRUE(this->m_flag_settings_saved_to_flash); ASSERT_TRUE(this->m_flag_settings_sent_to_nrf); ASSERT_TRUE(this->m_flag_settings_ethernet_ip_updated); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FLASH_MEM, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_JSON, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_resp), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("POST /ruuvi.json")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "Got SETTINGS:"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dhcp not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_static_ip not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_netmask not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_gw not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dns1 not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dns2 not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_mqtt: 1"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_server: test.mosquitto.org"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_prefix: ruuvi/30:AE:A4:02:84:A4"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_port: 1883"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_user: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_pass: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_http: 0"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_url: https://network.ruuvi.com/record"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_user: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_pass: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_filtering: 1"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "company_id not found or invalid"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "coordinates not found"); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("Got SETTINGS from browser:")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use eth dhcp: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth static ip: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth netmask: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth gw: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth dns1: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth dns2: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use mqtt: 1")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt server: test.mosquitto.org")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt port: 1883")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt prefix: ruuvi/30:AE:A4:02:84:A4")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt user: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt password: ********")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use http: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http url: https://network.ruuvi.com/record")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http user: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http pass: ********")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: coordinates: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use company id filter: 1")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: company id: 0x0000")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan coded phy: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan 1mbit/phy: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan extended payload: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 37: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 38: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 39: 0")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_post_ruuvi_malloc_failed) // NOLINT { memset(&g_gateway_config, 0, sizeof(g_gateway_config)); this->m_malloc_fail_on_cnt = 1; const http_server_resp_t resp = http_server_cb_on_post_ruuvi( "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}"); ASSERT_FALSE(this->m_flag_settings_saved_to_flash); ASSERT_FALSE(this->m_flag_settings_sent_to_nrf); ASSERT_FALSE(this->m_flag_settings_ethernet_ip_updated); ASSERT_EQ(HTTP_RESP_CODE_503, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("POST /ruuvi.json")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, string("Failed to parse json or no memory")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_post_ruuvi_json_ok) // NOLINT { const char *expected_resp = "{}"; memset(&g_gateway_config, 0, sizeof(g_gateway_config)); const http_server_resp_t resp = http_server_cb_on_post( "ruuvi.json", "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}"); ASSERT_TRUE(this->m_flag_settings_saved_to_flash); ASSERT_TRUE(this->m_flag_settings_sent_to_nrf); ASSERT_TRUE(this->m_flag_settings_ethernet_ip_updated); ASSERT_EQ(HTTP_RESP_CODE_200, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_FLASH_MEM, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_APPLICATION_JSON, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(strlen(expected_resp), resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_NE(nullptr, resp.select_location.memory.p_buf); ASSERT_EQ(string(expected_resp), string(reinterpret_cast<const char *>(resp.select_location.memory.p_buf))); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, string("POST /ruuvi.json")); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "Got SETTINGS:"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dhcp not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_static_ip not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_netmask not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_gw not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dns1 not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "eth_dns2 not found"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_mqtt: 1"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_server: test.mosquitto.org"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_prefix: ruuvi/30:AE:A4:02:84:A4"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_port: 1883"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_user: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "mqtt_pass: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_http: 0"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_url: https://network.ruuvi.com/record"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_user: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "http_pass: "); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_DEBUG, "use_filtering: 1"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "company_id not found or invalid"); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_ERROR, "coordinates not found"); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("Got SETTINGS from browser:")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use eth dhcp: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth static ip: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth netmask: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth gw: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth dns1: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: eth dns2: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use mqtt: 1")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt server: test.mosquitto.org")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt port: 1883")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt prefix: ruuvi/30:AE:A4:02:84:A4")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt user: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: mqtt password: ********")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use http: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http url: https://network.ruuvi.com/record")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http user: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: http pass: ********")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: coordinates: ")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use company id filter: 1")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: company id: 0x0000")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan coded phy: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan 1mbit/phy: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan extended payload: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 37: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 38: 0")); TEST_CHECK_LOG_RECORD_GW_CFG(ESP_LOG_INFO, string("config: use scan channel 39: 0")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_post_unknown_json) // NOLINT { memset(&g_gateway_config, 0, sizeof(g_gateway_config)); const http_server_resp_t resp = http_server_cb_on_post( "unknown.json", "{" "\"use_mqtt\":true," "\"mqtt_server\":\"test.mosquitto.org\"," "\"mqtt_port\":1883," "\"mqtt_prefix\":\"ruuvi/30:AE:A4:02:84:A4\"," "\"mqtt_user\":\"\"," "\"mqtt_pass\":\"\"," "\"use_http\":false," "\"http_url\":\"https://network.ruuvi.com/record\"," "\"http_user\":\"\"," "\"http_pass\":\"\"," "\"use_filtering\":true" "}"); ASSERT_FALSE(this->m_flag_settings_saved_to_flash); ASSERT_FALSE(this->m_flag_settings_sent_to_nrf); ASSERT_FALSE(this->m_flag_settings_ethernet_ip_updated); ASSERT_EQ(HTTP_RESP_CODE_404, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_WARN, string("POST /unknown.json")); ASSERT_TRUE(esp_log_wrapper_is_empty()); } TEST_F(TestHttpServerCb, http_server_cb_on_delete) // NOLINT { const http_server_resp_t resp = http_server_cb_on_delete("unknown.json"); ASSERT_EQ(HTTP_RESP_CODE_404, resp.http_resp_code); ASSERT_EQ(HTTP_CONTENT_LOCATION_NO_CONTENT, resp.content_location); ASSERT_FALSE(resp.flag_no_cache); ASSERT_EQ(HTTP_CONENT_TYPE_TEXT_HTML, resp.content_type); ASSERT_EQ(nullptr, resp.p_content_type_param); ASSERT_EQ(0, resp.content_len); ASSERT_EQ(HTTP_CONENT_ENCODING_NONE, resp.content_encoding); ASSERT_EQ(nullptr, resp.select_location.memory.p_buf); TEST_CHECK_LOG_RECORD_HTTP_SERVER(ESP_LOG_WARN, string("DELETE /unknown.json")); ASSERT_TRUE(esp_log_wrapper_is_empty()); }
42.572284
118
0.704744
DG12
4084cb54acf621bd5348923cbda12033ef4d6131
2,162
cpp
C++
Source/Physics/Soft/Constraint.cpp
Karshilov/Dorothy-SSR
cce19ed2218d76f941977370f6b3894e2f87236a
[ "MIT" ]
43
2020-01-29T02:22:41.000Z
2021-12-06T04:20:12.000Z
Source/Physics/Soft/Constraint.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
1
2020-03-19T16:23:12.000Z
2020-03-19T16:23:12.000Z
Source/Physics/Soft/Constraint.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
8
2020-03-08T13:46:08.000Z
2021-07-19T11:30:23.000Z
/* Copyright (c) 2021 Jin Li, http://www.luvfight.me 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 "Const/Header.h" #include "Physics/Soft/Constraint.h" #include "Physics/Soft/Particle.h" NS_DOROTHY_BEGIN NS_BEGIN(Soft) Particle* Constraint::getNodeA() const { return _node1; } Particle* Constraint::getNodeB() const { return _node2; } Constraint::Constraint(Particle* p1, Particle* p2, float s, std::optional<float> d): _node1(p1), _node2(p2), _stiff(s) { if (d) { _target = d.value(); } else { _target = std::sqrt(std::pow(p2->getPosition().x - p1->getPosition().x, 2) + std::pow(p2->getPosition().y - p1->getPosition().y, 2)); } } void Constraint::Relax() { Vec2 D = _node2->getPosition() - _node1->getPosition(); Vec2 F = Vec2::normalize(D) * (0.5f * _stiff * (D.length() - _target)); if (F == Vec2::zero) return; if (_node1->getMaterial()->mass > 0 && _node2->getMaterial()->mass == 0) { _node1->ApplyImpulse(F * 2.0f); } else if (_node1->getMaterial()->mass == 0 && _node2->getMaterial()->mass > 0) { _node2->ApplyImpulse(-F * 2.0f); } else { _node1->ApplyImpulse(F); _node2->ApplyImpulse(-F); } } NS_END(Soft) NS_DOROTHY_END
33.78125
463
0.723404
Karshilov
4089df6e2bbd0f9c60fc12835cd4bb8f4a29965c
1,309
cpp
C++
solutions-in-cpp/F-LCS.cpp
fastestmk/atcoder-dp-contest
0a710a87da833ab26af2502b6ee3166aee16cb29
[ "MIT" ]
null
null
null
solutions-in-cpp/F-LCS.cpp
fastestmk/atcoder-dp-contest
0a710a87da833ab26af2502b6ee3166aee16cb29
[ "MIT" ]
null
null
null
solutions-in-cpp/F-LCS.cpp
fastestmk/atcoder-dp-contest
0a710a87da833ab26af2502b6ee3166aee16cb29
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std; #define ll long long const int INF = 1e9+5; int dp[3005][3005]; int main(){ //freopen("tree.in","r",stdin); //freopen("tree.out","w",stdout); //freopen("input.txt", "r", stdin); //freopen("out.txt", "w", stdout); ios_base::sync_with_stdio(0); //cin.tie(0); // diagram from techiedelight string s, t; cin >> s >> t; for(int i = 1; i <= s.size(); ++i){ for(int j = 1; j <= t.size(); ++j){ if(s[i-1] == t[j-1]){ dp[i][j] = dp[i-1][j-1]+1; //cout << i << " " << j << " " << dp[i][j] << endl; } else{ dp[i][j] = max(dp[i][j-1], dp[i-1][j]); //cout << i << " " << j << " " << dp[i][j] << endl; } } } // lcs size //cout << dp[s.size()][t.size()] << endl; int i = s.size(), j = t.size(); string ans; // iterating in reverse while(i && j){ // i >= 1 && j >= 1 if(s[i-1] == t[j-1]){ ans = s[i-1]+ans; // concatinating previous element into last string --i; --j; continue; } if(dp[i-1][j] > dp[i][j-1]) --i; else --j; } cout << ans << endl; }
22.568966
80
0.398014
fastestmk
408d7db4c636089388dba7cccb9d735a7edccd5f
8,581
cpp
C++
src/OpcUaStackServer/ServiceSet/NodeManagementService.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackServer/ServiceSet/NodeManagementService.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackServer/ServiceSet/NodeManagementService.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2015-2017 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h" #include "OpcUaStackCore/Base/Log.h" #include "OpcUaStackServer/ServiceSet/NodeManagementService.h" #include "OpcUaStackServer/AddressSpaceModel/ObjectNodeClass.h" namespace OpcUaStackServer { NodeManagementService::NodeManagementService(void) { } NodeManagementService::~NodeManagementService(void) { } void NodeManagementService::receive(Message::SPtr message) { ServiceTransaction::SPtr serviceTransaction = boost::static_pointer_cast<ServiceTransaction>(message); switch (serviceTransaction->nodeTypeRequest().nodeId<uint32_t>()) { case OpcUaId_AddNodesRequest_Encoding_DefaultBinary: receiveAddNodesRequest(serviceTransaction); break; case OpcUaId_AddReferencesRequest_Encoding_DefaultBinary: receiveAddReferencesRequest(serviceTransaction); break; case OpcUaId_DeleteNodesRequest_Encoding_DefaultBinary: receiveDeleteNodesRequest(serviceTransaction); break; case OpcUaId_DeleteReferencesRequest_Encoding_DefaultBinary: receiveDeleteReferencesRequest(serviceTransaction); break; default: serviceTransaction->statusCode(BadInternalError); serviceTransaction->componentSession()->send(serviceTransaction); } } void NodeManagementService::receiveAddNodesRequest(ServiceTransaction::SPtr serviceTransaction) { OpcUaStatusCode statusCode = Success; ServiceTransactionAddNodes::SPtr trx = boost::static_pointer_cast<ServiceTransactionAddNodes>(serviceTransaction); AddNodesRequest::SPtr addNodesRequest = trx->request(); AddNodesResponse::SPtr addNodesResponse = trx->response(); uint32_t size = addNodesRequest->nodesToAdd()->size(); addNodesResponse->results()->resize(size); Log(Debug, "node management service add nodes request") .parameter("Trx", serviceTransaction->transactionId()) .parameter("NumberNodes", size); for (uint32_t idx=0; idx<size; idx++) { AddNodesResult::SPtr addNodesResult = constructSPtr<AddNodesResult>(); addNodesResponse->results()->set(idx, addNodesResult); AddNodesItem::SPtr addNodesItem; addNodesRequest->nodesToAdd()->get(idx, addNodesItem); statusCode = addNode(idx, addNodesItem, addNodesResult); if (statusCode != Success) break; } serviceTransaction->statusCode(statusCode); serviceTransaction->componentSession()->send(serviceTransaction); } void NodeManagementService::receiveAddReferencesRequest(ServiceTransaction::SPtr serviceTransaction) { // FIXME: serviceTransaction->statusCode(BadInternalError); serviceTransaction->componentSession()->send(serviceTransaction); } void NodeManagementService::receiveDeleteNodesRequest(ServiceTransaction::SPtr serviceTransaction) { // FIXME: serviceTransaction->statusCode(BadInternalError); serviceTransaction->componentSession()->send(serviceTransaction); } void NodeManagementService::receiveDeleteReferencesRequest(ServiceTransaction::SPtr serviceTransaction) { // FIXME: serviceTransaction->statusCode(BadInternalError); serviceTransaction->componentSession()->send(serviceTransaction); } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // add node // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ OpcUaStatusCode NodeManagementService::addNodeAndReference( BaseNodeClass::SPtr baseNodeClass, AddNodesItem::SPtr& addNodesItem ) { bool rc; // set parent node identifier OpcUaNodeId parentNodeId; parentNodeId.namespaceIndex(addNodesItem->parentNodeId()->namespaceIndex()); parentNodeId.nodeIdValue(addNodesItem->parentNodeId()->nodeIdValue()); // find parent node BaseNodeClass::SPtr parentBaseNodeClass = informationModel_->find(parentNodeId); if (parentBaseNodeClass.get() == nullptr) { return BadParentNodeIdInvalid; } // create hierarchical reference rc = parentBaseNodeClass->referenceItemMap().add( *addNodesItem->referenceTypeId(), true, *baseNodeClass->getNodeId() ); if (!rc) return BadReferenceTypeIdInvalid; rc = baseNodeClass->referenceItemMap().add( *addNodesItem->referenceTypeId(), false, *baseNodeClass->getNodeId() ); if (!rc) return BadReferenceTypeIdInvalid; return Success; } OpcUaStatusCode NodeManagementService::addNode(uint32_t pos, BaseNodeClass::SPtr baseNodeClass) { if ((informationModel_->find(baseNodeClass->nodeId().data())).get() != nullptr) { Log(Error, "node already exist") .parameter("Pos", pos) .parameter("BrowseName", baseNodeClass->browseName()); return BadNodeIdExists; } informationModel_->insert(baseNodeClass); return Success; } OpcUaStatusCode NodeManagementService::addNode(uint32_t pos, AddNodesItem::SPtr addNodesItem, AddNodesResult::SPtr addNodesResult) { switch (addNodesItem->nodeClass()->nodeClassType()) { case NodeClassType_Object: return addNodeObject(pos, addNodesItem, addNodesResult); case NodeClassType_Variable: case NodeClassType_Method: case NodeClassType_ObjectType: case NodeClassType_VariableType: case NodeClassType_ReferenceType: case NodeClassType_DataType: case NodeClassType_View: case NodeClassType_Unspecified: case NodeClassType_Dummy: default: { Log(Error, "invalid node class") .parameter("Pos", pos) .parameter("BrowseName", *addNodesItem->browseName()); addNodesResult->statusCode(BadInternalError); } } return Success; } OpcUaStatusCode NodeManagementService::addBaseNodeClass( uint32_t pos, BaseNodeClass::SPtr baseNodeClass, AddNodesItem::SPtr addNodesItem, AddNodesResult::SPtr addNodesResult ) { // // M - NodeId // M - NodeClass // M - BrowseName // M - DisplayName // O - Description // O - WriteMask // O - UserWriteMask // OpcUaNodeId nodeId; nodeId.namespaceIndex(addNodesItem->requestedNewNodeId()->namespaceIndex()); nodeId.nodeIdValue(addNodesItem->requestedNewNodeId()->nodeIdValue()); baseNodeClass->setNodeId(nodeId); NodeClassType nodeClassType = addNodesItem->nodeClass()->nodeClassType(); baseNodeClass->setNodeClass(nodeClassType); baseNodeClass->setBrowseName(*addNodesItem->browseName()); return Success; } OpcUaStatusCode NodeManagementService::addNodeObject( uint32_t pos, AddNodesItem::SPtr addNodesItem, AddNodesResult::SPtr addNodesResult ) { OpcUaStatusCode statusCode; ObjectNodeClass::SPtr objectNodeClass = constructSPtr<ObjectNodeClass>(); // set base attributes statusCode = addBaseNodeClass(pos, objectNodeClass, addNodesItem, addNodesResult); if (statusCode != Success) return statusCode; // get object attributes if (addNodesItem->nodeAttributes().parameterTypeId().nodeId<uint32_t>() != OpcUaId_ObjectAttributes) { Log(Error, "invalid attribute type") .parameter("Pos", pos) .parameter("BrowseName", *addNodesItem->browseName()) .parameter("AttributeType", addNodesItem->nodeAttributes().parameterTypeId().nodeId<uint32_t>()); addNodesResult->statusCode(BadInvalidArgument); return Success; } ObjectAttributes::SPtr objectAttributes = addNodesItem->nodeAttributes().parameter<ObjectAttributes>(); // set additional object attributes objectNodeClass->setDisplayName(*objectAttributes->displayName()); objectNodeClass->setDescription(*objectAttributes->description()); objectNodeClass->setEventNotifier(objectAttributes->eventNotifier()); objectNodeClass->setWriteMask(objectAttributes->writeMask()); objectNodeClass->setUserWriteMask(objectAttributes->userWriteMask()); // added node and reference statusCode = addNodeAndReference(objectNodeClass, addNodesItem); addNodesResult->statusCode(statusCode); return Success; } }
32.381132
116
0.740939
gianricardo
4095e3374b46d2f2a2912652122e45fb204f825b
37,303
cpp
C++
src/c_map.cpp
deadline-cxn/dlstorm
4dec81a71af5f4bbf7daf227c5fd662b9c613e9c
[ "BSD-3-Clause" ]
null
null
null
src/c_map.cpp
deadline-cxn/dlstorm
4dec81a71af5f4bbf7daf227c5fd662b9c613e9c
[ "BSD-3-Clause" ]
null
null
null
src/c_map.cpp
deadline-cxn/dlstorm
4dec81a71af5f4bbf7daf227c5fd662b9c613e9c
[ "BSD-3-Clause" ]
null
null
null
/* Seth's Map Class */ #include "c_map.h" CMapObject::CMapObject() { iType = 0; memset(szName, 0, 32); memset(szDescription, 0, 256); SID = 0; iGFXIndex = 0; iX = 0; iY = 0; iZ = 0; rcMouse.bottom = 0; rcMouse.left = 0; rcMouse.right = 0; rcMouse.top = 0; pNext = NULL; pPrevious = NULL; } ////////////////////////////////////////////////////// CMapObject::~CMapObject() {} ////////////////////////////////////////////////////// CMap::CMap() { Width = 1; Height = 1; SIZE = Width * Height; pMapData = NULL; pItemData = NULL; pNext = NULL; pPrevious = NULL; } CMap::CMap(u_short x, u_short y) { Width = x; Height = y; SIZE = Width * Height; pMapData = NULL; pItemData = NULL; pNext = NULL; pPrevious = NULL; Initialize(x, y, 0, 0); } CMap::CMap(u_short x, u_short y, u_char bank, u_char tile) { Width = x; Height = y; SIZE = Width * Height; pMapData = NULL; pItemData = NULL; pNext = NULL; pPrevious = NULL; Initialize(x, y, bank, tile); } ////////////////////////////////////////////////////// CMap::~CMap() { CleanUp(); } ////////////////////////////////////////////////////// Create a new map, and fill it with a certain tile bool CMap::Initialize(u_short x, u_short y, u_char bank, u_char tile) { CleanUp(); int i; Width = x; Height = y; SIZE = Width * Height; if (pMapData) delete[] pMapData; pMapData = new MAPDATA[SIZE]; if (!pMapData) return false; if (pItemData) delete[] pItemData; pItemData = new ITEMDATA[SIZE]; if (pItemData == NULL) { delete[] pMapData; return false; } for (i = 0; i < SIZE; i++) { pItemData[i].pItem = NULL; pItemData[i].pFirstItem = NULL; pItemData[i].pItem = new CMapObject; pItemData[i].pFirstItem = pItemData[i].pItem; } return true; } ////////////////////////////////////////////////////// Clean up the map data, tile, and object banks void CMap::CleanUp(void) { if (pMapData) { delete[] pMapData; pMapData = NULL; } CMapObject *pHi = NULL; CMapObject *pFirstHi = NULL; int j = 0; if (pItemData) { for (int i = 0; i < SIZE; i++) { if (pItemData[i].pFirstItem) { pItemData[i].pItem = pItemData[i].pFirstItem; while (pItemData[i].pItem) { if (!pFirstHi) { pFirstHi = pItemData[i].pItem; pHi = pFirstHi; } else { pHi->pNext = pItemData[i].pItem; pHi = pHi->pNext; } pItemData[i].pItem = pItemData[i].pItem->pNext; j++; } } } delete[] pItemData; pItemData = NULL; pHi = pFirstHi; while (pHi) { pFirstHi = pHi; pHi = pHi->pNext; DEL(pFirstHi); } } } ////////////////////////////////////////////////////// Load the 3D map... bool CMap::Load3D(char *szFileName) { if (szFileName == NULL) return false; FILE *fp; fp = fopen(szFileName, "rb"); if (fp == NULL) return false; fread(&Width, sizeof(u_short), 1, fp); fread(&Height, sizeof(u_short), 1, fp); SIZE = Width * Height; for (int i = 0; i < SIZE; i++) fread(&pMapData[i], sizeof(MAPDATA), 1, fp); fclose(fp); return true; } ////////////////////////////////////////////////////// Load in a sector bool CMap::LoadSector3D(char *szDir, int iMapX, int iMapY, int iMapZ) { char szFName[1024]; memset(szFName, 0, 1024); sprintf(szFName, "%s%c%d-%d-%d.fm2", szDir, PATH_SEP, iMapX, iMapY, iMapZ); if (!Load3D(szFName)) { Clear(); FillRandom(0, 1, 1, 60); if (!Save3D(szFName)) return false; } return true; } ////////////////////////////////////////////////////// Save the 3D map... bool CMap::Save3D(char *szFilename) { FILE *fp; fp = fopen(szFilename, "wb"); if (fp == NULL) return false; fwrite(&Width, sizeof(u_short), 1, fp); fwrite(&Height, sizeof(u_short), 1, fp); SIZE = Width * Height; for (int i = 0; i < SIZE; i++) fwrite(&pMapData[i], sizeof(MAPDATA), 1, fp); fclose(fp); return true; } ////////////////////////////////////////////////////// Save a 3D sector bool CMap::SaveSector3D(char *szDir, int iMapX, int iMapY, int iMapZ) { char szFName[1024]; memset(szFName, 0, 1024); dlcs_mkdir(szDir); sprintf(szFName, "%s%c%d-%d-%d.fm2", szDir, PATH_SEP, iMapX, iMapY, iMapZ); return (Save3D(szFName)); } ////////////////////////////////////////////////////// Get the map's width u_short CMap::GetWidth(void) { return Width; } ////////////////////////////////////////////////////// Get the map's height u_short CMap::GetHeight(void) { return Height; } ////////////////////////////////////////////////////// Clear the map data void CMap::Clear(void) { ClearTiles(); ClearObjects(); ClearProperties(); ClearVertexHeights(); ClearVertexWidths(); ClearVertexColors(255, 255, 255); } ////////////////////////////////////////////////////// Clear the item data void CMap::ClearItems(void) { // int i; // for(i=0;i<SIZE;i++) { //pItemData[i].pItem->bClear(); } } ////////////////////////////////////////////////////// Returns the tile information at (X,Y) in the format of: u_short (LOu_char = Bank / HIu_char = Tile) int CMap::GetTile(int x, int y) { return GetTile(x + y * Width); } int CMap::GetTile(int dt) { if ((dt < 0) || (dt > SIZE)) return 0; return pMapData[dt].iTile; } ////////////////////////////////////////////////////// Sets the tile data for the maptile at (X,Y) void CMap::SetTile(int x, int y, u_char bank, u_char tile) { SetTile(x + y * Width, bank, tile); } void CMap::SetTile(int dt, u_char bank, u_char tile) { if (!pMapData) return; if ((dt < 0) || (dt > SIZE)) return; pMapData[dt].iTile = (bank << 8) + tile; } ////////////////////////////////////////////////////// Fill the map with a certain tile void CMap::FillTiles(u_char bank, u_char tile) { SIZE = Width * Height; u_short t = (bank << 8) + tile; for (int i = 0; i < SIZE; i++) { pMapData[i].iTile = t; } } ////////////////////////////////////////////////////// void CMap::FillRandom(u_char blow, u_char bhi, u_char tlow, u_char thi) { for (int dt = 0; dt < SIZE; dt++) SetTile(dt, rand() % bhi + blow, rand() % thi + tlow); } ////////////////////////////////////////////////////// Clear all objects from a map tilespace void CMap::ClearTiles(void) { FillTiles(0, 0); } ////////////////////////////////////////////////////// Returns the object information at (X,Y,level) in the format of: unsigned short CMap::GetObj(int x, int y, int priority) { return GetObj(x + y * Width, priority); } unsigned short CMap::GetObj(int dt, int priority) { if ((dt < 0) || (dt > SIZE)) return 0; return (pMapData[dt].Object[priority].cBank << 8) + (pMapData[dt].Object[priority].cObject); } ////////////////////////////////////////////////////// Sets the object at x,y using priority void CMap::SetObj(int x, int y, u_char bank, u_char object, u_char priority) { SetObj(x + y * Width, bank, object, priority); } void CMap::SetObj(int dt, u_char bank, u_char object, u_char priority) { if ((dt < 0) || (dt > SIZE)) return; pMapData[dt].Object[priority].cBank = bank; pMapData[dt].Object[priority].cObject = object; } ////////////////////////////////////////////////////// Clear all objects from a map tilespace void CMap::ClearObjects(void) { for (int dt = 0; dt < SIZE; dt++) { for (int pp = 0; pp < GMP_OBJECT_LAYERS; pp++) { SetObj(dt, GMP_NO_OBJECT, GMP_NO_OBJECT, pp); } } } ////////////////////////////////////////////////////// Clears map properties void CMap::ClearProperties(void) { for (int dt = 0; dt < SIZE; dt++) { pMapData[dt].cProperties = (u_char)NULL; pMapData[dt].cProperties2 = (u_char)NULL; pMapData[dt].cProperties3 = (u_char)NULL; pMapData[dt].cProperties4 = (u_char)NULL; } } ////////////////////////////////////////////////////// Get map properties u_short CMap::cGetProperties(int x, int y) { return pMapData[y * Width + x].cProperties; } u_short CMap::cGetProperties(int dt) { if ((dt < 0) || (dt > SIZE)) return 0; return pMapData[dt].cProperties; } ////////////////////////////////////////////////////// Set map properties (precalculated) ////////////////////////////////////////////////////// Set map properties void CMap::SetProperties(int x, int y, u_short cProperties) { SetProperties(y * Width + x, cProperties); } void CMap::SetProperties(int dt, u_short cProperties) { if ((dt < 0) || (dt > SIZE)) return; pMapData[dt].cProperties = cProperties; } ////////////////////////////////////////////////////// bool CMap::GetProperty(int x, int y, u_short prp) { return GetProperty((y * Width + x), prp); } bool CMap::GetProperty(int dt, u_short prp) { if ((dt < 0) || (dt > SIZE)) return 0; return dlcsm_tobool(pMapData[dt].cProperties & prp); } ////////////////////////////////////////////////////// void CMap::SetProperty(int x, int y, u_short prp, bool yesno) { SetProperty((y * Width + x), prp, yesno); } void CMap::SetProperty(int dt, u_short prp, bool yesno) { if ((dt < 0) || (dt > SIZE)) return; if (yesno) pMapData[dt].cProperties |= prp; else pMapData[dt].cProperties = (pMapData[dt].cProperties & (GMP_PROPERTY_MASK - prp)); } ////////////////////////////////////////////////////// void CMap::FillBlocked(bool bBlocked) { for (int dt = 0; dt < SIZE; dt++) { SetProperty(dt, GMP_PROPERTY_BLOCKED, bBlocked); } } ////////////////////////////////////////////////////// void CMap::FillLiquid(bool bLiquid) { for (int dt = 0; dt < SIZE; dt++) { SetProperty(dt, GMP_PROPERTY_LIQUID, bLiquid); } } ////////////////////////////////////////////////////// Get Vertex Height float CMap::GetVertexHeight(u_char cX, u_char cY, u_char cVertex) { return pMapData[cX + cY * Width].Vertex[cVertex].Height; } float CMap::GetVertexHeight(int dt, u_char cVertex) { if (cVertex > 3) return 0; if ((dt < 0) || (dt > SIZE)) return 0; return pMapData[dt].Vertex[cVertex].Height; } ////////////////////////////////////////////////////// void CMap::SetSingleVertexHeight(u_char cX, u_char cY, u_char cVertex, float cHeight) { SetSingleVertexHeight(cX + cY * Width, cVertex, cHeight); } void CMap::SetSingleVertexHeight(int dt, u_char cVertex, float cHeight) { if (cVertex > 3) return; if ((dt < 0) || (dt > SIZE)) return; pMapData[dt].Vertex[cVertex].Height = cHeight; } ////////////////////////////////////////////////////// Set Vertex Height void CMap::SetVertexHeight(u_char cX, u_char cY, u_char cVertex, float cHeight) { SetVertexHeight((cX + cY * Width), cVertex, cHeight); } void CMap::SetVertexHeight(int dt, u_char cVertex, float cHeight) { int dta; int i = dt; if ((dt < 0) || (dt > SIZE)) return; switch (cVertex) { case 0: dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = cHeight; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = cHeight; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = cHeight; dta = i + 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = cHeight; break; case 1: dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = cHeight; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = cHeight; dta = i - 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = cHeight; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = cHeight; break; case 2: dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = cHeight; dta = i - 1 - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = cHeight; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = cHeight; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = cHeight; break; case 3: dta = i - Width + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = cHeight; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = cHeight; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = cHeight; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = cHeight; break; default: break; } } ////////////////////////////////////////////////////// void CMap::SmoothHeights(void) { int dta; float vx; for (int i = (Width * 2); i < (SIZE - Width * 2); i++) { for (int vertex = 0; vertex < 4; vertex++) { switch (vertex) { case 0: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[0].Height; dta = i + Width; vx += pMapData[dta].Vertex[0].Height; dta = i + 1; vx += pMapData[dta].Vertex[0].Height; dta = i - Width; vx += pMapData[dta].Vertex[0].Height; vx /= 4; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = vx; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = vx; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = vx; dta = i + 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = vx; } break; case 1: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[1].Height; dta = i + Width; vx += pMapData[dta].Vertex[1].Height; dta = i + 1; vx += pMapData[dta].Vertex[1].Height; dta = i - Width; vx += pMapData[dta].Vertex[1].Height; vx /= 4; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = vx; dta = i - 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = vx; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = vx; } break; case 2: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[2].Height; dta = i + Width; vx += pMapData[dta].Vertex[2].Height; dta = i + 1; vx += pMapData[dta].Vertex[2].Height; dta = i - Width; vx += pMapData[dta].Vertex[2].Height; vx /= 4; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = vx; dta = i - 1 - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = vx; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = vx; } break; case 3: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[3].Height; dta = i - 1; vx += pMapData[dta].Vertex[3].Height; dta = i - Width; vx += pMapData[dta].Vertex[3].Height; dta = i + Width; vx += pMapData[dta].Vertex[3].Height; vx /= 4; dta = i - Width + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Height = vx; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Height = vx; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Height = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Height = vx; } break; default: break; } } } } ////////////////////////////////////////////////////// void CMap::SmoothWidths(void) { int dta; float vx; for (int i = (Width * 2); i < (SIZE - Width * 2); i++) { for (int vertex = 0; vertex < 4; vertex++) { switch (vertex) { case 0: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[0].Width; dta = i + Width; vx += pMapData[dta].Vertex[0].Width; dta = i + 1; vx += pMapData[dta].Vertex[0].Width; dta = i - Width; vx += pMapData[dta].Vertex[0].Width; vx /= 4; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = vx; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = vx; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = vx; dta = i + 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = vx; } break; case 1: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[1].Width; dta = i + Width; vx += pMapData[dta].Vertex[1].Width; dta = i + 1; vx += pMapData[dta].Vertex[1].Width; dta = i - Width; vx += pMapData[dta].Vertex[1].Width; vx /= 4; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = vx; dta = i - 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = vx; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = vx; } break; case 2: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[2].Width; dta = i + Width; vx += pMapData[dta].Vertex[2].Width; dta = i + 1; vx += pMapData[dta].Vertex[2].Width; dta = i - Width; vx += pMapData[dta].Vertex[2].Width; vx /= 4; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = vx; dta = i - 1 - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = vx; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = vx; } break; case 3: dta = i; if ((dta > 0) && (dta < SIZE)) { vx = pMapData[dta].Vertex[3].Width; dta = i - 1; vx += pMapData[dta].Vertex[3].Width; dta = i - Width; vx += pMapData[dta].Vertex[3].Width; dta = i + Width; vx += pMapData[dta].Vertex[3].Width; vx /= 4; dta = i - Width + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = vx; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = vx; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = vx; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = vx; } break; default: break; } } } } ////////////////////////////////////////////////////// Get Vertex Width float CMap::GetVertexWidth(u_char cX, u_char cY, u_char cVertex) { return GetVertexWidth(cX + cY * Width, cVertex); } float CMap::GetVertexWidth(int dt, u_char cVertex) { if ((dt > 0) || (dt < SIZE)) return pMapData[dt].Vertex[cVertex].Width; return 0.0f; } ////////////////////////////////////////////////////// void CMap::SetSingleVertexWidth(u_char cX, u_char cY, u_char cVertex, float cWidth) { SetSingleVertexWidth(cX + cY * Width, cVertex, cWidth); } void CMap::SetSingleVertexWidth(int dt, u_char cVertex, float cWidth) { if (cVertex > 3) return; if ((dt < 0) || (dt > SIZE)) return; pMapData[dt].Vertex[cVertex].Width = cWidth; } ////////////////////////////////////////////////////// Set Vertex Width void CMap::SetVertexWidth(u_char cX, u_char cY, u_char cVertex, float cWidth) { SetVertexWidth(cX + cY * Width, cVertex, cWidth); } void CMap::SetVertexWidth(int dt, u_char cVertex, float cWidth) { if (cVertex > 3) return; int dta; int i = dt; switch (cVertex) { case 0: dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = cWidth; dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = cWidth; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = cWidth; dta = i + 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = cWidth; break; case 1: dta = i + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = cWidth; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = cWidth; dta = i - 1 + Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = cWidth; dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = cWidth; break; case 2: dta = i - 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = cWidth; dta = i - 1 - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = cWidth; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = cWidth; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = cWidth; break; case 3: dta = i - Width + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[1].Width = cWidth; dta = i + 1; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[2].Width = cWidth; dta = i - Width; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[0].Width = cWidth; dta = i; if ((dta > 0) && (dta < SIZE)) pMapData[dta].Vertex[3].Width = cWidth; break; default: break; } } ////////////////////////////////////////////////////// Clear Vertex Heights void CMap::ClearVertexHeights(void) { for (int dt = 0; dt < SIZE; dt++) { for (int v = 0; v < 4; v++) { pMapData[dt].Vertex[v].Height = 0.0f; } } } ////////////////////////////////////////////////////// Clear Vertex Widths void CMap::ClearVertexWidths(void) { for (int dt = 0; dt < SIZE; dt++) { for (int v = 0; v < 4; v++) { pMapData[dt].Vertex[v].Width = 0.0f; } } } ////////////////////////////////////////////////////// float CMap::GetVertexColorR(u_char cX, u_char cY, u_char cVertex) { if (cVertex > 3) return 0; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return 0; return pMapData[cX + cY * Width].Vertex[cVertex].R; } ////////////////////////////////////////////////////// float CMap::GetVertexColorG(u_char cX, u_char cY, u_char cVertex) { if (cVertex > 3) return 0; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return 0; return pMapData[cX + cY * Width].Vertex[cVertex].G; } ////////////////////////////////////////////////////// float CMap::GetVertexColorB(u_char cX, u_char cY, u_char cVertex) { if (cVertex > 3) return 0; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return 0; return pMapData[cX + cY * Width].Vertex[cVertex].B; } ////////////////////////////////////////////////////// void CMap::SetSingleVertexColor(u_char cX, u_char cY, u_char cVertex, u_long dwColor) { if (cVertex > 3) return; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return; SetSingleVertexColor(cX, cY, cVertex, (float)((dwColor & 255) / 255), (float)(((dwColor >> 8) & 255) / 255), (float)(((dwColor >> 16) & 255)) / 255); } ////////////////////////////////////////////////////// void CMap::SetSingleVertexColor(u_char cX, u_char cY, u_char cVertex, float cRed, float cGreen, float cBlue) { if (cVertex > 3) return; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return; pMapData[cX + cY * Width].Vertex[cVertex].R = cRed; pMapData[cX + cY * Width].Vertex[cVertex].G = cGreen; pMapData[cX + cY * Width].Vertex[cVertex].B = cBlue; } ////////////////////////////////////////////////////// Set vertex color (proper) void CMap::SetVertexColor(u_char cX, u_char cY, u_char cVertex, float cR, float cG, float cB) { if (cVertex > 3) return; if ((cX + cY * SIZE < 0) || (cX + cY * Width > SIZE)) return; int dta; int i = cX + cY * Width; switch (cVertex) { case 0: dta = i; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[0].R = cR; pMapData[dta].Vertex[0].G = cG; pMapData[dta].Vertex[0].B = cB; } dta = i + Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[3].R = cR; pMapData[dta].Vertex[3].G = cG; pMapData[dta].Vertex[3].B = cB; } dta = i + 1; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[1].R = cR; pMapData[dta].Vertex[1].G = cG; pMapData[dta].Vertex[1].B = cB; } dta = i + 1 + Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[2].R = cR; pMapData[dta].Vertex[2].G = cG; pMapData[dta].Vertex[2].B = cB; } break; case 1: dta = i + Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[2].R = cR; pMapData[dta].Vertex[2].G = cG; pMapData[dta].Vertex[2].B = cB; } dta = i; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[1].R = cR; pMapData[dta].Vertex[1].G = cG; pMapData[dta].Vertex[1].B = cB; } dta = i - 1 + Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[3].R = cR; pMapData[dta].Vertex[3].G = cG; pMapData[dta].Vertex[3].B = cB; } dta = i - 1; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[0].R = cR; pMapData[dta].Vertex[0].G = cG; pMapData[dta].Vertex[0].B = cB; } break; case 2: dta = i - 1; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[3].R = cR; pMapData[dta].Vertex[3].G = cG; pMapData[dta].Vertex[3].B = cB; } dta = i - 1 - Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[0].R = cR; pMapData[dta].Vertex[0].G = cG; pMapData[dta].Vertex[0].B = cB; } dta = i; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[2].R = cR; pMapData[dta].Vertex[2].G = cG; pMapData[dta].Vertex[2].B = cB; } dta = i - Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[1].R = cR; pMapData[dta].Vertex[1].G = cG; pMapData[dta].Vertex[1].B = cB; } break; case 3: dta = i - Width + 1; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[1].R = cR; pMapData[dta].Vertex[1].G = cG; pMapData[dta].Vertex[1].B = cB; } dta = i + 1; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[2].R = cR; pMapData[dta].Vertex[2].G = cG; pMapData[dta].Vertex[2].B = cB; } dta = i - Width; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[0].R = cR; pMapData[dta].Vertex[0].G = cG; pMapData[dta].Vertex[0].B = cB; } dta = i; if ((dta > 0) && (dta < SIZE)) { pMapData[dta].Vertex[3].R = cR; pMapData[dta].Vertex[3].G = cG; pMapData[dta].Vertex[3].B = cB; } break; default: break; } } ////////////////////////////////////////////////////// void CMap::SetVertexColor(u_char cX, u_char cY, u_char cVertex, u_long dwColor) { SetVertexColor(cX, cY, cVertex, (float)((float(dwColor & 255)) / 255.0f), (float)((float((dwColor >> 8) & 255)) / 255.0f), (float)((float((dwColor >> 16) & 255)) / 255.0f)); } ////////////////////////////////////////////////////// void CMap::ClearVertexColors(void) { ClearVertexColors(1.0f, 1.0f, 1.0f); } ////////////////////////////////////////////////////// void CMap::ClearVertexColors(float cRed, float cGreen, float cBlue) { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { for (int v = 0; v < 4; v++) { pMapData[x + y * Width].Vertex[v].R = cRed; pMapData[x + y * Width].Vertex[v].G = cGreen; pMapData[x + y * Width].Vertex[v].B = cBlue; } } } } ////////////////////////////////////////////////////// Move the map draw area to (X,Y) void CMap::MoveTo(int x, int y) { X = x; Y = y; } ////////////////////////////////////////////////////// Move the map draw area to (X,Y,Z) void CMap::MoveTo(int x, int y, int z) { X = x; Y = y; Z = z; } ////////////////////////////////////////////////////// Get the X coordinate of the map int CMap::GetX(void) { return X; } ////////////////////////////////////////////////////// Set just the X coordinate of the map void CMap::SetX(int x) { X = x; } ////////////////////////////////////////////////////// Get the Y coordinate of the map int CMap::GetY(void) { return Y; } ////////////////////////////////////////////////////// Set just the Y coordinate of the map void CMap::SetY(int y) { Y = y; } ////////////////////////////////////////////////////// Get the Z coordinate of the map int CMap::GetZ(void) { return Z; } ////////////////////////////////////////////////////// Set the Z coordinate of the map void CMap::SetZ(int z) { Z = z; } ////////////////////////////////////////////////////// Teleport Class CTeleport::CTeleport() { bClear(); } ////////////////////////////////////////////////////// CTeleport::~CTeleport() {} ////////////////////////////////////////////////////// bool CTeleport::bClear(void) { strcpy(szName, "UNK_TELEPORT"); strcpy(szDestName, "UNK_TELEPORT"); iSourceX = NOT_A_TELEPORT; iSourceY = NOT_A_TELEPORT; iSourceZ = NOT_A_TELEPORT; iDestinationX = NOT_A_TELEPORT; iDestinationY = NOT_A_TELEPORT; iDestinationZ = NOT_A_TELEPORT; iKey = NOT_A_TELEPORT; pNext = NULL; pPrevious = NULL; return true; } ////////////////////////////////////////////////////// bool CTeleport::bLoad(char *FileName) { char *szEntry; char In[256]; FILE *fp; fp = fopen(FileName, "rt"); if (!fp) return false; strcpy(szName, "UNK_TELEPORT"); strcpy(szDestName, "UNK_TELEPORT"); while (1) { if (!fgets(In, 255, fp)) break; szEntry = strtok(In, "=\n\r"); if (szEntry != NULL) { if (!strcmp(szEntry, "SRC_NAME")) { szEntry = strtok(NULL, ",\n\r"); if (szEntry) { strcpy(szName, szEntry); } } if (!strcmp(szEntry, "SRC")) { szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iSourceX = atoi(szEntry); szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iSourceY = atoi(szEntry); szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iSourceZ = atoi(szEntry); } } } } if (!strcmp(szEntry, "DST_NAME")) { szEntry = strtok(NULL, ",\n\r"); if (szEntry) { strcpy(szDestName, szEntry); } } if (!strcmp(szEntry, "DST")) { szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iDestinationX = atoi(szEntry); szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iDestinationY = atoi(szEntry); szEntry = strtok(NULL, ",\n\r"); if (szEntry != NULL) { iDestinationZ = atoi(szEntry); } } } } } } fclose(fp); return true; } ////////////////////////////////////////////////////// bool CTeleport::bSave(char *szFileName) { char szTemp[256]; FILE *fp; fp = fopen(szFileName, "wt"); if (!fp) return false; sprintf(szTemp, "SRC_NAME=%s", szName); fputs(szTemp, fp); sprintf(szTemp, "SRC=%d,%d,%d\n", iSourceX, iSourceY, iSourceZ); fputs(szTemp, fp); sprintf(szTemp, "DST_NAME=%s", szDestName); fputs(szTemp, fp); sprintf(szTemp, "DST=%d,%d,%d\n", iDestinationX, iDestinationY, iDestinationZ); fputs(szTemp, fp); fclose(fp); return true; } //////////////////////////////////////////////////////
39.557794
257
0.420449
deadline-cxn
409670dfebcd2a626c9a93d0fc89755aab2877a1
2,689
cc
C++
processors/IA32/bochs/bios/usage.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
445
2016-06-30T08:19:11.000Z
2022-03-28T06:09:49.000Z
processors/IA32/bochs/bios/usage.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
439
2016-06-29T20:14:36.000Z
2022-03-17T19:59:58.000Z
processors/IA32/bochs/bios/usage.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
137
2016-07-02T17:32:07.000Z
2022-03-20T11:17:25.000Z
///////////////////////////////////////////////////////////////////////// // $Id: usage.cc,v 1.4 2003/10/07 01:44:34 danielg4 Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> unsigned char bios[65536]; int main(int argc, char *argv[]) { int bios_file; FILE * org_file; unsigned org, last_org, offset; int retval; unsigned int to_read, index; double elements, ratio; if (argc !=3 ) { fprintf(stderr, "Usage: usage bios-file org-file\n"); exit(1); } bios_file = open(argv[1], O_RDONLY); org_file = fopen(argv[2], "r"); if ( (bios_file<0) | (org_file==NULL) ) { fprintf(stderr, "problems opening files.\n"); exit(1); } printf("files opened OK\n"); to_read = 65536; index = 0; while (to_read > 0) { retval = read(bios_file, &bios[index], to_read); if (retval <= 0) { fprintf(stderr, "problem reading bios file\n"); exit(1); } to_read -= retval; index += retval; } printf("bios file read in OK\n"); last_org = 0; while (1) { retval = fscanf(org_file, "0x%x\n", &org); if (retval <= 0) break; printf("%04x .. %04x ", last_org, org-1); for (offset=org-1; offset>last_org; offset--) { if (bios[offset] != 0) break; } if (offset > last_org) { elements = (1.0 + double(offset) - double(last_org)); } else { if (bios[last_org] == 0) elements = 0.0; else elements = 1.0; } ratio = elements / (double(org) - double(last_org)); ratio *= 100.0; printf("%6.2lf\n", ratio); last_org = org; } }
26.89
76
0.586463
bavison
409737a2d1130201d399d379151c0943329aa0c6
8,916
cpp
C++
miniapps/pnp/EAFE_SUPG_advection_diffusion/adv_diff_3D.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
1
2020-04-28T05:08:24.000Z
2020-04-28T05:08:24.000Z
miniapps/pnp/EAFE_SUPG_advection_diffusion/adv_diff_3D.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
null
null
null
miniapps/pnp/EAFE_SUPG_advection_diffusion/adv_diff_3D.cpp
fanronghong/mfem
5bc8d5ea1b7e3a0b377423773e78428bf7160612
[ "BSD-3-Clause" ]
null
null
null
/* * 参考文献 * [1] a monotone finite element scheme for convection-diffusion equations * * -\nabla\cdot(\alpha \nabla u + \beta u) = f, in \Omega, * u = u_D, on \partial\Omega */ #include <string> #include <iostream> #include "mfem.hpp" #include "adv_diff_3D.hpp" #include "../utils/mfem_utils.hpp" #include "../utils/SUPG_Integrator.hpp" #include "../utils/EAFE_ModifyStiffnessMatrix.hpp" using namespace std; using namespace mfem; void EAFE_advec_diffu(Mesh& mesh, Array<double>& L2norms, Array<double>& meshsizes) { int dim = mesh.Dimension(); H1_FECollection h1_fec(p_order, dim); FiniteElementSpace h1_space(&mesh, &h1_fec); Array<int> ess_tdof_list; Array<int> ess_bdr(mesh.bdr_attributes.Max()); if (mesh.bdr_attributes.Size()) { ess_bdr = 1; h1_space.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } LinearForm lf(&h1_space); lf.AddDomainIntegrator(new DomainLFIntegrator(analytic_rhs_)); lf.Assemble(); BilinearForm blf(&h1_space); //EAFE基本的刚度矩阵只需要Poisson方程,后面修改的就是这个Poisson方程的刚度矩阵,参考[1],(3.24)式 blf.AddDomainIntegrator(new DiffusionIntegrator); // (grad(u), grad(v)) blf.Assemble(0); blf.Finalize(0); GridFunction uh(&h1_space); uh.ProjectCoefficient(analytic_solution_);//使得uh满足边界条件,必须 SparseMatrix& A = blf.SpMat(); Vector &b=lf; EAFE_Modify(mesh, A, DiffusionTensor, AdvectionVector); blf.EliminateVDofs(ess_tdof_list, uh, lf); if (EAFE_Only_Dump_data) { cout << "number of mesh nodes: \n" << mesh.GetNV() << endl; GridFunction u_exact(&h1_space); u_exact.ProjectCoefficient(analytic_solution_); // WriteVector("u_exact_eafe.txt", u_exact); // WriteCSR("A_eafe.txt", A); // WriteVector("b_eafe.txt", b); BinaryWriteVector("u_exact_eafe.bin", u_exact); BinaryWriteCSR("A_eafe.bin", A); BinaryWriteVector("b_eafe.bin", b); return; } GMRESSolver solver; solver.SetOperator(A); solver.SetAbsTol(gmres_atol); solver.SetRelTol(gmres_rtol); solver.SetPrintLevel(gmres_printlevel); solver.SetMaxIter(gmres_maxiter); Vector x(lf.Size()); solver.Mult(b, x); if (!solver.GetConverged()) throw "GMRES solver not converged!"; uh = x; { VisItDataCollection uh_dc("uh for EAFE", &mesh); uh_dc.RegisterField("value", &uh); Visualize(uh_dc, "value"); Wx += offx; } double l2norm = uh.ComputeL2Error(analytic_solution_); L2norms.Append(l2norm); double totle_size = 0.0; for (int i=0; i<mesh.GetNE(); i++) { totle_size += mesh.GetElementSize(0, 1); } meshsizes.Append(totle_size / mesh.GetNE()); } void SUPG_advec_diffu(Mesh& mesh, Array<double>& L2norms, Array<double>& meshsizes) { int dim = mesh.Dimension(); FiniteElementCollection *fec = new H1_FECollection(p_order, dim); FiniteElementSpace *fespace = new FiniteElementSpace(&mesh, fec); Array<int> ess_tdof_list; Array<int> ess_bdr(mesh.bdr_attributes.Max()); if (mesh.bdr_attributes.Size()) { ess_bdr = 1; //标记所有的边界都为essential boundary fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } LinearForm *lf = new LinearForm(fespace); lf->AddDomainIntegrator(new DomainLFIntegrator(analytic_rhs_)); // (f, v) lf->AddDomainIntegrator(new SUPG_LinearFormIntegrator(diffusion_tensor, advection_vector, one, analytic_rhs_, mesh)); lf->Assemble(); BilinearForm *blf = new BilinearForm(fespace); blf->AddDomainIntegrator(new DiffusionIntegrator(diffusion_tensor)); // (alpha grad(u), grad(v)) blf->AddDomainIntegrator(new ConvectionIntegrator(advection_vector, -1.0)); // -(beta \cdot grad(u), v) blf->AddDomainIntegrator(new MassIntegrator(neg_div_advection_)); // (-div(beta) u, v) blf->AddDomainIntegrator(new SUPG_BilinearFormIntegrator(&diffusion_tensor, neg, advection_vector, neg, div_adv, mesh)); blf->Assemble(0); // { // SparseMatrix temp(blf->SpMat()); // temp.Print(cout << std::setprecision(3) << "3D SUPG stiffness matrix (before apply bdc)\n"); // PrintSparsePattern(temp, "3D SUPG stiffness matrix"); // } GridFunction uh(fespace); // uh.ProjectCoefficient(analytic_solution_); uh.ProjectBdrCoefficient(analytic_solution_, ess_bdr); //两种加边界条件的方式 blf->EliminateEssentialBC(ess_bdr, uh, *lf); blf->Finalize(1); SparseMatrix &A = blf->SpMat(); if (SUPG_Only_Dump_data) { cout << "number of mesh nodes: \n" << mesh.GetNV() << endl; GridFunction u_exact(fespace); u_exact.ProjectCoefficient(analytic_solution_); BinaryWriteVector("u_exact_supg.bin", u_exact); BinaryWriteCSR("A_supg.bin", A); BinaryWriteVector("b_supg.bin", *lf); return; } GMRESSolver solver; solver.SetOperator(A); solver.SetAbsTol(gmres_atol); solver.SetRelTol(gmres_rtol); solver.SetPrintLevel(gmres_printlevel); solver.SetMaxIter(gmres_maxiter); Vector x(lf->Size()); solver.Mult(*lf, x); if (!solver.GetConverged()) MFEM_ABORT("GMRES solver not converged!"); uh = x; double l2norm = uh.ComputeL2Error(analytic_solution_); L2norms.Append(l2norm); double totle_size = 0.0; for (int i=0; i<mesh.GetNE(); i++) { totle_size += mesh.GetElementSize(0, 1); } meshsizes.Append(totle_size / mesh.GetNE()); // 11. Free the used memory. delete blf; delete lf; delete fespace; delete fec; } void advec_diffu(Mesh& mesh, Array<double>& L2norms, Array<double>& meshsizes) { int dim = mesh.Dimension(); H1_FECollection h1_fec(p_order, dim); FiniteElementSpace h1_space(&mesh, &h1_fec); Array<int> ess_tdof_list; if (mesh.bdr_attributes.Size()) { Array<int> ess_bdr(mesh.bdr_attributes.Max()); ess_bdr = 1; h1_space.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } LinearForm lf(&h1_space); lf.AddDomainIntegrator(new DomainLFIntegrator(analytic_rhs_)); // (f, v) lf.Assemble(); BilinearForm blf(&h1_space); blf.AddDomainIntegrator(new DiffusionIntegrator(diffusion_tensor)); // (alpha * grad(u), grad(v)) blf.AddDomainIntegrator(new ConvectionIntegrator(advection_vector, -1.0)); // -(beta * grad(u), v) blf.AddDomainIntegrator(new MassIntegrator(neg_div_advection_)); // (-div(beta)u, v). 扩散速度不是divergence free的 blf.Assemble(); GridFunction uh(&h1_space); uh.ProjectCoefficient(analytic_solution_); SparseMatrix A; Vector x, b; blf.FormLinearSystem(ess_tdof_list, uh, lf, A, x, b); GMRESSolver solver; solver.SetOperator(A); solver.SetAbsTol(gmres_atol); solver.SetRelTol(gmres_rtol); solver.SetPrintLevel(gmres_printlevel); solver.SetMaxIter(gmres_maxiter); solver.Mult(b, x); if (!solver.GetConverged()) throw("GMRES solver not converged!"); uh = x; { VisItDataCollection uh_dc("uh for FEM", &mesh); uh_dc.RegisterField("value", &uh); Visualize(uh_dc, "value"); Wx += offx; } double l2norm = uh.ComputeL2Error(analytic_solution_); L2norms.Append(l2norm); double totle_size = 0.0; for (int i=0; i<mesh.GetNE(); i++) { totle_size += mesh.GetElementSize(0, 1); } meshsizes.Append(totle_size / mesh.GetNE()); } int main(int args, char **argv) { if (Run_SUPG) { Mesh mesh(mesh_file, 1, 1); Array<double> L2norms; Array<double> meshsizes; for (int i=0; i<refine_times; i++) { mesh.UniformRefinement(); SUPG_advec_diffu(mesh, L2norms, meshsizes); } // SUPG_advec_diffu(mesh, L2norms, meshsizes); Array<double> rates = compute_convergence(L2norms, meshsizes); rates.Print(cout << "SUPG convergence rate: \n", rates.Size()); } if (Run_EAFE) { Mesh mesh(mesh_file, 1, 1); Array<double> L2norms; Array<double> meshsizes; for (int i=0; i<refine_times; i++) { mesh.UniformRefinement(); EAFE_advec_diffu(mesh, L2norms, meshsizes); } // EAFE_advec_diffu(mesh, L2norms, meshsizes); Array<double> rates = compute_convergence(L2norms, meshsizes); rates.Print(cout << "EAFE convergence rate: \n", rates.Size()); } if (Run_FEM) { Mesh mesh(mesh_file, 1, 1); Array<double> L2norms; Array<double> meshsizes; for (int i=0; i<refine_times; i++) { mesh.UniformRefinement(); advec_diffu(mesh, L2norms, meshsizes); } // advec_diffu(mesh, L2norms, meshsizes); Array<double> rates = compute_convergence(L2norms, meshsizes); rates.Print(cout << "FEM convergence rate: \n", rates.Size()); } return 0; }
30.851211
124
0.647712
fanronghong
409a771e84a5e930a1acbdac2ab73d096773b33d
12,524
cpp
C++
src/TRTexture2D.cpp
ZeusYang/TinySoftRenderer
16ed454beb231e3585f218158b41cd37387b7d13
[ "MIT" ]
70
2021-03-19T14:19:45.000Z
2022-03-26T12:43:16.000Z
src/TRTexture2D.cpp
yanwc/Soft-Renderer
16ed454beb231e3585f218158b41cd37387b7d13
[ "MIT" ]
1
2021-03-18T11:57:51.000Z
2021-03-18T11:57:51.000Z
src/TRTexture2D.cpp
yanwc/Soft-Renderer
16ed454beb231e3585f218158b41cd37387b7d13
[ "MIT" ]
12
2021-03-19T14:19:46.000Z
2022-03-21T15:53:27.000Z
#include "TRTexture2D.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "TRParallelWrapper.h" #include <iostream> namespace TinyRenderer { //----------------------------------------------TRTexture2D---------------------------------------------- TRTexture2D::TRTexture2D() : m_generateMipmap(false), m_warpMode(TRTextureWarpMode::TR_MIRRORED_REPEAT), m_filteringMode(TRTextureFilterMode::TR_LINEAR) {} TRTexture2D::TRTexture2D(bool generatedMipmap) : m_generateMipmap(generatedMipmap), m_warpMode(TRTextureWarpMode::TR_MIRRORED_REPEAT), m_filteringMode(TRTextureFilterMode::TR_LINEAR) {} void TRTexture2D::setWarpingMode(TRTextureWarpMode mode) { m_warpMode = mode; } void TRTexture2D::setFilteringMode(TRTextureFilterMode mode) { m_filteringMode = mode; } bool TRTexture2D::loadTextureFromFile( const std::string &filepath, TRTextureWarpMode warpMode, TRTextureFilterMode filterMode) { m_warpMode = warpMode; m_filteringMode = filterMode; std::vector<TRTextureHolder::ptr>().swap(m_texHolders); unsigned char *pixels = nullptr; //Load image from given file using stb_image.h //Refs: https://github.com/nothings/stb int width, height, channel; { //stbi_set_flip_vertically_on_load(true); pixels = stbi_load(filepath.c_str(), &width, &height, &channel, 0); if (pixels == nullptr) { std::cerr << "Failed to load image from " << filepath << std::endl; exit(1); } if (width <= 0 || width >= 65536 || height <= 0 || height >= 65536) { std::cerr << "Invalid size from image: " << filepath << std::endl; exit(1); } } //32bpp unsigned char *raw = new unsigned char[width * height * 4]; parallelFor((int)0, (int)(width * height), [&](const int &index) { unsigned char &r = raw[index * 4 + 0]; unsigned char &g = raw[index * 4 + 1]; unsigned char &b = raw[index * 4 + 2]; unsigned char &a = raw[index * 4 + 3]; int fromIndex = index * channel; switch (channel) { case 1: r = g = b = pixels[fromIndex], a = 255; break; case 3: r = pixels[fromIndex], g = pixels[fromIndex + 1], b = pixels[fromIndex + 2], a = 255; break; case 4: r = pixels[fromIndex], g = pixels[fromIndex + 1], b = pixels[fromIndex + 2], a = pixels[fromIndex + 3]; break; default: r = g = b = pixels[fromIndex], a = 255; break; } }, TRExecutionPolicy::TR_PARALLEL); channel = 4; stbi_image_free(pixels); pixels = nullptr; //Generate resolution pyramid for mipmap if (m_generateMipmap) { generateMipmap(raw, width, height, channel); } else { m_texHolders = { std::make_shared<TRZCurveTilingTextureHolder>(raw, width, height, channel) }; } delete[] raw; return true; } void TRTexture2D::generateMipmap(unsigned char *pixels, int width, int height, int channel) { unsigned char *rawData = pixels; bool reAlloc = false; //Find the first greater number which equals to 2^n static auto firstGreaterPowOf2 = [](const int &num) -> int { int base = num - 1; base |= (base >> 1); base |= (base >> 2); base |= (base >> 4); base |= (base >> 8); base |= (base >> 16); return base + 1; }; int nw = firstGreaterPowOf2(width); int nh = firstGreaterPowOf2(height); //Note: need to make sure that width and height equal to 2^n if (nw != width || nh != height || nw != nh) { //Reallocation for padding to 2^n * 2^n nw = glm::max(nw, nh); nh = glm::max(nw, nh); reAlloc = true; rawData = new unsigned char[nw * nh * channel]; auto readPixels = [&](const int &x, const int &y, unsigned char &r, unsigned char &g, unsigned char &b, unsigned char &a) -> void { int tx = (x >= width) ? (width - 1) : x; int ty = (y >= height) ? (height - 1) : y; r = pixels[(ty*width + tx) * channel + 0]; g = pixels[(ty*width + tx) * channel + 1]; b = pixels[(ty*width + tx) * channel + 2]; a = pixels[(ty*width + tx) * channel + 3]; }; parallelFor((int)0, (int)(nw * nh), [&](const int &index) -> void { float x = (float)(index % nw)/(float)(nw - 1) * (width - 1); float y = (float)(index / nw)/(float)(nh - 1) * (height - 1); unsigned char r, g, b, a; //Binlear interpolation for scaling { int ix = (int)x, iy = (int)y; int fx = x - ix, fy = y - iy; unsigned char p[4][4]; readPixels(ix, iy, p[0][0], p[0][1], p[0][2], p[0][3]); readPixels(ix + 1, iy, p[1][0], p[1][1], p[1][2], p[1][3]); readPixels(ix, iy + 1, p[2][0], p[2][1], p[2][2], p[2][3]); readPixels(ix + 1, iy + 1, p[3][0], p[3][1], p[3][2], p[3][3]); float w0 = (1.0f - fx) * (1.0f - fy), w1 = fx * (1.0f - fy); float w2 = (1.0f - fx) * fy, w3 = fx * fy; r = (unsigned char)(w0 * p[0][0] + w1 * p[1][0] + w2 * p[2][0] + w3 * p[3][0]); g = (unsigned char)(w0 * p[0][1] + w1 * p[1][1] + w2 * p[2][1] + w3 * p[3][1]); b = (unsigned char)(w0 * p[0][2] + w1 * p[1][2] + w2 * p[2][2] + w3 * p[3][2]); a = (unsigned char)(w0 * p[0][3] + w1 * p[1][3] + w2 * p[2][3] + w3 * p[3][3]); } rawData[index * channel] = r; rawData[index * channel + 1] = g; rawData[index * channel + 2] = b; rawData[index * channel + 3] = a; }); width = nw; height = nh; std::cout << "Warning: texture padding to 2^n * 2^n\n"; } //First level int curW = width, curH = height; m_texHolders.push_back(std::make_shared<TRZCurveTilingTextureHolder>(rawData, curW, curH, channel)); //The rest of levels unsigned char *previous = rawData; unsigned char *tmpAlloc = new unsigned char[curW * curH * channel]; unsigned char *current = tmpAlloc; while(curW >= 2) { curW /= 2, curH /= 2; parallelFor((int)0, (int)(curW * curH), [&](const int &index) { int x = index % curW; int y = index / curW; unsigned char r, g, b, a; int destX = 2 * x, destY = 2 * y; int target1 = (destY * curW * 2 + destX) * channel; int target2 = (destY * curW * 2 + destX + 1) * channel; int target3 = ((destY + 1) * curW * 2 + destX) * channel; int target4 = ((destY + 1) * curW * 2 + destX + 1) * channel; //Box filtering for down-sampling r = (previous[target1 + 0] + previous[target2 + 0] + previous[target3 + 0] + previous[target4 + 0]) * 0.25; g = (previous[target1 + 1] + previous[target2 + 1] + previous[target3 + 1] + previous[target4 + 1]) * 0.25; b = (previous[target1 + 2] + previous[target2 + 2] + previous[target3 + 2] + previous[target4 + 2]) * 0.25; a = (previous[target1 + 3] + previous[target2 + 3] + previous[target3 + 3] + previous[target4 + 3]) * 0.25; current[index * channel + 0] = r; current[index * channel + 1] = g; current[index * channel + 2] = b; current[index * channel + 3] = a; }); //Note: Tiling and ZCuve mapping are also time-consuming //if (curW >= 32) //{ // m_texHolders.push_back(std::make_shared<TRZCurveTilingTextureHolder>(current, curW, curH, channel)); //} //else //{ // m_texHolders.push_back(std::make_shared<TRLinearTextureHolder>(current, curW, curH, channel)); //} m_texHolders.push_back(std::make_shared<TRTilingTextureHolder>(current, curW, curH, channel)); //m_texHolders.push_back(std::make_shared<TRLinearTextureHolder>(current, curW, curH, channel)); std::swap(current, previous); } delete[] tmpAlloc; if (reAlloc) { delete[] rawData; } } void TRTexture2D::readPixel(const std::uint16_t &u, const std::uint16_t &v, unsigned char &r, unsigned char &g, unsigned char &b, unsigned char &a, const int level) const { //Please make sure that loadTextureFromFile() had been called. //Note: guarantee that u and v are in [0,width-1],[0,height-1] respectively. std::uint32_t texel = m_texHolders[level]->read(u, v); r = (texel >> 24) & 0xFF; g = (texel >> 16) & 0xFF; b = (texel >> 8) & 0xFF; a = (texel >> 0) & 0xFF; } glm::vec4 TRTexture2D::sample(const glm::vec2 &uv, const float &level) const { //Perform sampling procedure //Note: return texel that ranges from 0.0f to 1.0f instead of [0,255] float u = uv.x, v = uv.y; //Texture warpping mode { if (u < 0 || u > 1.0f) { switch (m_warpMode) { case TRTextureWarpMode::TR_REPEAT: u = (u > 0) ? (u - (int)u) : (1.0f - ((int)u - u)); break; case TRTextureWarpMode::TR_MIRRORED_REPEAT: u = (u > 0) ? (1.0f - (u - (int)u)) : ((int)u - u); break; case TRTextureWarpMode::TR_CLAMP_TO_EDGE: u = (u < 0) ? 0 : 1.0f; break; default: u = (u < 0) ? 0 : 1.0f; break; } } if (v < 0 || v > 1.0f) { switch (m_warpMode) { case TRTextureWarpMode::TR_REPEAT: v = (v > 0) ? (v - (int)v) : (1.0f - ((int)v - v)); break; case TRTextureWarpMode::TR_MIRRORED_REPEAT: v = (v > 0) ? (1.0f - (v - (int)v)) : ((int)v - v); break; case TRTextureWarpMode::TR_CLAMP_TO_EDGE: v = (v < 0) ? 0 : 1.0f; break; default: v = (v < 0) ? 0 : 1.0f; break; } } } glm::vec4 texel(1.0f); //No mipmap: just sampling at the first level if (!m_generateMipmap) { switch (m_filteringMode) { case TRTextureFilterMode::TR_NEAREST: texel = TRTexture2DSampler::textureSamplingNearest(m_texHolders[0], glm::vec2(u, v)); break; case TRTextureFilterMode::TR_LINEAR: texel = TRTexture2DSampler::textureSamplingBilinear(m_texHolders[0], glm::vec2(u, v)); break; default: break; } } //Mipmap: linear interpolation between two levels else { glm::vec4 texel1(1.0f), texel2(1.0f); unsigned int level1 = glm::min((unsigned int)level, (unsigned int)m_texHolders.size() - 1); unsigned int level2 = glm::min((unsigned int)(level + 1), (unsigned int)m_texHolders.size() - 1); switch (m_filteringMode) { case TRTextureFilterMode::TR_NEAREST: if (level1 != level2) { texel1 = TRTexture2DSampler::textureSamplingNearest(m_texHolders[level1], glm::vec2(u, v)); texel2 = TRTexture2DSampler::textureSamplingNearest(m_texHolders[level2], glm::vec2(u, v)); } else { texel1 = TRTexture2DSampler::textureSamplingNearest(m_texHolders[level1], glm::vec2(u, v)); texel2 = texel1; } break; case TRTextureFilterMode::TR_LINEAR: //Trilinear interpolation if (level1 != level2) { texel1 = TRTexture2DSampler::textureSamplingBilinear(m_texHolders[level1], glm::vec2(u, v)); texel2 = TRTexture2DSampler::textureSamplingBilinear(m_texHolders[level2], glm::vec2(u, v)); } else { texel1 = TRTexture2DSampler::textureSamplingBilinear(m_texHolders[level1], glm::vec2(u, v)); texel2 = texel1; } break; } //Interpolation float frac = level - (int)level; texel = (1.0f - frac) * texel1 + frac * texel2; } return texel; } //----------------------------------------------TRTexture2DSampler---------------------------------------------- glm::vec4 TRTexture2DSampler::textureSamplingNearest(TRTextureHolder::ptr texture, glm::vec2 uv) { //Perform nearest sampling procedure unsigned char r, g, b, a = 255; texture->read( (std::uint16_t)(uv.x * (texture->getWidth() - 1) + 0.5f), //Rounding (std::uint16_t)(uv.y * (texture->getHeight() - 1) + 0.5f), //Rounding r, g, b, a); constexpr float denom = 1.0f / 255.0f; return glm::vec4(r, g, b, a) * denom; } glm::vec4 TRTexture2DSampler::textureSamplingBilinear(TRTextureHolder::ptr texture, glm::vec2 uv) { //Perform bilinear sampling procedure const auto &w = texture->getWidth(); const auto &h = texture->getHeight(); float fx = (uv.x * (w- 1)), fy = (uv.y * (h - 1)); std::uint16_t ix = (std::uint16_t)fx, iy = (std::uint16_t)fy; float frac_x = fx - ix, frac_y = fy - iy; /********************* * p2--p3 * | | * p0--p1 * Note: p0 is (ix,iy) ********************/ static constexpr float denom = 1.0f / 255.0f; unsigned char r, g, b, a = 255; //p0 texture->read(ix, iy, r, g, b, a); glm::vec4 p0(r, g, b, a); //p1 texture->read((ix + 1 >= w) ? ix : (ix + 1), iy, r, g, b, a); glm::vec4 p1(r, g, b, a); //p2 texture->read(ix, (iy + 1 >= h) ? iy : (iy + 1), r, g, b, a); glm::vec4 p2(r, g, b, a); //p3 texture->read((ix + 1 >= w) ? ix : (ix + 1), (iy + 1 >= h) ? iy : (iy + 1), r, g, b, a); glm::vec4 p3(r, g, b, a); return ((1.0f - frac_x) * (1.0f - frac_y) * p0 + frac_x * (1.0f - frac_y) * p1 + (1.0f - frac_x) * frac_y * p2 + frac_x * frac_y * p3) * denom; } }
32.030691
132
0.587512
ZeusYang
409d70869718b1052b0f6059d8eca1420f44a19f
28,544
cpp
C++
Alien Engine/Alien Engine/PanelInspector.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/PanelInspector.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/PanelInspector.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "PanelInspector.h" #include "ModuleObjects.h" #include "ModuleRenderer3D.h" #include "ModuleUI.h" #include "PanelProject.h" #include "ResourceScript.h" #include "ComponentTransform.h" #include "ComponentMesh.h" #include "ComponentMaterial.h" #include "ComponentLightDirectional.h" #include "ComponentLightSpot.h" #include "ComponentCurve.h" #include "ComponentLightPoint.h" #include "ComponentAnimator.h" #include "ModuleResources.h" #include "ResourceAnimation.h" #include "ResourceModel.h" #include "ResourceBone.h" #include "ResourceMesh.h" #include "ResourceMaterial.h" #include "imgui/imgui_internal.h" #include "ComponentAudioListener.h" #include "ComponentAudioEmitter.h" #include "ComponentParticleSystem.h" #include "ComponentTrail.h" #include "ComponentSlider.h" #include "ComponentCanvas.h" #include "ComponentUI.h" #include "ComponentImage.h" #include "ComponentBar.h" #include "ComponentText.h" #include "ComponentButton.h" #include "ComponentCheckbox.h" #include "ComponentAnimatedImage.h" #include "ReturnZ.h" #include "Alien.h" #include "ComponentScript.h" #include "ShortCutManager.h" #include "ModuleCamera3D.h" #include "mmgr/mmgr.h" #include "ComponentCollider.h" #include "ComponentBoxCollider.h" #include "ComponentSphereCollider.h" #include "ComponentMeshCollider.h" #include "ComponentCapsuleCollider.h" #include "ComponentConvexHullCollider.h" #include "ComponentRigidBody.h" #include "ComponentCharacterController.h" #include "ComponentJoint.h" #include "ComponentConfigurableJoint.h" #include "Optick/include/optick.h" #define DAE_FPS 30 PanelInspector::PanelInspector(const std::string& panel_name, const SDL_Scancode& key1_down, const SDL_Scancode& key2_repeat, const SDL_Scancode& key3_repeat_extra) : Panel(panel_name, key1_down, key2_repeat, key3_repeat_extra) { shortcut = App->shortcut_manager->AddShortCut("Inspector", key1_down, std::bind(&Panel::ChangeEnable, this), key2_repeat, key3_repeat_extra); components.push_back(std::pair<std::string, ComponentType>("AASelect Component", ComponentType::NONE)); // This name is for the sort in order to have it at the begin for (int i = 0; i < (int)ComponentType::MAX; i++) { if (i != (int)ComponentType::BONE && i != (int)ComponentType::MESH && i != (int)ComponentType::DEFORMABLE_MESH && i != (int)ComponentType::MAX && i != (int)ComponentType::UI) //Add the component types you don't want to show in combo components.push_back( std::pair<std::string, ComponentType>( Component::EnumToString((ComponentType)i), (ComponentType)i) ); } //if there is an empty id in ComponentType we have to exclude if they have no name auto i = components.begin(); while (i != components.end()) { if ((*i).first.compare("Not valid") == 0) i = components.erase(i); else ++i; } std::sort(components.begin(), components.end()); // Sort components by name for (auto i = components.begin(); i != components.end(); i++) { // iterate and add the name and '\0' to the combo for imgui if ((*i).second == ComponentType::NONE) (*i).first.assign("Select Component"); // rename NONE id combo_select += (*i).first + '\0'; } } PanelInspector::~PanelInspector() { } void PanelInspector::PanelLogic() { OPTICK_EVENT(); ImGui::Begin(panel_name.data(), &enabled, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize); if (ImGui::IsWindowHovered()) App->camera->is_scene_hovered = false; //selected gameobject/s if (App->objects->GetSelectedObjects().size() == 1) { static bool draw_add = true; GameObject* obj = App->objects->GetSelectedObjects().back(); std::vector<Component*>::iterator item = obj->components.begin(); for (; item != obj->components.end(); ++item) { if (*item != nullptr) { if ((*item)->DrawInspector()) { if (!(*item)->not_destroy && (*item)->serialize) { to_destroy = (*item); delete_panel = &(*item)->not_destroy; *delete_panel = !(*delete_panel); } } else { draw_add = false; break; } } } if (draw_add) { ButtonAddComponent(); } else { draw_add = true; } DropScript(); } else if (App->objects->GetSelectedObjects().size() > 1) { if (ImGui::CollapsingHeader("Transform", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Spacing(); ImGui::Text("Position "); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(1); std::list<GameObject*> selected = App->objects->GetSelectedObjects(); auto item = selected.begin(); float4x4 trans = float4x4::zero(); bool some_static = false; for (; item != selected.end(); ++item) { if (*item != nullptr) { if ((*item)->is_static) { some_static = true; } if (trans.Equals(float4x4::zero())) { trans = (*item)->GetComponent<ComponentTransform>()->global_transformation; } else { trans = trans * (*item)->GetComponent<ComponentTransform>()->global_transformation; } } } float3 view_pos, view_scale, view_rot; Quat rot; trans.Decompose(view_pos, rot, view_scale); view_rot = rot.ToEulerXYZ(); view_rot = RadToDeg(view_rot) / selected.size(); view_pos /= selected.size(); view_scale /= selected.size(); float3 original_pos, original_rot, original_scale; original_pos = view_pos; original_rot = view_rot; original_scale = view_scale; bool need_refresh_pos = false; bool need_refresh_scale = false; bool need_refresh_rot = false; if (ImGui::DragFloat("X", &view_pos.x, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_pos = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(2); if (ImGui::DragFloat("Y", &view_pos.y, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_pos = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(3); if (ImGui::DragFloat("Z", &view_pos.z, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_pos = true; } ImGui::PopID(); ImGui::Spacing(); ImGui::Text("Rotation "); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(4); if (ImGui::DragFloat("X", &view_rot.x, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_rot = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(5); if (ImGui::DragFloat("Y", &view_rot.y, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_rot = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(6); if (ImGui::DragFloat("Z", &view_rot.z, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_rot = true; } ImGui::PopID(); ImGui::Spacing(); ImGui::Text("Scale "); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(7); if (ImGui::DragFloat("X", &view_scale.x, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_scale = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(8); if (ImGui::DragFloat("Y", &view_scale.y, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_scale = true; } ImGui::PopID(); ImGui::SameLine(); ImGui::SetNextItemWidth(70); ImGui::PushID(9); if (ImGui::DragFloat("Z", &view_scale.z, 0.5F, 0, 0, "%.3f", 1, some_static)) { need_refresh_scale = true; } ImGui::PopID(); ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); if (need_refresh_pos) { item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { (*item)->GetComponent<ComponentTransform>()->AddPosition(view_pos - original_pos); } } } else if (need_refresh_rot) { item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { (*item)->GetComponent<ComponentTransform>()->AddRotation(view_rot - original_rot); } } } else if (need_refresh_scale) { item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { (*item)->GetComponent<ComponentTransform>()->AddScale(view_scale - original_scale); } } } } ButtonAddComponent(); } else if (App->ui->panel_project->selected_resource != nullptr) { Resource* selected_file = App->ui->panel_project->selected_resource; if (selected_file->GetType() == ResourceType::RESOURCE_MODEL) { ShowModelImportSettings((ResourceModel*)selected_file); } else if (selected_file->GetType() == ResourceType::RESOURCE_MATERIAL) { static_cast<ResourceMaterial*>(selected_file)->DisplayMaterialOnInspector(); } else if (selected_file->GetType() == ResourceType::RESOURCE_TEXTURE) { static_cast<ResourceTexture*>(selected_file)->DisplayTextureOnInspector(); } } ImGui::End(); DeleteComponentPopup(); } void PanelInspector::DeleteComponentPopup() { if (delete_panel != nullptr && *delete_panel) { ImGui::OpenPopup("Do you want to delete it?"); ImGui::SetNextWindowSize({ 200,60 }); if (ImGui::BeginPopupModal("Do you want to delete it?", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { ImGui::Spacing(); ImGui::NewLine(); ImGui::SameLine(40); ImGui::PushStyleColor(ImGuiCol_::ImGuiCol_Button, { 0.5F,0,0,1 }); if (ImGui::Button("Delete")) { *delete_panel = !(*delete_panel); delete_panel = nullptr; App->objects->need_to_delete_objects = true; ReturnZ::AddNewAction(ReturnZ::ReturnActions::DELETE_COMPONENT, to_destroy); to_destroy = nullptr; } ImGui::PopStyleColor(); ImGui::SameLine(100); if (ImGui::Button("Cancel")) { delete_panel = nullptr; } ImGui::EndPopup(); } } } void PanelInspector::ButtonAddComponent() { ImGui::Spacing(); if (components[component].second == ComponentType::SCRIPT) { if (ImGui::BeginCombo("##Scriptss", std::get<0>(script_info))) { bool sel = App->StringCmp("Return To Components", std::get<0>(script_info)); ImGui::Selectable("Return To Components", sel); if (ImGui::IsItemClicked()) { std::get<0>(script_info) = "Return To Components"; component = 0; } std::vector<Resource*>::iterator item = App->resources->resources.begin(); for (; item != App->resources->resources.end(); ++item) { if (*item != nullptr && (*item)->GetType() == ResourceType::RESOURCE_SCRIPT) { ResourceScript* script = (ResourceScript*)(*item); if (!script->data_structures.empty()) { for (uint i = 0; i < script->data_structures.size(); ++i) { bool is_selected = (std::get<0>(script_info) == script->data_structures[i].first.data()); if (ImGui::Selectable(script->data_structures[i].first.data(), is_selected)) { std::get<0>(script_info) = script->data_structures[i].first.data(); std::get<1>(script_info) = script->data_structures[i].second; std::get<2>(script_info) = script->GetID(); } } } } } ImGui::EndCombo(); } ImGui::SameLine(); if (ImGui::Button("Add Component")) { if (!App->StringCmp("Return To Components", std::get<0>(script_info))) { bool added = false; for (auto item = App->objects->GetSelectedObjects().begin(); item != App->objects->GetSelectedObjects().end(); ++item) { GameObject* obj = *item; bool exists = false; std::vector<ComponentScript*> scripts = obj->GetComponents<ComponentScript>(); for (uint i = 0; i < scripts.size(); ++i) { if (App->StringCmp(scripts[i]->data_name.data(), std::get<0>(script_info))) { exists = true; break; } } if (!exists) { ComponentScript* comp_script = new ComponentScript(obj); comp_script->resourceID = std::get<2>(script_info); comp_script->LoadData(std::get<0>(script_info), std::get<1>(script_info)); added = true; ReturnZ::AddNewAction(ReturnZ::ReturnActions::ADD_COMPONENT, (void*)comp_script); if (Time::IsInGameState() && comp_script->need_alien && comp_script->data_ptr != nullptr) { Alien* alien = (Alien*)comp_script->data_ptr; if (alien != nullptr) { alien->Awake(); alien->Start(); } } break; } else { LOG_ENGINE("This script is already attached!"); } } if (added) { std::get<0>(script_info) = "Return To Components"; component = 0; } } else { LOG_ENGINE("Select a script"); } } } else { ImGui::Combo("##choose component", &component, combo_select.c_str()); ImGui::SameLine(); if (ImGui::Button("Add Component")) { bool added = true; for (auto item = App->objects->GetSelectedObjects().begin(); item != App->objects->GetSelectedObjects().end(); ++item) { Component* comp = nullptr; GameObject* selected = *item; switch (components[component].second) { case ComponentType::NONE: { LOG_ENGINE("Select a Component!"); break; } case ComponentType::MESH: { if (!selected->HasComponent(ComponentType::MESH)) { comp = new ComponentMesh(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::MATERIAL: { if ((!selected->HasComponent(ComponentType::MATERIAL)) && (selected->HasComponent(ComponentType::MESH) || selected->HasComponent(ComponentType::DEFORMABLE_MESH))) { comp = new ComponentMaterial(selected); selected->AddComponent(comp); } else if (selected->HasComponent(ComponentType::MATERIAL)) { LOG_ENGINE("The selected object already has this component!"); } else LOG_ENGINE("The object needs a mesh to have a material!"); break; } case ComponentType::LIGHT_DIRECTIONAL: { if (!selected->HasComponent(ComponentType::LIGHT_DIRECTIONAL)) { comp = new ComponentLightDirectional(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::CURVE: { if (!selected->HasComponent(ComponentType::CURVE)) { comp = new ComponentCurve(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::LIGHT_SPOT: { if (!selected->HasComponent(ComponentType::LIGHT_SPOT)) { comp = new ComponentLightSpot(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::LIGHT_POINT: { if (!selected->HasComponent(ComponentType::LIGHT_POINT)) { comp = new ComponentLightPoint(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::CAMERA: { if (!selected->HasComponent(ComponentType::CAMERA)) { comp = new ComponentCamera(selected); selected->AddComponent(comp); App->renderer3D->selected_game_camera = (ComponentCamera*)comp; } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::ANIMATOR: { if (!selected->HasComponent(ComponentType::ANIMATOR)) { comp = new ComponentAnimator(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::PARTICLES: { if (!selected->HasComponent(ComponentType::PARTICLES)) { //A GameObject can't have two shaders because binding order, thats why we check if obj has a material //Also, we check if it has a Mesh cause drawing order deals with mesh if (!selected->HasComponent(ComponentType::MATERIAL) && !selected->HasComponent(ComponentType::MESH)) { comp = new ComponentParticleSystem(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has a Shader Material to bind!"); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::TRAIL: { if (!selected->HasComponent(ComponentType::TRAIL)) { if (!selected->HasComponent(ComponentType::MATERIAL) && !selected->HasComponent(ComponentType::MESH)) { comp = new ComponentTrail(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has a Shader Material to bind!"); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::A_EMITTER: { if (!selected->HasComponent(ComponentType::A_EMITTER)) { comp = new ComponentAudioEmitter(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::A_LISTENER: { if (!selected->HasComponent(ComponentType::A_LISTENER)) { comp = new ComponentAudioListener(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::CANVAS: { if (!selected->HasComponent(ComponentType::CANVAS)) { comp = new ComponentCanvas(selected); selected->AddComponent(comp); } else LOG_ENGINE("The selected object already has this component!"); break; } case ComponentType::UI_IMAGE: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); comp = new ComponentImage(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_BUTTON: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); Component* comp_emitter = nullptr; Component* comp_text = nullptr; GameObject* object_text = App->objects->CreateEmptyGameObject(nullptr); comp = new ComponentButton(selected); comp_emitter = new ComponentAudioEmitter(selected); comp_text = new ComponentText(object_text); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); dynamic_cast<ComponentUI*>(comp_text)->SetCanvas(canvas); selected->SetName("Button"); selected->AddComponent(comp); selected->AddComponent(comp_emitter); object_text->SetName("Text"); object_text->AddComponent(comp_text); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); App->objects->ReparentGameObject(object_text, selected, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_TEXT: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); comp = new ComponentText(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_CHECKBOX: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); Component* comp_emitter = nullptr; comp = new ComponentCheckbox(selected); comp_emitter = new ComponentAudioEmitter(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); selected->AddComponent(comp_emitter); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_SLIDER: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); Component* comp_emitter = nullptr; comp = new ComponentSlider(selected); comp_emitter = new ComponentAudioEmitter(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); selected->AddComponent(comp_emitter); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_BAR: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); comp = new ComponentBar(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::UI_ANIMATED_IMAGE: { if (!selected->HasComponent(ComponentType::UI)) { ComponentCanvas* canvas = GetCanvas(); comp = new ComponentAnimatedImage(selected); dynamic_cast<ComponentUI*>(comp)->SetCanvas(canvas); selected->AddComponent(comp); App->objects->ReparentGameObject(selected, canvas->game_object_attached, false); } else LOG_ENGINE("The selected object already has Component UI!"); break; } case ComponentType::BOX_COLLIDER: { comp = new ComponentBoxCollider(selected); selected->AddComponent(comp); break; } case ComponentType::SPHERE_COLLIDER: { comp = new ComponentSphereCollider(selected); selected->AddComponent(comp); break; } case ComponentType::CAPSULE_COLLIDER: { comp = new ComponentCapsuleCollider(selected); selected->AddComponent(comp); break; } case ComponentType::MESH_COLLIDER: { comp = new ComponentMeshCollider(selected); selected->AddComponent(comp); break; } case ComponentType::CONVEX_HULL_COLLIDER: { comp = new ComponentConvexHullCollider(selected); selected->AddComponent(comp); break; } case ComponentType::RIGID_BODY: { if (!selected->HasComponent(ComponentType::RIGID_BODY)) { comp = new ComponentRigidBody(selected); selected->AddComponent(comp); } break; } case ComponentType::CHARACTER_CONTROLLER: { if (!selected->HasComponent(ComponentType::CHARACTER_CONTROLLER)) { comp = new ComponentCharacterController(selected); selected->AddComponent(comp); } break; } case ComponentType::CHARACTER_JOINT: { comp = new ComponentConfigurableJoint(selected); selected->AddComponent(comp); break; } case ComponentType::CONFIGURABLE_JOINT: { comp = new ComponentConfigurableJoint(selected); selected->AddComponent(comp); break; } } if (comp != nullptr) { ReturnZ::AddNewAction(ReturnZ::ReturnActions::ADD_COMPONENT, comp); added = true; } } if (added) { component = 0; } } } } void PanelInspector::ShowModelImportSettings(ResourceModel* model) { if (model->animations_attached.size() > 0) { static char anim_name[MAX_PATH] = "Name"; for each (ResourceAnimation * anim in model->animations_attached) { ImGui::PushID(anim); strcpy_s(anim_name, 100, anim->name.data()); if (ImGui::InputText("Clip Name", anim_name, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) { anim->name = anim_name; } //bool is_dae = (anim->ticks_per_second == 1); uint max_tick = /*is_dae ? (uint)(anim->max_tick * DAE_FPS) : */(int)anim->max_tick; int start_tick = /*is_dae ? (int)(anim->start_tick * DAE_FPS) : */(int)anim->start_tick; int end_tick = /*is_dae ? (int)(anim->end_tick * DAE_FPS) : */(int)anim->end_tick; if (ImGui::DragInt("Start", &start_tick, 1.0F, 0, end_tick - 1)) { if (start_tick >= 0 && start_tick < end_tick) { anim->start_tick = /*is_dae ? (float)start_tick / DAE_FPS :*/ (uint)start_tick; } } if (ImGui::DragInt("End", &end_tick, 1.0F, start_tick + 1, max_tick)) { if (end_tick > start_tick && end_tick <= max_tick) { anim->end_tick = /*is_dae ? (float)end_tick / DAE_FPS :*/ (uint)end_tick; } } ImGui::Checkbox("Loops", &anim->loops); ImGui::Separator(); ImGui::PopID(); } if (ImGui::Button("+")) { ResourceAnimation* new_anim = new ResourceAnimation(); new_anim->name = "New Clip"; new_anim->max_tick = model->animations_attached[0]->max_tick; new_anim->end_tick = model->animations_attached[0]->max_tick; model->animations_attached.push_back(new_anim); App->resources->AddResource(new_anim); } ImGui::SameLine(); if (ImGui::Button("-") && model->animations_attached.size() > 1) { App->resources->RemoveResource(model->animations_attached[model->animations_attached.size() - 1]); delete model->animations_attached[model->animations_attached.size() - 1]; model->animations_attached.pop_back(); } ImGui::Separator(); if (ImGui::Button("Save")) { //TODO: FIX THIS MESS OF CODE :| model->animations_attached[0]->LoadMemory(); if (model->animations_attached.size() > 1) { for (int i = 1; i < model->animations_attached.size(); ++i) { model->animations_attached[i]->Copy(model->animations_attached[0]); } } model->UpdateAnimationInfo(); } } } ComponentCanvas* PanelInspector::GetCanvas() { ComponentCanvas* canvas = App->objects->GetRoot(true)->GetCanvas(); if (canvas == nullptr) { GameObject* obj = new GameObject(App->objects->GetRoot(false)); obj->SetName("Canvas"); canvas = new ComponentCanvas(obj); obj->AddComponent(canvas); } return canvas; } void PanelInspector::DropScript() { // drop a node in the window, parent is base_game_object ImVec2 min_space = ImGui::GetWindowContentRegionMin(); ImVec2 max_space = ImGui::GetWindowContentRegionMax(); min_space.x += ImGui::GetWindowPos().x; min_space.y += ImGui::GetWindowPos().y; max_space.x += ImGui::GetWindowPos().x; max_space.y += ImGui::GetWindowPos().y; if (ImGui::BeginDragDropTargetCustom({ min_space.x,min_space.y, max_space.x,max_space.y }, ImGui::GetID(panel_name.data()))) { const ImGuiPayload* payload = ImGui::GetDragDropPayload(); if (payload != nullptr && payload->IsDataType(DROP_ID_PROJECT_NODE)) { FileNode* node = *(FileNode**)payload->Data; if (node->type == FileDropType::SCRIPT && ImGui::AcceptDragDropPayload(DROP_ID_PROJECT_NODE, ImGuiDragDropFlags_SourceNoDisableHover)) { if (App->objects->GetSelectedObjects().size() == 1) { std::string path = App->file_system->GetPathWithoutExtension(node->path + node->name); path += "_meta.alien"; u64 ID = App->resources->GetIDFromAlienPath(path.data()); ResourceScript* script = (ResourceScript*)App->resources->GetResourceWithID(ID); path = node->path + node->name; JSONfilepack* scriptData = JSONfilepack::GetJSON(path.data()); if (script != nullptr && scriptData != nullptr && scriptData->GetBoolean("HasData")) { JSONArraypack* structure = scriptData->GetArray("DataStructure"); if (structure != nullptr) { structure->GetFirstNode(); for (uint i = 0; i < structure->GetArraySize(); ++i) { if (strcmp(structure->GetString("DataName"), App->file_system->GetBaseFileName(node->name.data()).data()) == 0) { ComponentScript* comp_script = new ComponentScript(App->objects->GetSelectedObjects().back()); comp_script->resourceID = script->GetID(); comp_script->LoadData(structure->GetString("DataName"), structure->GetBoolean("UsesAlien")); ReturnZ::AddNewAction(ReturnZ::ReturnActions::ADD_COMPONENT, (void*)comp_script); if (Time::IsInGameState() && comp_script->need_alien && comp_script->data_ptr != nullptr) { Alien* alien = (Alien*)comp_script; if (alien != nullptr) { alien->Awake(); alien->Start(); } } break; } structure->GetAnotherNode(); } delete scriptData; } } } ImGui::ClearDragDrop(); } } ImGui::EndDragDropTarget(); } }
31.857143
234
0.658317
OverPowered-Team
409de0324022cf3cd9c5649ae826755f28ece621
1,219
cpp
C++
abc_186/f.cpp
dashimaki360/atcoder
1462150d59d50f270145703df579dba8c306376c
[ "MIT" ]
null
null
null
abc_186/f.cpp
dashimaki360/atcoder
1462150d59d50f270145703df579dba8c306376c
[ "MIT" ]
null
null
null
abc_186/f.cpp
dashimaki360/atcoder
1462150d59d50f270145703df579dba8c306376c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // #include <atcoder/all> // using namespace atcoder; #define rep(i,n) for (int i = 0; i < (n); ++i) using ll = long long; using P = pair<int,int>; int main() { int h, w, m; cin >> h >> w >> m; bool up[h][w] = {false}; bool side[h][w] = {false}; vector<int> x(m), y(m); rep(i,m){ int a, b; cin >> a >> b; x[i] = a-1; y[i] = b-1; if(a-1==0){ rep(j,w){ if(y[i]+j+1 >= w) break; x.push_back(0); y.push_back(y[i]+j+1); } } if(b-1==0){ rep(j,h){ if(x[i]+j+1 >= h) break; y.push_back(0); x.push_back(x[i]+j+1); } } } // for(auto hoge:x) cout << hoge << endl; // for(auto hoge:y) cout << hoge << endl; for (int i = 0; i < x.size(); i++) { for(int j = x[i]; j < h; ++j){ up[j][y[i]] = true; // cout << "up: " << j << y[i] << endl; } for(int j = y[i]; j < w; ++j){ side[x[i]][j] = true; // cout << "side: " << x[i] << j << endl; } } int bad_sum=0; rep(i,h) rep(j,w) { if(up[i][j]&&side[i][j]){ bad_sum++; // cout << i << j << endl; } } cout << h*w - bad_sum << endl; return 0; }
19.983607
47
0.418376
dashimaki360
40a27bb7b022b9f71807e088177b957f2b1b0f19
9,610
cc
C++
src/ppl/common/x86/sysinfo.cc
lzhangzz/ppl.common
c1cb1bb2ac01cca38fad47bd10995d60b7f7f252
[ "Apache-2.0" ]
20
2021-06-30T13:41:04.000Z
2022-02-16T13:19:28.000Z
src/ppl/common/x86/sysinfo.cc
lzhangzz/ppl.common
c1cb1bb2ac01cca38fad47bd10995d60b7f7f252
[ "Apache-2.0" ]
1
2021-07-11T05:00:10.000Z
2021-07-21T09:06:30.000Z
src/ppl/common/x86/sysinfo.cc
lzhangzz/ppl.common
c1cb1bb2ac01cca38fad47bd10995d60b7f7f252
[ "Apache-2.0" ]
14
2021-06-30T14:24:31.000Z
2022-03-16T07:58:43.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "ppl/common/sys.h" #include "sysinfo.h" #include <string.h> #include <mutex> #ifdef _WIN32 #define NOGDI #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #include <immintrin.h> #else #include <errno.h> #include <signal.h> #include <setjmp.h> #include <immintrin.h> #include <unistd.h> #include <fcntl.h> #endif template <typename... Args> static inline void supress_unused_warnings(Args &&...) {} #ifdef __GNUC__ #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #ifdef __APPLE__ extern "C" void _do_cpuid(int ieax, int iecx, int* rst_reg); #elif !(defined(_WIN32) || defined(_WIN64)) extern "C" void __do_cpuid(int ieax, int iecx, int* rst_reg); #endif static void DoCpuid(int ieax, int iecx, int *eax, int *ebx, int *ecx, int *edx) { int iEXXValue[4]; #if defined(_WIN32) || defined(_WIN64) __cpuidex(iEXXValue, ieax, iecx); #elif defined(__APPLE__) _do_cpuid(ieax, iecx, iEXXValue); #else __do_cpuid(ieax, iecx, iEXXValue); #endif if (eax) *eax = iEXXValue[0]; if (ebx) *ebx = iEXXValue[1]; if (ecx) *ecx = iEXXValue[2]; if (edx) *edx = iEXXValue[3]; } #ifdef _WIN32 static int try_run(float(*func)()) { __try { func(); } __except(EXCEPTION_EXECUTE_HANDLER) { return -1; } return 0; } #else static jmp_buf exceptJmpBuf; static struct sigaction exceptOldAct; static void exceptHandler(int) { siglongjmp(exceptJmpBuf, 1); } static int try_run(float(*func)()) { struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = &exceptHandler; sigaction(SIGILL, &act, &exceptOldAct); if (0 == sigsetjmp(exceptJmpBuf, 1)) { const float value = func(); sigaction(SIGILL, &exceptOldAct, NULL); supress_unused_warnings(value); return 0; } sigaction(SIGILL, &exceptOldAct, NULL); return -1; } #endif //! non-windows namespace ppl { namespace common { #ifdef _MSC_VER #pragma optimize("", off) #else #pragma GCC push_options #pragma GCC optimize ("-O0") #endif static #ifndef _MSC_VER __attribute__((__target__("sse"))) __attribute__((optimize(0))) #endif float TestIsaSSE() { return 0.0f; } static #ifndef _MSC_VER __attribute__((__target__("avx"))) __attribute__((optimize(0))) #endif float TestIsaAVX() { __m256 ymm0, ymm1, ymm2; #if defined (_WIN64) || defined (_WIN32) __declspec(align(64)) float buf[24] = { #else float buf[24] __attribute__((aligned(64))) = { #endif 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f, 1.0f, 0.0f, 3.0f, 0.0f, 5.0f, 0.0f, 7.0f, }; ymm0 = _mm256_load_ps(buf); ymm1 = _mm256_load_ps(buf + 8); ymm1 = _mm256_mul_ps(ymm0, ymm1); ymm2 = _mm256_load_ps(buf + 16); ymm2 = _mm256_add_ps(ymm1, ymm2); _mm256_store_ps(buf + 16, ymm2); return buf[18]; } static #ifndef _MSC_VER __attribute__((__target__("fma"))) __attribute__((optimize(0))) #endif float TestIsaFMA() { __m256 ymm0, ymm1, ymm2; #if defined (_WIN64) || defined (_WIN32) __declspec(align(64)) float buf[24] = { #else float buf[24] __attribute__((aligned(64))) = { #endif 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f, 1.0f, 0.0f, 3.0f, 0.0f, 5.0f, 0.0f, 7.0f, }; ymm0 = _mm256_load_ps(buf); ymm1 = _mm256_load_ps(buf + 8); ymm2 = _mm256_load_ps(buf + 16); ymm2 = _mm256_fmadd_ps(ymm0, ymm1, ymm2); _mm256_store_ps(buf + 16, ymm2); return buf[19]; } // About __AVX512F__ see: https://docs.microsoft.com/en-us/cpp/build/reference/arch-x64?view=vs-2019 // AVX512 was landed in VS2017 and GCC-4.9.2 #if (GCC_VERSION >= 40902 || _MSC_VER >= 1910) static float #ifdef __GNUC__ __attribute__((__target__("avx512f"))) __attribute__((optimize(0))) #endif // __GNUC__ TestIsaAVX512() { __m512 zmm0, zmm1, zmm2; #if defined (_WIN64) || defined (_WIN32) __declspec(align(64)) float buf[48] = { #else float buf[48] __attribute__((aligned(64))) = { #endif 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f, 1.0f, 0.0f, 3.0f, 0.0f, 5.0f, 0.0f, 7.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 3.0f, 0.0f, 5.0f, 0.0f, 7.0f, 7.0f, 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f, 0.0f, }; zmm0 = _mm512_load_ps(buf); zmm1 = _mm512_load_ps(buf + 16); zmm2 = _mm512_load_ps(buf + 32); zmm2 = _mm512_fmadd_ps(zmm0, zmm1, zmm2); _mm512_store_ps(buf + 32, zmm2); return buf[41]; } #endif // __AVX512F__ #ifdef _MSC_VER #pragma optimize("", on) #else #pragma GCC pop_options #endif static void GetCacheInfoIntel(const int &eax, const int &ebx, const int &ecx, const int &edx, uint64_t* cache_size, bool* inclusive) { int cache_type = eax & 31; if (cache_type == 1 || cache_type == 3) { int cache_sets = ecx + 1; int cacheline_size = (ebx & 0xfff) + 1; int cacheline_partitions = ((ebx >> 12) & 0x3ff) + 1; int cache_ways = ((ebx >> 22) & 0x3ff) + 1; *cache_size = static_cast<uint64_t>(cache_ways * cacheline_partitions * cacheline_size * cache_sets); if (inclusive != nullptr) { *inclusive = (edx >> 1) & 1; } } } static void GetCacheInfo(struct CpuInfo* info) { int eax, ebx, ecx, edx; // detect cache DoCpuid(0x80000000, 0x0, &eax, &ebx, &ecx, &edx); if ((unsigned int)eax >= 0x80000005) { uint64_t temp; // L1D DoCpuid(0x80000005, 0x0, &eax, &ebx, &ecx, &edx); temp = ecx; info->l1_cache_size = ((temp >> 24) & 0xFF) << 10; // L2 info->l2_cache_size = 0; DoCpuid(0x80000006, 0x0, &eax, &ebx, &ecx, &edx); temp = ecx; if (temp) info->l2_cache_size = ((temp >> 16) & 0xFFFF) << 10; // L3 info->l3_cache_size = 0; temp = edx; if (temp) info->l3_cache_size = ((temp >> 18) & 0x3FFF) << 19; } DoCpuid(4, 0, &eax, &ebx, &ecx, &edx); GetCacheInfoIntel(eax, ebx, ecx, edx, &(info->l1_cache_size), nullptr); DoCpuid(4, 2, &eax, &ebx, &ecx, &edx); GetCacheInfoIntel(eax, ebx, ecx, edx, &(info->l2_cache_size), nullptr); DoCpuid(4, 3, &eax, &ebx, &ecx, &edx); GetCacheInfoIntel(eax, ebx, ecx, edx, &(info->l3_cache_size), nullptr); } static void GetVendorId(struct CpuInfo* info) { int eax, ebx, ecx, edx; DoCpuid(0x00000000, 0x0, &eax, &ebx, &ecx, &edx); int* vendor_id_int = (int*)info->vendor_id; vendor_id_int[0] = ebx; vendor_id_int[1] = edx; vendor_id_int[2] = ecx; vendor_id_int[3] = 0; } void GetCPUInfoByCPUID(struct CpuInfo* info) { #define BIT_TEST(bit_map, pos) (((bit_map) & (0x1 << (pos))) ? 1 : 0) int eax, ebx, ecx, edx; DoCpuid(0x1, 0x0, &eax, &ebx, &ecx, &edx); info->isa = 0; info->isa |= (BIT_TEST(edx, 25) ? ISA_X86_SSE : 0x0UL); // ISA_X86_SSE info->isa |= (BIT_TEST(edx, 26) ? ISA_X86_SSE2 : 0x0UL); // ISA_X86_SSE2 info->isa |= (BIT_TEST(ecx, 0) ? ISA_X86_SSE3 : 0x0UL); // ISA_X86_SSE3 info->isa |= (BIT_TEST(ecx, 9) ? ISA_X86_SSSE3 : 0x0UL); // ISA_X86_SSSE3 info->isa |= (BIT_TEST(ecx, 19) ? ISA_X86_SSE41 : 0x0UL); // ISA_X86_SSE41 info->isa |= (BIT_TEST(ecx, 20) ? ISA_X86_SSE42 : 0x0UL); // ISA_X86_SSE42 info->isa |= (BIT_TEST(ecx, 28) ? ISA_X86_AVX : 0x0UL); // ISA_X86_AVX info->isa |= (BIT_TEST(ecx, 12) ? ISA_X86_FMA : 0x0UL); // ISA_X86_FMA DoCpuid(0x7, 0x0, &eax, &ebx, &ecx, &edx); info->isa |= (BIT_TEST(ebx, 5) ? ISA_X86_AVX2 : 0x0UL); // ISA_X86_AVX2 info->isa |= (BIT_TEST(ebx, 16) ? ISA_X86_AVX512 : 0x0UL); // ISA_X86_AVX512 info->isa |= (BIT_TEST(ecx, 11) ? ISA_X86_AVX512VNNI : 0x0UL); // ISA_X86_AVX512VNNI #undef BIT_TEST GetCacheInfo(info); GetVendorId(info); } void GetCPUInfoByRun(CpuInfo* info) { #if (GCC_VERSION >= 40902 || _MSC_VER >= 1910) if (0 == try_run(&TestIsaAVX512)) { info->isa |= ISA_X86_AVX512; } #endif // __AVX512F__ if (0 == try_run(&TestIsaFMA)) { info->isa |= ISA_X86_FMA; } if (0 == try_run(&TestIsaAVX)) { info->isa |= ISA_X86_AVX; } if (0 == try_run(&TestIsaSSE)) { info->isa |= ISA_X86_SSE; } GetCacheInfo(info); GetVendorId(info); } static CpuInfo __st_cpuinfo {0, 0, 0, 0}; static std::once_flag __st_cpuinfo_once_flag; static void detect_cpuinfo_once() { GetCPUInfoByRun(&__st_cpuinfo); } const CpuInfo* GetCpuInfo(int) { std::call_once(__st_cpuinfo_once_flag, &detect_cpuinfo_once); return &__st_cpuinfo; } } //! namespace common } //! namespace ppl #ifdef __GNUC__ #undef GCC_VERSION #endif
30.507937
109
0.631113
lzhangzz
40a432f692c75dc24163a2ada378b9582a05562d
480
cpp
C++
development/Games/TicTocToe/source/BoardSystem.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
development/Games/TicTocToe/source/BoardSystem.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
44
2018-06-28T03:01:44.000Z
2022-03-20T19:53:00.000Z
development/Games/TicTocToe/source/BoardSystem.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
#include "BoardSystem.h" #include "BoardComponent.h" ttt::BoardSystem::BoardSystem(Messaging& messaging, yaget::Application& app) : GameSystem("BoardSystem", messaging, app, [this](auto&&... params) {OnUpdate(params...); }) { int z = 0; z; } void ttt::BoardSystem::OnUpdate(yaget::comp::Id_t id, const yaget::time::GameClock& gameClock, yaget::metrics::Channel& channel, BoardComponent* boardComponent) { id; gameClock; channel; boardComponent; }
24
160
0.685417
eglowacki
40a5a238b25c7cd8bd3776563dc58256b2252ecc
199
hh
C++
include/size.hh
KPO-2020-2021/zad4-AdamDomachowski-1
8b88520d0902c9186a71d58390d4607daab2f74e
[ "Unlicense" ]
null
null
null
include/size.hh
KPO-2020-2021/zad4-AdamDomachowski-1
8b88520d0902c9186a71d58390d4607daab2f74e
[ "Unlicense" ]
null
null
null
include/size.hh
KPO-2020-2021/zad4-AdamDomachowski-1
8b88520d0902c9186a71d58390d4607daab2f74e
[ "Unlicense" ]
null
null
null
#pragma once /*! \file \brief definicje stalych */ constexpr int SIZE = 2; constexpr int ILOSC_WIERZCHOLKOW = 8; constexpr double MAKSYMALNA_ROZNICA_WYNIKOW = 0.0000000001;
16.583333
62
0.678392
KPO-2020-2021
40a68e2885326fadcbd7155a22a46625a9fed598
43,166
cpp
C++
videopp/renderer.cpp
volcoma/videopp
4da7ab1b189c0092eaa59064cfffb448312b7d41
[ "BSD-2-Clause" ]
1
2020-10-15T03:38:50.000Z
2020-10-15T03:38:50.000Z
videopp/renderer.cpp
volcoma/videopp
4da7ab1b189c0092eaa59064cfffb448312b7d41
[ "BSD-2-Clause" ]
null
null
null
videopp/renderer.cpp
volcoma/videopp
4da7ab1b189c0092eaa59064cfffb448312b7d41
[ "BSD-2-Clause" ]
null
null
null
#include "renderer.h" #include "font.h" #include "ttf_font.h" #include "texture.h" #include "logger.h" #include "detail/shaders.h" #include "detail/utils.h" #include <set> #ifdef WGL_CONTEXT #include "detail/wgl/context_wgl.h" #elif GLX_CONTEXT #include "detail/glx/context_glx.h" #elif EGL_CONTEXT #include "detail/egl/context_egl.h" #else #endif namespace gfx { namespace { struct gl_module { gl_module() { if(!gladLoad()) { throw exception("Could not open gl module"); } } ~gl_module() { gladUnload(); } } module; constexpr float FARTHEST_Z = -1.0f; // Callback function for printing debug statements void APIENTRY MessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar *msg, const void*) { std::string source_str; std::string type_str; std::string severity_str; switch (source) { case GL_DEBUG_SOURCE_API: source_str = "api"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: source_str = "window system"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: source_str = "shader compiler"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: source_str = "THIRD PARTY"; break; case GL_DEBUG_SOURCE_APPLICATION: source_str = "application"; break; case GL_DEBUG_SOURCE_OTHER: source_str = "unknown"; break; default: source_str = "unknown"; break; } switch (type) { case GL_DEBUG_TYPE_ERROR: type_str = "error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_str = "deprecated behavior"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_str = "undefined behavior"; break; case GL_DEBUG_TYPE_PORTABILITY: type_str = "portability"; break; case GL_DEBUG_TYPE_PERFORMANCE: type_str = "performance"; break; case GL_DEBUG_TYPE_OTHER: type_str = "other"; break; case GL_DEBUG_TYPE_MARKER: type_str = "unknown"; break; default: type_str = "unknown"; break; } switch (severity) { case GL_DEBUG_SEVERITY_HIGH: severity_str = "high"; break; case GL_DEBUG_SEVERITY_MEDIUM: severity_str = "medium"; break; case GL_DEBUG_SEVERITY_LOW: severity_str = "low"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: severity_str = "info"; break; default: severity_str = "unknown"; break; } std::stringstream ss; ss << "--[OPENGL CALLBACK]--\n" << " source : " << source_str << "\n" << " type : " << type_str << "\n" << " severity : " << severity_str << "\n" << " id : " << id << "\n" << " message : " << msg << "\n"; if(severity > GL_DEBUG_SEVERITY_NOTIFICATION) { log(ss.str()); } assert(type != GL_DEBUG_TYPE_ERROR); } rect transform_rect(const rect& rect, const math::transformf& transform) noexcept { const auto& scale = transform.get_scale(); return { int(std::lround(float(rect.x) * scale.x)), int(std::lround(float(rect.y) * scale.y)), int(std::lround(float(rect.w) * scale.x)), int(std::lround(float(rect.h) * scale.y))}; } rect inverse_and_tranfrom_rect(const rect& rect, const math::transformf& transform) noexcept { auto inversed_transform = math::inverse(transform); return transform_rect(rect, inversed_transform); } inline GLenum to_gl_primitive(primitive_type type) { switch(type) { case primitive_type::lines: return GL_LINES; case primitive_type::lines_loop: return GL_LINE_LOOP; case primitive_type::triangle_fan: return GL_TRIANGLE_FAN; case primitive_type::triangle_strip: return GL_TRIANGLE_STRIP; default: return GL_TRIANGLES; } } } /// Construct the renderer and initialize default rendering states /// @param win - the window handle /// @param vsync - true to enable vsync renderer::renderer(os::window& win, bool vsync, frame_callbacks fn) : win_(win) #ifdef WGL_CONTEXT , context_(std::make_unique<context_wgl>(win.get_native_handle())) #elif GLX_CONTEXT , context_(std::make_unique<context_glx>(win.get_native_handle(), win.get_native_display()/*, 3, 3*/)) #elif EGL_CONTEXT , context_(std::make_unique<context_egl>(win.get_native_handle(), win.get_native_display()/*, 3*/)) #endif , rect_({0, 0, int(win.get_size().w), int(win_.get_size().h)}) { if(!gladLoadGL()) { throw exception("Cannot load glad."); } GLint max_tex_units{}; gl_call(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_tex_units)); draw_config cfg; cfg.max_textures_per_batch = max_tex_units; set_draw_config(cfg); log("Max Texture Units Supported : " + std::to_string(max_tex_units)); log("Max Texture Units Per Batch configured to : " + std::to_string(cfg.max_textures_per_batch)); context_->set_vsync(vsync); // During init, enable debug output gl_call(glEnable(GL_DEBUG_OUTPUT)); gl_call(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS)); gl_call(glDebugMessageCallback(MessageCallback, nullptr)); // Depth calculation gl_call(glDisable(GL_DEPTH_TEST)); gl_call(glDepthMask(GL_FALSE)); // Default blending mode set_blending_mode(blending_mode::blend_normal); // Default texture interpolation methods gl_call(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); gl_call(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); // Default texture wrapping methods gl_call(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)); gl_call(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)); // Default vertex buffer budget. This is not static, so no worries for(auto& vao : stream_vaos_) { vao.create(); } // Default vertex buffer budget. This is not static, so no worries for(auto& vbo : stream_vbos_) { vbo.create(); vbo.bind(); vbo.reserve(nullptr, sizeof(vertex_2d) * 1024, true); vbo.unbind(); } // Default index buffer budget. This is not static, so no worries for(auto& ibo : stream_ibos_) { ibo.create(); ibo.bind(); ibo.reserve(nullptr, sizeof(draw_list::index_t) * 1024, true); ibo.unbind(); } reset_transform(); set_model_view(0, rect_); auto create_program = [&](auto& program, auto fs, auto vs) { if(!program.shader) { auto shader = create_shader(fs, vs); embedded_shaders_.emplace_back(shader); program.shader = shader.get(); auto& layout = shader->get_layout(); constexpr auto stride = sizeof(vertex_2d); layout.template add<float>(2, offsetof(vertex_2d, pos), "aPosition", stride); layout.template add<float>(2, offsetof(vertex_2d, uv), "aTexCoord", stride); layout.template add<uint8_t>(4, offsetof(vertex_2d, col) ,"aColor", stride, true); layout.template add<uint8_t>(4, offsetof(vertex_2d, extra_col) , "aExtraColor", stride, true); layout.template add<float>(2, offsetof(vertex_2d, extra_data), "aExtraData", stride); layout.template add<uint32_t>(1, offsetof(vertex_2d, tex_idx), "aTexIndex", stride); } }; create_program(get_program<programs::simple>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_simple).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::multi_channel>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_multi_channel).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::multi_channel_crop>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(user_defines) .append(fs_multi_channel).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::single_channel>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_single_channel).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::single_channel_crop>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(user_defines) .append(fs_single_channel).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::distance_field>(), std::string(glsl_version) .append(glsl_derivatives) .append(glsl_precision) .append(common_funcs) .append(fs_distance_field).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::distance_field_crop>(), std::string(glsl_version) .append(glsl_derivatives) .append(glsl_precision) .append(common_funcs) .append(user_defines) .append(fs_distance_field).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::distance_field_supersample>(), std::string(glsl_version) .append(glsl_derivatives) .append(glsl_precision) .append(common_funcs) .append(supersample) .append(fs_distance_field).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::distance_field_crop_supersample>(), std::string(glsl_version) .append(glsl_derivatives) .append(glsl_precision) .append(common_funcs) .append(user_defines) .append(supersample) .append(fs_distance_field).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::alphamix>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_alphamix).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::valphamix>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_valphamix).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::halphamix>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_halphamix).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::raw_alpha>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_raw_alpha).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::grayscale>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_grayscale).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); create_program(get_program<programs::blur>(), std::string(glsl_version) .append(glsl_precision) .append(common_funcs) .append(fs_blur).c_str(), std::string(glsl_version) .append(vs_simple).c_str()); if(!font_default()) { font_default() = create_font(create_default_font(13), true); } master_list_.reserve_rects(4096); dummy_list_.add_line({0, 0}, {1, 1}, {0, 0, 0, 0}); setup_sampler(texture::wrap_type::wrap_clamp, texture::interpolation_type::interpolate_linear); setup_sampler(texture::wrap_type::wrap_repeat, texture::interpolation_type::interpolate_linear); setup_sampler(texture::wrap_type::wrap_mirror, texture::interpolation_type::interpolate_linear); setup_sampler(texture::wrap_type::wrap_clamp, texture::interpolation_type::interpolate_none); setup_sampler(texture::wrap_type::wrap_repeat, texture::interpolation_type::interpolate_none); setup_sampler(texture::wrap_type::wrap_mirror, texture::interpolation_type::interpolate_none); clear(color::black()); present(); clear(color::black()); frame_callbacks_ = std::move(fn); if (frame_callbacks_.on_start_frame) { frame_callbacks_.on_start_frame(*this); } } void renderer::setup_sampler(texture::wrap_type wrap, texture::interpolation_type interp) noexcept { uint32_t sampler_state = 0; gl_call(glGenSamplers(1, &sampler_state)); switch (wrap) { case texture::wrap_type::wrap_mirror: gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT)); gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT)); break; case texture::wrap_type::wrap_repeat: gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_S, GL_REPEAT)); gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_T, GL_REPEAT)); break; case texture::wrap_type::wrap_clamp: default: gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); break; } switch (interp) { case texture::interpolation_type::interpolate_none: gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); break; case texture::interpolation_type::interpolate_linear: default: gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); gl_call(glSamplerParameteri(sampler_state, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); break; } samplers_[size_t(wrap)][size_t(interp)] = sampler_state; } renderer::~renderer() { set_current_context(); delete_textures(); embedded_fonts_.clear(); embedded_shaders_.clear(); auto clear_embedded = [](auto& shared) { if(shared.use_count() == 1) { shared.reset(); } }; clear_embedded(font_default()); clear_embedded(font_regular()); clear_embedded(font_bold()); clear_embedded(font_black()); clear_embedded(font_monospace()); } draw_list& renderer::get_list() const noexcept { if (fbo_stack_.empty()) { return master_list_; } return fbo_stack_.top().list; } renderer::transform_stack& renderer::get_transform_stack() const noexcept { if (fbo_stack_.empty()) { return master_transforms_; } return fbo_stack_.top().transforms; } void renderer::flush() const noexcept { draw_cmd_list(get_list()); get_list().clear(); } void renderer::check_stacks() const noexcept { assert(fbo_stack_.empty() && "fbo stack was not popped"); } void renderer::queue_to_delete_texture(pixmap pixmap_id, uint32_t fbo_id, uint32_t texture_id) const { if (pixmap_id != pixmap_invalid_id) { pixmap_to_delete_.push_back(pixmap_id); } if (fbo_id > 0) { fbo_to_delete_.push_back(fbo_id); } if (texture_id > 0) { textures_to_delete_.push_back(texture_id); } } void renderer::delete_textures() noexcept { for (auto& pixmap_id : pixmap_to_delete_) { context_->destroy_pixmap(pixmap_id); } pixmap_to_delete_.clear(); if (!fbo_to_delete_.empty()) { gl_call(glDeleteFramebuffers(GLsizei(fbo_to_delete_.size()), fbo_to_delete_.data())); fbo_to_delete_.clear(); } if (!textures_to_delete_.empty()) { // Destroy texture gl_call(glDeleteTextures(GLsizei(textures_to_delete_.size()), textures_to_delete_.data())); textures_to_delete_.clear(); } } /// Bind FBO, set projection, switch to modelview /// @param fbo - framebuffer object, use 0 for the backbuffer /// @param rect - the dirty area to draw into void renderer::set_model_view(uint32_t fbo, const rect& rect) const noexcept { // Bind the FBO or backbuffer if 0 gl_call(glBindFramebuffer(GL_FRAMEBUFFER, fbo)); // Set the viewport gl_call(glViewport(0, 0, rect.w, rect.h)); // Set the projection if(fbo == 0) { // If we have 0 it is the back buffer current_ortho_ = math::ortho<float>(0, float(rect.w), float(rect.h), 0, 0, FARTHEST_Z); } else { // If we have > 0 the fbo must be flipped current_ortho_ = math::ortho<float>(0, float(rect.w), 0, float(rect.h), 0, FARTHEST_Z); } // // Switch to modelview matrix and setup identity // reset_transform(); } /// Bind this renderer & window /// @return true on success bool renderer::set_current_context() const noexcept { return context_->make_current(); } /// void renderer::set_old_framebuffer() const noexcept { if (fbo_stack_.empty()) { gl_call(glBindFramebuffer(GL_FRAMEBUFFER, 0)); return; } const auto& top_texture = fbo_stack_.top(); gl_call(glBindFramebuffer(GL_FRAMEBUFFER, top_texture.fbo->get_FBO())); } /// Resize the dirty rectangle /// @param new_width - the new width /// @param new_height - the new height void renderer::resize(int new_width, int new_height) noexcept { rect_.w = new_width; rect_.h = new_height; } texture_ptr renderer::create_texture(const surface& surface, bool empty) const noexcept { if(!set_current_context()) { return {}; } try { auto tex = new texture(*this, surface, empty); return texture_ptr(tex); } catch(const exception& e) { log(std::string("ERROR: Cannot create texture from surface. Reason ") + e.what()); } return texture_ptr(nullptr); } texture_ptr renderer::create_texture(const surface& surface, size_t level_id, size_t layer_id, size_t face_id) const noexcept { if(!set_current_context()) { return {}; } try { auto tex = new texture(*this, surface, level_id, layer_id, face_id); return texture_ptr(tex); } catch(const exception& e) { log(std::string("ERROR: Cannot create texture from surface. Reason ") + e.what()); } return texture_ptr(nullptr); } texture_ptr renderer::create_texture(const std::string& file_name) const noexcept { if(!set_current_context()) { return {}; } try { surface surf(file_name); auto tex = new texture(*this, surf); texture_ptr texture(tex); return texture; } catch(const exception& e) { log(std::string("ERROR: Cannot create texture from file. Reason ") + e.what()); } return texture_ptr(); } /// Create a blank texture /// @param w, h - size of texture /// @param pixel_type - color type of pixel /// @param format_type - texture puprose /// @param allocatorName - allocator name /// @return a shared pointer to the produced texture texture_ptr renderer::create_texture(int w, int h, pix_type pixel_type, texture::format_type format_type) const noexcept { if(!set_current_context()) { return {}; } try { auto tex = new texture(*this, w, h, pixel_type, format_type); return texture_ptr(tex); } catch(const exception& e) { log(std::string("ERROR: Cannot create blank texture. Reason ") + e.what()); } return texture_ptr(); } texture_ptr renderer::create_texture(const texture_src_data& data) const noexcept { if(!set_current_context()) { return {}; } try { auto tex = new texture(*this, data); return texture_ptr(tex); } catch(const exception& e) { log(std::string("ERROR: Cannot create blank texture. Reason ") + e.what()); } return texture_ptr(); } /// Create a shader /// @param fragment_code - fragment shader written in GLSL /// @param vertex_code - vertex shader code written in GLSL /// @return a shared pointer to the shader shader_ptr renderer::create_shader(const char* fragment_code, const char* vertex_code) const noexcept { if(!set_current_context()) { return {}; } try { auto* shad = new shader(*this, fragment_code, vertex_code); return shader_ptr(shad); } catch(const exception& e) { log(std::string("ERROR: Cannot create shader. Reason ") + e.what()); } return {}; } /// Create a font /// @param info - description of font /// @return a shared pointer to the font font_ptr renderer::create_font(font_info&& info, bool embedded) const noexcept { if(!set_current_context()) { return {}; } try { auto r = std::make_shared<font>(); font_info& slice = *r; slice = std::move(info); r->texture = texture_ptr(new texture(*this, *r->surface)); if(r->sdf_spread == 0) { r->texture->generate_mipmap(); } r->surface.reset(); if(embedded) { embedded_fonts_.emplace_back(r); } return r; } catch(const exception& e) { log(std::string("ERROR: Cannot create font. Reason ") + e.what()); } return {}; } /// Set the blending mode for drawing /// @param mode - blending mode to set /// @return true on success bool renderer::set_blending_mode(blending_mode mode) const noexcept { if(!set_current_context()) { return false; } switch(mode) { case blending_mode::blend_none: gl_call(glDisable(GL_BLEND)); break; case blending_mode::blend_normal: gl_call(glEnable(GL_BLEND)); gl_call(glBlendEquation(GL_FUNC_ADD)); gl_call(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); break; case blending_mode::blend_add: gl_call(glEnable(GL_BLEND)); gl_call(glBlendEquation(GL_FUNC_ADD)); gl_call(glBlendFunc(GL_SRC_ALPHA, GL_ONE)); break; case blending_mode::blend_lighten: gl_call(glEnable(GL_BLEND)); gl_call(glBlendEquation(GL_MAX)); gl_call(glBlendFunc(GL_ONE, GL_ONE)); break; case blending_mode::pre_multiplication: gl_call(glEnable(GL_BLEND)); gl_call(glBlendEquation(GL_FUNC_ADD)); gl_call(glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE)); break; case blending_mode::unmultiplied_alpha: gl_call(glEnable(GL_BLEND)); gl_call(glBlendEquation(GL_FUNC_ADD)); gl_call(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)); break; case blending_mode::blend_screen: default: // TODO gl_call(glEnable(GL_BLEND)); break; } return true; } blending_mode renderer::get_apropriate_blend_mode(blending_mode mode, const gpu_program &program) const noexcept { if(!fbo_stack_.empty()) { const auto& fbo = fbo_stack_.top().fbo; if(fbo->get_pix_type() == pix_type::rgba) { // When drawing into a fbo which has an alpha channel // the proper blending should be pre_multiplication // We do this here so that it is hidden from the end user if( mode == blending_mode::blend_normal && program.shader != get_program<programs::raw_alpha>().shader ) { mode = blending_mode::pre_multiplication; } } } return mode; } /// Lowest level texture binding call, for both fixed pipeline and shaders, and provide optional wrapping and interpolation modes /// @param texture - the texture view /// @param id - texture unit id (for the shader) /// @param wrap_type - wrapping type /// @param interp_type - interpolation type bool renderer::set_texture(texture_view texture, uint32_t id) const noexcept { // Activate texture for shader gl_call(glActiveTexture(GL_TEXTURE0 + id)); // Bind texture to the pipeline, and the currently active texture gl_call(glBindTexture(GL_TEXTURE_2D, texture.id)); return true; } /// Reset a texture slot /// @param id - the texture to reset void renderer::reset_texture(uint32_t id) const noexcept { gl_call(glActiveTexture(GL_TEXTURE0 + id)); gl_call(glBindTexture(GL_TEXTURE_2D, 0)); } void renderer::set_texture_sampler(texture_view texture, uint32_t id) const noexcept { auto sampler = samplers_[size_t(texture.wrap_type)][size_t(texture.interp_type)]; if(sampler != 0) { gl_call(glBindSampler(id, sampler)); } else { log("ERROR: Undefined sampler used! If it's legit - add it on initialization phase"); //auto add? } } void renderer::reset_texture_sampler(uint32_t id) const noexcept { // Unbind active sampler gl_call(glBindSampler(id, 0)); } bool renderer::bind_pixmap(const pixmap& p) const noexcept { return context_->bind_pixmap(p); } /// Reset a texture slot /// @param id - the texture to reset void renderer::unbind_pixmap(const pixmap& p) const noexcept { context_->unbind_pixmap(p); } texture_ptr renderer::blur(const texture_ptr& texture, uint32_t passes) { passes = std::max<uint32_t>(1, passes); texture_ptr input = texture; auto radius = passes / 2.0f; for(uint32_t i = 0; i < passes; ++i) { if(i % 2 == 0) { radius = ((passes - i)/ 2.0f); } auto input_size = math::vec2(input->get_rect().w, input->get_rect().h); auto fbo = create_texture(int(input_size.x), int(input_size.y), input->get_pix_type(), texture::format_type::streaming); auto direction = i % 2 == 0 ? math::vec2{radius, 0.0f} : math::vec2{0.0f, radius}; if (!push_fbo(fbo)) { return {}; } draw_list list; program_setup setup; setup.program = get_program<programs::blur>(); setup.begin = [=](const gpu_context& ctx) { ctx.program.shader->set_uniform("uTexture", input); ctx.program.shader->set_uniform("uTextureSize", input_size); ctx.program.shader->set_uniform("uDirection", direction); }; list.add_image(input, input->get_rect(), fbo->get_rect(), {}, color::white(), flip_format::none, setup); draw_cmd_list(list); if (!pop_fbo()) { return {}; } input = fbo; } return input; } /// Push and load a modelview matrix /// @param transform - the transformation to push /// @return true on success bool renderer::push_transform(const math::transformf& transform) const noexcept { auto& transforms = get_transform_stack(); if(transforms.empty()) { transforms.push(transform); } else { const auto& top = transforms.top(); transforms.push(top * transform.get_matrix()); } return true; } /// Restore a previously set matrix /// @return true on success bool renderer::pop_transform() const noexcept { auto& transforms = get_transform_stack(); transforms.pop(); if (transforms.empty()) { reset_transform(); } return true; } /// Reset the modelview transform to identity /// @return true on success bool renderer::reset_transform() const noexcept { auto& transforms = get_transform_stack(); transform_stack new_tranform; new_tranform.push(math::transformf::identity()); transforms.swap(new_tranform); return true; } math::transformf renderer::get_transform() const noexcept { auto& transforms = get_transform_stack(); return transforms.top(); } /// Set scissor test rectangle /// @param rect - rectangle to clip /// @return true on success bool renderer::push_clip(const rect& rect) const noexcept { if (!set_current_context()) { return false; } gl_call(glEnable(GL_SCISSOR_TEST)); auto mod_clip = rect; const auto& transforms = get_transform_stack(); if (transforms.size() > 1) { const auto trans = math::transformf{transforms.top()}; const auto& scale = trans.get_scale(); const auto& pos = trans.get_position(); mod_clip.x = int(float(mod_clip.x) * scale.x + pos.x); mod_clip.y = int(float(mod_clip.y) * scale.y + pos.y); mod_clip.w = int(float(rect.w) * scale.x); mod_clip.h = int(float(rect.h) * scale.y); } if (fbo_stack_.empty()) { // If we have no fbo_target_ it is a back buffer gl_call(glScissor(mod_clip.x, rect_.h - mod_clip.y - mod_clip.h, mod_clip.w, mod_clip.h)); } else { gl_call(glScissor(mod_clip.x, mod_clip.y, mod_clip.w, mod_clip.h)); } return true; } bool renderer::pop_clip() const noexcept { if (!set_current_context()) { return false; } gl_call(glDisable(GL_SCISSOR_TEST)); return true; } /// Set FBO target for drawing /// @param texture - texture to draw to /// @return true on success bool renderer::push_fbo(const texture_ptr& texture) { if (texture->format_type_ != texture::format_type::streaming) { return false; } if (!set_current_context()) { return false; } fbo_stack_.emplace(); auto& top_texture = fbo_stack_.top(); top_texture.fbo = texture; top_texture.transforms.push(math::transformf::identity()); set_model_view(top_texture.fbo->get_FBO(), top_texture.fbo->get_rect()); return true; } /// Set old FBO target for drawing. if empty set draw to back render buffer /// @return true on success bool renderer::pop_fbo() { if (fbo_stack_.empty()) { return false; } if (!set_current_context()) { return false; } draw_cmd_list(fbo_stack_.top().list); fbo_stack_.pop(); if (fbo_stack_.empty()) { set_model_view(0, rect_); return true; } auto& top_texture = fbo_stack_.top(); set_model_view(top_texture.fbo->get_FBO(), top_texture.fbo->get_rect()); return true; } /// Remove all FBO targets from stack and set draw to back render buffer /// @return true on success bool renderer::reset_fbo() { if (!set_current_context()) { return false; } while (!fbo_stack_.empty()) { draw_cmd_list(fbo_stack_.top().list); fbo_stack_.pop(); } set_model_view(0, rect_); return true; } bool renderer::is_with_fbo() const { return !fbo_stack_.empty(); } /// Swap buffers void renderer::present() noexcept { auto sz = win_.get_size(); resize(int(sz.w), int(sz.h)); // { // const auto& stats = get_stats(); // gfx::text text; // text.set_font(gfx::default_font(), 24); // text.set_utf8_text(stats.to_string()); // text.set_outline_width(0.1f); // math::transformf t {}; // t.set_position(0, 100); // get_list().add_text(text, t); // } if (frame_callbacks_.on_end_frame) { frame_callbacks_.on_end_frame(*this); } if(!master_list_.commands_requested) { // due to bug in the driver // we must keep it busy draw_cmd_list(dummy_list_); } else { draw_cmd_list(master_list_); master_list_.clear(); } last_stats_ = stats_; stats_ = {}; context_->swap_buffers(); set_current_context(); delete_textures(); reset_transform(); set_model_view(0, rect_); if (frame_callbacks_.on_start_frame) { frame_callbacks_.on_start_frame(*this); } } /// Clear the currently bound buffer /// @param color - color to clear with void renderer::clear(const color& color) const noexcept { set_current_context(); if (fbo_stack_.empty()) { master_list_.push_blend(blending_mode::blend_none); master_list_.add_rect(get_rect(), color); master_list_.pop_blend(); return; } auto& fbo_info = fbo_stack_.top(); fbo_info.list.push_blend(blending_mode::blend_none); fbo_info.list.add_rect(fbo_info.fbo->get_rect(), color); fbo_info.list.pop_blend(); } constexpr uint16_t get_index_type() { if(sizeof(draw_list::index_t) == sizeof(uint32_t)) { return GL_UNSIGNED_INT; } return GL_UNSIGNED_SHORT; } /// Render a draw list /// @param list - list to draw /// @return true on success bool renderer::draw_cmd_list(const draw_list& list) const noexcept { if (list.empty()) { return false; } if (!set_current_context()) { return false; } stats_.record(list); list.validate_stacks(); // EGT_BLOCK_PROFILING("renderer::draw_cmd_list - %d commands", int(list.commands.size())) const auto vtx_stride = sizeof(decltype(list.vertices)::value_type); const auto vertices_mem_size = list.vertices.size() * vtx_stride; const auto idx_stride = sizeof(decltype(list.indices)::value_type); const auto indices_mem_size = list.indices.size() * idx_stride; // We are using several stream buffers to avoid syncs caused by // uploading new data while the old one is still processing auto& vao = stream_vaos_[current_vao_idx_]; auto& vbo = stream_vbos_[current_vbo_idx_]; auto& ibo = stream_ibos_[current_ibo_idx_]; current_vao_idx_ = (current_vao_idx_ + 1) % stream_vaos_.size(); current_vbo_idx_ = (current_vbo_idx_ + 1) % stream_vbos_.size(); current_ibo_idx_ = (current_ibo_idx_ + 1) % stream_ibos_.size(); bool mapped = get_draw_config().mapped_buffers; { // EGT_BLOCK_PROFILING("draw_cmd_list::vao/vbo/ibo") // Bind the vertex array object vao.bind(); // Bind the vertex buffer vbo.bind(); // Upload vertices to VRAM if (!vbo.update(list.vertices.data(), 0, vertices_mem_size, mapped)) { // We're out of vertex budget. Allocate a new vertex buffer vbo.reserve(list.vertices.data(), vertices_mem_size, true); } // Bind the index buffer ibo.bind(); // Upload indices to VRAM if (!ibo.update(list.indices.data(), 0, indices_mem_size, mapped)) { // We're out of index budget. Allocate a new index buffer ibo.reserve(list.indices.data(), indices_mem_size, true); } } { blending_mode last_blend{blending_mode::blend_none}; set_blending_mode(last_blend); // Draw commands for (const auto& cmd : list.commands) { // EGT_BLOCK_PROFILING("draw_cmd_list::cmd") { if(cmd.setup.program.shader) { // EGT_BLOCK_PROFILING("draw_cmd_list::shader.enable") cmd.setup.program.shader->enable(); } if (cmd.clip_rect) { push_clip(cmd.clip_rect); } if(cmd.setup.begin) { // EGT_BLOCK_PROFILING("draw_cmd_list::cmd.setup.begin") cmd.setup.begin(gpu_context{cmd, *this, cmd.setup.program}); } if(cmd.setup.program.shader && cmd.setup.program.shader->has_uniform("uProjection")) { const auto& projection = current_ortho_ * get_transform_stack().top(); cmd.setup.program.shader->set_uniform("uProjection", projection); } if (cmd.blend != last_blend) { auto mode = get_apropriate_blend_mode(cmd.blend, cmd.setup.program); set_blending_mode(mode); last_blend = mode; } } switch(cmd.dr_type) { case draw_type::elements: { // EGT_BLOCK_PROFILING("draw_cmd_list::glDrawElements - %d indices", int(cmd.indices_count)) gl_call(glDrawElements(to_gl_primitive(cmd.type), GLsizei(cmd.indices_count), get_index_type(), reinterpret_cast<const GLvoid*>(uintptr_t(cmd.indices_offset * idx_stride)))); } break; case draw_type::array: { // EGT_BLOCK_PROFILING("draw_cmd_list::glDrawArrays") gl_call(glDrawArrays(to_gl_primitive(cmd.type), GLint(cmd.vertices_offset), GLsizei(cmd.vertices_count))); } break; default: break; } { if (cmd.setup.end) { // EGT_BLOCK_PROFILING("draw_cmd_list::cmd.setup.end") cmd.setup.end(gpu_context{cmd, *this, cmd.setup.program}); } if (cmd.clip_rect) { pop_clip(); } if(cmd.setup.program.shader) { // EGT_BLOCK_PROFILING("draw_cmd_list::shader.disable") cmd.setup.program.shader->disable(); } } } set_blending_mode(blending_mode::blend_none); } vbo.unbind(); ibo.unbind(); vao.unbind(); if(list.debug) { draw_cmd_list(*list.debug); } return true; } /// Enable vertical synchronization to avoid tearing /// @return true on success bool renderer::enable_vsync() noexcept { return context_->set_vsync(true); } /// Disable vertical synchronization /// @return true on success bool renderer::disable_vsync() noexcept { return context_->set_vsync(false); } bool renderer::set_vsync(bool vsync) noexcept { return context_->set_vsync(vsync); } /// Get the dirty rectangle we're drawing into /// @return the currently used rect const rect& renderer::get_rect() const { if (fbo_stack_.empty()) { const auto& transforms = get_transform_stack(); if (transforms.size() > 1) // skip identity matrix { transformed_rect_ = inverse_and_tranfrom_rect(rect_, math::transformf{transforms.top()}); return transformed_rect_; } return rect_; } const auto& top_stack = fbo_stack_.top(); const auto& fbo = top_stack.fbo; const auto& transforms = top_stack.transforms; if (transforms.size() > 1) // skip identity matrix { const auto& rect = fbo->get_rect(); transformed_rect_ = inverse_and_tranfrom_rect(rect, math::transformf{transforms.top()}); return transformed_rect_; } return fbo->get_rect(); } const gpu_stats& renderer::get_stats() const { return last_stats_; } void gpu_stats::record(const draw_list& list) { requested_calls += size_t(list.commands_requested); rendered_calls += list.commands.size(); batched_calls += size_t(list.commands_requested) - list.commands.size(); vertices += list.vertices.size(); indices += list.indices.size(); size_t req_opaque_calls = 0; size_t rend_opaque_calls = 0; size_t req_blended_calls = 0; size_t rend_blended_calls = 0; for(const auto& cmd : list.commands) { if(cmd.blend == blending_mode::blend_none) { req_opaque_calls += cmd.subcount; rend_opaque_calls++; } else { req_blended_calls += cmd.subcount; rend_blended_calls++; } } requested_opaque_calls += req_opaque_calls; requested_blended_calls += req_blended_calls; rendered_opaque_calls += rend_opaque_calls; rendered_blended_calls += rend_blended_calls; batched_opaque_calls += req_opaque_calls - rend_opaque_calls; batched_blended_calls += req_blended_calls - rend_blended_calls; } std::string gpu_stats::to_string() const { std::stringstream ss; ss << "Requested:" << requested_calls << "\n" << " - Opaque: " << requested_opaque_calls << "\n" << " - Blended: " << requested_blended_calls << "\n" << "Rendered:" << rendered_calls << "\n" << " - Opaque: " << rendered_opaque_calls << "\n" << " - Blended: " << rendered_blended_calls << "\n" << "Batched:" << batched_calls << "\n" << " - Opaque: " << batched_opaque_calls << "\n" << " - Blended: " << batched_blended_calls; return ss.str(); } }
28.605699
129
0.595237
volcoma
40aa48dbd3b5f3fa4ff29e6e8fae3a3a934fe6a2
4,884
cpp
C++
main.cpp
felixny/Arkanoid
882118a8ca5f3e7228767f3a963c82619b0aa54e
[ "MIT" ]
null
null
null
main.cpp
felixny/Arkanoid
882118a8ca5f3e7228767f3a963c82619b0aa54e
[ "MIT" ]
null
null
null
main.cpp
felixny/Arkanoid
882118a8ca5f3e7228767f3a963c82619b0aa54e
[ "MIT" ]
null
null
null
#ifdef __APPLE__ /* Defined before OpenGL and GLUT includes to avoid deprecation messages */ #define GL_SILENCE_DEPRECATION #endif #include <iostream> #include "GL/glut.h" #include "glm/glm.hpp" #include "glm/gtc/constants.hpp" #define WINDOW_WIDTH (1280) #define WINDOW_HEIGHT (720) #define BLOCK_WIDTH (128) #define BLOCK_HEIGHT (32) #define BLOCK_COLUMN_MAX (WINDOW_WIDTH / BLOCK_WIDTH) #define BLOCK_ROW_MAX (6) #define PADDLE_WIDTH (128) #define PADDLE_HEIGHT (32) #define BALL_RADIUS (10) #define BALL_SPEED (WINDOW_HEIGHT / (60.0f)) typedef struct { bool isHit; } BLOCK; typedef struct { glm::vec2 position; } PADDLE; typedef struct { glm::vec2 position; glm::vec2 lastPosition; glm::vec2 velocity; } BALL; BLOCK blocks[BLOCK_ROW_MAX][BLOCK_COLUMN_MAX]; PADDLE paddle; BALL ball; void Init(void) { memset(blocks, 0, sizeof(blocks)); paddle.position = {WINDOW_WIDTH / 2 - PADDLE_WIDTH / 2, WINDOW_HEIGHT - PADDLE_HEIGHT * 2}; ball.lastPosition = ball.position = {WINDOW_WIDTH / 2, BLOCK_HEIGHT * BLOCK_ROW_MAX}; ball.velocity = {BALL_SPEED, BALL_SPEED}; ball.velocity = glm::normalize(ball.velocity) * BALL_SPEED; } void Display(void) { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); for (int y = 0; y < BLOCK_ROW_MAX; y++) { const unsigned char colors[][3] = {{0xff, 0x00, 0x00}, {0xff, 0xff, 0x00}, {0x00, 0xff, 0x00}, {0x00, 0xff, 0xff}, {0x00, 0x00, 0xff}, {0xff, 0x00, 0xff}}; glColor3ubv((GLubyte*)&colors[y]); for (int x = 0; x < BLOCK_COLUMN_MAX; x++) { if (blocks[y][x].isHit) continue; glPushMatrix(); { glTranslated(BLOCK_WIDTH * x, BLOCK_HEIGHT * y, 0); glBegin(GL_QUADS); { glVertex2d(0, 0); glVertex2d(0, BLOCK_HEIGHT - 1); glVertex2d(BLOCK_WIDTH - 1, BLOCK_HEIGHT - 1); glVertex2d(BLOCK_WIDTH - 1, 0); } glEnd(); } glPopMatrix(); } } glColor3ub(0xff, 0xff, 0xff); glPushMatrix(); { glTranslatef(paddle.position.x, paddle.position.y, 0); glBegin(GL_QUADS); { glVertex2d(0, 0); // left upper glVertex2d(0, PADDLE_HEIGHT); // left bottom glVertex2d(PADDLE_WIDTH, PADDLE_HEIGHT); glVertex2d(PADDLE_WIDTH, 0); } glEnd(); } glPopMatrix(); glPushMatrix(); { glTranslatef(ball.position.x, ball.position.y, 0); glScalef(BALL_RADIUS, BALL_RADIUS, 0); glBegin(GL_TRIANGLE_FAN); { glVertex2f(0, 0); int n = 32; for (int i = 0; i <= n; i++) { float r = glm::pi<float>() * 2 * i / n; glVertex2f(cosf(r), -sinf(r)); } } glEnd(); } glPopMatrix(); glutSwapBuffers(); } void Idle(void) { ball.lastPosition = ball.position; ball.position += ball.velocity; if (ball.position.y >= WINDOW_HEIGHT){ Init(); glutPostRedisplay(); return; } if ((ball.position.x < 0) || (ball.position.x >= WINDOW_WIDTH)) { ball.position = ball.lastPosition; ball.velocity.x *= -1.0f; } if ((ball.position.y < 0) || (ball.position.y >= WINDOW_HEIGHT)) { ball.position = ball.lastPosition; ball.velocity.y *= -1.0f; } if ((ball.position.x >= paddle.position.x) && (ball.position.x < paddle.position.x + PADDLE_WIDTH) && (ball.position.y >= paddle.position.y) && (ball.position.y < paddle.position.y + PADDLE_HEIGHT)) { ball.position = ball.lastPosition; float paddleCenterX = paddle.position.x + PADDLE_WIDTH / 2; ball.velocity.x = (ball.position.x - paddleCenterX) / (PADDLE_WIDTH / 2) * 1.5; ball.velocity.y = -glm::sign(ball.velocity.y); ball.velocity = glm::normalize(ball.velocity) * BALL_SPEED; } { // if the ball hits, then destory the block int x = (int)ball.position.x / BLOCK_WIDTH; int y = (int)ball.position.y / BLOCK_HEIGHT; if ((x >= 0) && (x < BLOCK_COLUMN_MAX) && (y >= 0) && (y < BLOCK_ROW_MAX) && (!blocks[y][x].isHit)) { ball.position = ball.lastPosition; blocks[y][x].isHit = true; if ((ball.lastPosition.y < BLOCK_HEIGHT * y) || (ball.lastPosition.y >= BLOCK_HEIGHT * (y + 1))) ball.velocity.y *= -1.0f; else ball.velocity.x *= -1.0f; } } glutPostRedisplay(); } void PassiveMotion(int _x, int _y) { paddle.position.x = (float)_x - PADDLE_WIDTH / 2; } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow("Arkanoid"); glutDisplayFunc(Display); glutIdleFunc(Idle); glutPassiveMotionFunc(PassiveMotion); Init(); glutMainLoop(); }
26.4
80
0.620188
felixny
40ab65644706877b5a3b0aaa78967a933c9d55fe
713
cpp
C++
src/ui/simulator/simulator_app.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/ui/simulator/simulator_app.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/ui/simulator/simulator_app.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ #include "ui/simulator/simulator_app.h" #include "ui/simulator/simulator_frame.h" using vulcan::ui::SimulatorApp; IMPLEMENT_APP(SimulatorApp) bool SimulatorApp::OnInit(void) { mainFrame = new SimulatorFrame(); mainFrame->Show(true); SetTopWindow(mainFrame); return true; } int SimulatorApp::OnExit(void) { return 0; }
20.371429
95
0.740533
anuranbaka
40ac2035b46fb78dacc2e3f1717289c4bf402901
80,407
cpp
C++
deps/UMFLP/src/Functions.cpp
vOptSolver/vOptSpecific
9705cf4fde20dfb14c7f7f6e32b7df1d597b383d
[ "MIT" ]
5
2017-10-06T06:25:28.000Z
2021-10-15T13:23:44.000Z
deps/UMFLP/src/Functions.cpp
vOptSolver/vOptSpecific
9705cf4fde20dfb14c7f7f6e32b7df1d597b383d
[ "MIT" ]
6
2018-02-09T17:14:20.000Z
2021-07-24T14:10:09.000Z
deps/UMFLP/src/Functions.cpp
vOptSolver/vOptSpecific
9705cf4fde20dfb14c7f7f6e32b7df1d597b383d
[ "MIT" ]
4
2017-08-28T22:28:05.000Z
2020-02-08T11:13:33.000Z
/* #License and Copyright #Version : 1.3 #This file is part of BiUFLv2017. #BiUFLv2017 is Copyright © 2017, University of Nantes #BiUFLv2017 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program; if not, you can also find the GPL on the GNU web site. #In addition, we kindly ask you to acknowledge BiUFLv2017 and its authors in any program or publication in which you use BiUFLv2017. (You are not required to do so; it is up to your common sense to decide whether you want to comply with this request or not.) For general publications, we suggest referencing: BiUFLv2017, MSc ORO, University of Nantes. #Non-free versions of BiUFLv2017 are available under terms different from those of the General Public License. (e.g. they do not require you to accompany any object code using BiUFLv2012 with the corresponding source code.) For these alternative terms you must purchase a license from Technology Transfer Office of the University of Nantes. Users interested in such a license should contact us (valorisation@univ-nantes.fr) for more information. */ #include "Functions.hpp" long int createBox(vector<Box*> &vectorBox, vector<string> openedFacility, Data &data) { long int nbBoxComputed = 0; int currentSize = vectorBox.size() ; //Add the first boxes with only one facility opened Box *box0 = new Box(data); addChildren(box0,vectorBox,data); delete box0; for(unsigned int it = currentSize; it < vectorBox.size();) { nbBoxComputed++; if( data.modeImprovedUB && isAlreadyIn(openedFacility,vectorBox[it]) ) { // If box has already been computed in the Upper Bound Set, we add its children and we delete the doublon. if( vectorBox[it]->getNbFacilityOpen() < (data.BoundDeepNess - 1) ) { addChildren(vectorBox[it],vectorBox,data); } delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); } else if( isDominatedByItsOrigin(vectorBox,vectorBox[it]) ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); } else { if( data.modeLowerBound ) { computeLowerBound(vectorBox[it],data); } if( data.modeLowerBound && isDominatedByItsLowerBound(vectorBox,vectorBox[it],data) ) { // If Lower Bound Set is dominated, we can delete current box and cut the node. Children does not need to be added as the LBS is valable for the Children. delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); } else { //Compute bounds of this box vectorBox[it]->computeBox(data); //Compute all potential children of this box as candidates boxes if( vectorBox[it]->getNbFacilityOpen() < (data.BoundDeepNess - 1) ) { addChildren(vectorBox[it],vectorBox,data); } if( data.modeDichoBnB && vectorBox[it]->getHasEdge() ) { weightedSumOneStep(vectorBox[it],data); } //If this box is dominated by all the boxes (existing + its children) regarding to its bounds if( isDominatedByItsBox(vectorBox,vectorBox[it]) ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); } else { //If one of all others boxes are dominated by this box, we delete it for(unsigned int it2 = 0; it2 != it;) { if(isDominatedBetweenTwoBoxes(vectorBox[it2],vectorBox[it])) { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); //We delete an element before (the list shift one step forward), so we shift one step backward it--; } else { it2++; } } it++; } } } } return nbBoxComputed; } void addChildren(Box *boxMother, vector<Box*> &vBox, Data &data) { int deepness = 1 ; //To find the last digit at 1 in the open facility bool *facilityOpen = new bool[data.getnbFacility()]; int indexLastOpened = -1; if( data.modeSortFacility ) { for(unsigned int i = 0 ; i < data.getnbFacility() ; i++) { if(boxMother->isOpened(data.facilitySort[i])) { indexLastOpened = i; ++deepness ; } facilityOpen[data.facilitySort[i]] = boxMother->isOpened(data.facilitySort[i]); } //For each digit 0 of facilities not yet affected, we change it in 1 to create the corresponding a new combination for( unsigned int i = indexLastOpened + 1 ; i < data.getnbFacility() ; i++) { facilityOpen[data.facilitySort[i]] = true; Box *tmp = new Box(data,facilityOpen,data.facilitySort,i); vBox.push_back(tmp); facilityOpen[data.facilitySort[i]] = false; } } else { for(unsigned int i = 0 ; i < data.getnbFacility() ; i++) { if(boxMother->isOpened(i)) { indexLastOpened = i; ++deepness ; } facilityOpen[i] = boxMother->isOpened(i); } //For each digit 0 of facilities not yet affected, we change it in 1 to create the corresponding a new combination for(unsigned int i = indexLastOpened + 1 ; i < data.getnbFacility() ; i++) { facilityOpen[i] = true; Box *tmp = new Box(data,facilityOpen); vBox.push_back(tmp); facilityOpen[i] = false; } } if( deepness > data.MaxDeepNess ) data.MaxDeepNess = deepness ; delete []facilityOpen; } void computeUpperBound(vector<Box*> &vectorBox, vector<bool> &dichoSearch, Data &data) { if(vectorBox.size() < 2 ) { // If not done yet, compute first lexicographical point w.r.t. objective1 then objective2 Box* tmp = dualocprocedure(1.0,0.0,data); tmp->computeBox(data); vectorBox.push_back(tmp); } if(vectorBox.size() < 2 ) { // If not done yet, compute last lexicographical point w.r.t. objective2 then objective1 Box* tmp = dualocprocedure(0.0,1.0,data); tmp->computeBox(data); vectorBox.push_back(tmp); } if( vectorBox.size() == 2 ) { dichoSearch.push_back(true); } if( vectorBox.size() >= 2 ) { // For every pair of point, we compute a weighted sum. vector<Box*> tempBox = vector<Box*>() ; vector<bool> tempDicho = vector<bool>() ; for(unsigned int it = 0 ; it < vectorBox.size() - 1 ; ++it ) { tempBox.push_back(vectorBox[it]); if( !data.modeFullDicho && (vectorBox[it]->getId() == vectorBox[it+1]->getId()) ) { tempDicho.push_back(false); } else if( dichoSearch[it] ) { double alpha = 1.0 * ( vectorBox[it+1]->upperBoundObj1 - vectorBox[it]->upperBoundObj1 ) ; double beta = 1.0 * ( vectorBox[it]->upperBoundObj2 - vectorBox[it+1]->upperBoundObj2 ) ; Box* tmp = dualocprocedure(beta,alpha,data); if( ( beta * tmp->upperBoundObj1 + alpha * tmp->upperBoundObj2) < ( beta * vectorBox[it]->upperBoundObj1 + alpha * vectorBox[it]->upperBoundObj2) - data.epsilon ) { tmp->computeBox(data); tempBox.push_back(tmp); tempDicho.push_back(true); tempDicho.push_back(true); } else { tempDicho.push_back(false); } } else { tempDicho.push_back(false); } } // END FOR tempBox.push_back(vectorBox[vectorBox.size()-1]); vectorBox.clear() ; vectorBox = tempBox ; dichoSearch.clear() ; dichoSearch = tempDicho ; } } void computeLowerBound(Box *box, Data &data) { // We assign all the customer to their best possiblyOpenFacility for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { bool toStop1 = false; bool toStop2 = false; for(unsigned int j = 0 ; j < data.getnbFacility() && (!toStop1||!toStop2);++j) { for(unsigned int k = 0 ; k < box->possiblyOpenFacility.size() && !toStop1 ; ++k ) { if( data.customerSort[i][0][j] == box->possiblyOpenFacility[k] && !toStop1 ) { box->pointsLB[0] += data.getAllocationObj1Cost(i,box->possiblyOpenFacility[k]) ; box->pointsLB[1] += data.getAllocationObj2Cost(i,box->possiblyOpenFacility[k]) ; toStop1 = true ; } } for(unsigned int k = 0 ; k < box->possiblyOpenFacility.size() && !toStop2 ; ++k ) { if( data.customerSort[i][1][j] == box->possiblyOpenFacility[k] && !toStop2 ) { box->pointsLB[2] += data.getAllocationObj1Cost(i,box->possiblyOpenFacility[k]) ; box->pointsLB[3] += data.getAllocationObj2Cost(i,box->possiblyOpenFacility[k]) ; toStop2 = true ; } } } } // If ImprovedLB data.mode is on, we compute the supported points of the LBS. if( data.modeImprovedLB && box->pointsLB[0] != box->pointsLB[2] ) { parametricSearchLB(box,data); } } void filter(vector<Box*> &vectorBox) { //Filtering and update of booleans unsigned int size = vectorBox.size() ; for(unsigned int it = 0; it < size;) { for(unsigned int it2 = it + 1 ; it2 < size;) { if( isDominatedBetweenTwoBoxes(vectorBox[it2] , vectorBox[it]) ) { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); size-- ; } else if( isDominatedBetweenTwoBoxes(vectorBox[it] , vectorBox[it2]) ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin()+=it); it2 = it + 1 ; //Initialize it2 at the begin of the vector size-- ; } else { //it2 wasn't deleted it2++; } } //it wasn't deleted it++; } } void boxFiltering(vector<Box*> &vectorBox, Data &data) { bool MoreStep = true ; filter(vectorBox); // As long as there is some weighted sum to do, we do a weighted sum on all pair of point and update current box. Then we filter them with the new informations obtained. while(MoreStep) { weightedSumOneStepAll(vectorBox, data, MoreStep); filter(vectorBox); } } void weightedSumOneStep(Box* box, Data &data) { if( box->getHasMoreStepWS() ) { vector<double> temPoints = vector<double>(); vector<bool> tempEdges = vector<bool>() ; vector<bool> tempDicho = vector<bool>() ; for(unsigned int it2 = 0 ; it2 < box->points.size()-2 ; it2 = it2 + 2) { // For every pair of point of this box, we compute a weighted sum to improve current deepness by one. temPoints.push_back(box->points[it2]); temPoints.push_back(box->points[it2+1]); if( box->dicho[it2/2] && box->edges[it2/2] ) { double alpha = ( box->points[it2+2] - box->points[it2] ) / ( box->points[it2+1] - box->points[it2+3] ) ; double z_obj1 = box->getOriginZ1(); double z_obj2 = box->getOriginZ2(); for(unsigned int i = 0; i < data.getnbCustomer(); ++i) { // For all customers, we find the best indice considering current pair of points and current weighted sum if(! (box->isAssigned(i))) { int ind = -1; double val = DBL_MAX; for(unsigned int j = 0; j < data.getnbFacility(); ++j) { if( box->isOpened(j) ) { if(val > data.getAllocationObj1Cost(i,j) + alpha * data.getAllocationObj2Cost(i,j)) { ind = j; val = data.getAllocationObj1Cost(i,j) + alpha * data.getAllocationObj2Cost(i,j); } } } z_obj1 += data.getAllocationObj1Cost(i,ind); z_obj2 += data.getAllocationObj2Cost(i,ind); } } if( (z_obj1 + alpha * z_obj2) < (box->points[it2] + alpha * box->points[it2+1] - data.epsilon ) ) { // If new obtained solution is better than current solution, we add the new point. temPoints.push_back(z_obj1); temPoints.push_back(z_obj2); tempEdges.push_back(true); tempEdges.push_back(true); tempDicho.push_back(true); tempDicho.push_back(true); } else { tempEdges.push_back(true); tempDicho.push_back(false); } } else { tempEdges.push_back(box->edges[it2/2]); tempDicho.push_back(false); } } temPoints.push_back(box->points[box->points.size()-2]); temPoints.push_back(box->points[box->points.size()-1]); bool hasmoredicho = false ; if( temPoints.size() > box->points.size() ) { // If a new point was created, this means this box still has weighted sum to compute before proving completion. hasmoredicho = true ; } box->setHasMoreStepWS(hasmoredicho); box->points.clear() ; box->points = temPoints ; box->edges.clear() ; box->edges = tempEdges ; box->dicho.clear() ; box->dicho = tempDicho ; } else { } } void weightedSumOneStepLB(Box* box, Data &data) { // It is the same weighted sum method than weightedSumOneStep but applied to the Lower Bound Set. vector<double> temPoints = vector<double>(); vector<bool> tempEdges = vector<bool>() ; vector<bool> tempDicho = vector<bool>() ; for(unsigned int it2 = 0 ; it2 < box->pointsLB.size()-2 ; it2 = it2 + 2) { temPoints.push_back(box->pointsLB[it2]); temPoints.push_back(box->pointsLB[it2+1]); if( box->dichoLB[it2/2] ) { double alpha = ( box->pointsLB[it2+2] - box->pointsLB[it2] ) / ( box->pointsLB[it2+1] - box->pointsLB[it2+3] ) ; double z_obj1 = box->getOriginZ1(); double z_obj2 = box->getOriginZ2(); for(unsigned int i = 0; i < data.getnbCustomer(); ++i) { int ind = -1; double val = DBL_MAX; for(unsigned int j = 0; j < box->possiblyOpenFacility.size() ; ++j) { if(val > data.getAllocationObj1Cost(i,box->possiblyOpenFacility[j]) + alpha * data.getAllocationObj2Cost(i,box->possiblyOpenFacility[j])) { ind = box->possiblyOpenFacility[j]; val = data.getAllocationObj1Cost(i,ind) + alpha * data.getAllocationObj2Cost(i,ind); } } z_obj1 += data.getAllocationObj1Cost(i,ind); z_obj2 += data.getAllocationObj2Cost(i,ind); } if( (z_obj1 + alpha * z_obj2) < (box->pointsLB[it2] + alpha * box->pointsLB[it2+1] - data.epsilon ) ) { temPoints.push_back(z_obj1); temPoints.push_back(z_obj2); tempEdges.push_back(true); tempEdges.push_back(true); tempDicho.push_back(true); tempDicho.push_back(true); } else { tempEdges.push_back(true); tempDicho.push_back(false); } } else { tempEdges.push_back(true); tempDicho.push_back(false); } } temPoints.push_back(box->pointsLB[box->pointsLB.size()-2]); temPoints.push_back(box->pointsLB[box->pointsLB.size()-1]); box->setHasMoreStepLB( temPoints.size() > box->pointsLB.size() ) ; box->pointsLB.clear() ; box->pointsLB = temPoints ; box->edgesLB.clear() ; box->edgesLB = tempEdges ; box->dichoLB.clear() ; box->dichoLB = tempDicho ; } void weightedSumOneStepAll(vector<Box*> &vectorBox, Data &data, bool &MoreStep) { // It is the same weighted sum method than weightedSumOneStep but applied to all box of current vectorBox MoreStep = false ; unsigned int size = vectorBox.size(); for(unsigned int it = 0; it < size; it++) { if( vectorBox[it]->getHasMoreStepWS() ) { vector<double> temPoints = vector<double>(); vector<bool> tempEdges = vector<bool>() ; vector<bool> tempDicho = vector<bool>() ; for(unsigned int it2 = 0 ; it2 < vectorBox[it]->points.size()-2 ; it2 = it2 + 2) { temPoints.push_back(vectorBox[it]->points[it2]); temPoints.push_back(vectorBox[it]->points[it2+1]); if( vectorBox[it]->dicho[it2/2] && vectorBox[it]->edges[it2/2] ) { double alpha = ( vectorBox[it]->points[it2+2] - vectorBox[it]->points[it2] ) / ( vectorBox[it]->points[it2+1] - vectorBox[it]->points[it2+3] ) ; double z_obj1 = vectorBox[it]->getOriginZ1(); double z_obj2 = vectorBox[it]->getOriginZ2(); for(unsigned int i = 0; i < data.getnbCustomer(); ++i) { if(! (vectorBox[it]->isAssigned(i))) { int ind = -1; double val = DBL_MAX; for(unsigned int j = 0; j < data.getnbFacility(); ++j) { if( vectorBox[it]->isOpened(j) ) { if(val > data.getAllocationObj1Cost(i,j) + alpha * data.getAllocationObj2Cost(i,j)) { ind = j; val = data.getAllocationObj1Cost(i,j) + alpha * data.getAllocationObj2Cost(i,j); } } } z_obj1 += data.getAllocationObj1Cost(i,ind); z_obj2 += data.getAllocationObj2Cost(i,ind); } } if( (z_obj1 + alpha * z_obj2) < (vectorBox[it]->points[it2] + alpha * vectorBox[it]->points[it2+1] - data.epsilon ) ) { temPoints.push_back(z_obj1); temPoints.push_back(z_obj2); tempEdges.push_back(true); tempEdges.push_back(true); tempDicho.push_back(true); tempDicho.push_back(true); } else { tempEdges.push_back(true); tempDicho.push_back(false); } } else { tempEdges.push_back(vectorBox[it]->edges[it2/2]); tempDicho.push_back(false); } } temPoints.push_back(vectorBox[it]->points[vectorBox[it]->points.size()-2]); temPoints.push_back(vectorBox[it]->points[vectorBox[it]->points.size()-1]); bool hasmoredicho = false ; if( temPoints.size() > vectorBox[it]->points.size() ) { hasmoredicho = true ; MoreStep = true ; } vectorBox[it]->setHasMoreStepWS(hasmoredicho); vectorBox[it]->points.clear() ; vectorBox[it]->points = temPoints ; vectorBox[it]->edges.clear() ; vectorBox[it]->edges = tempEdges ; vectorBox[it]->dicho.clear() ; vectorBox[it]->dicho = tempDicho ; } else { } } } void parametricSearch(Box* box, Data &data) { vector<int> assignation = vector<int>(data.getnbCustomer(),-1); vector<int> nextAssignation = vector<int>(data.getnbCustomer(),-1); double maxNextLambda = 1 ; double end1 ; double end2 ; vector<double> assignedLambda = vector<double>(data.getnbCustomer(),0); box->points[0] = box->getOriginZ1() ; box->points[1] = box->getOriginZ2() ; if( !data.modeDichoBnB || box->points.size() == 4 ) { end1 = box->points[2]; end2 = box->points[3]; box->points.erase(box->points.begin() + 2 ); box->points.erase(box->points.begin() + 2 ); box->edges.erase( box->edges.begin() ); } else { end1 = box->points[4]; end2 = box->points[5]; box->points.erase(box->points.begin() + 2 ); box->points.erase(box->points.begin() + 2 ); box->points.erase(box->points.begin() + 2 ); box->points.erase(box->points.begin() + 2 ); box->edges.erase( box->edges.begin() ); box->edges.erase( box->edges.begin() ); } for(unsigned int i = 0 ; i < data.getnbCustomer(); ++i) { if( !box->isAssigned(i) ) { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { box->points[0] += data.getAllocationObj1Cost(i,data.customerSort[i][0][j]) ; box->points[1] += data.getAllocationObj2Cost(i,data.customerSort[i][0][j]) ; assignation[i] = data.customerSort[i][0][j] ; stop = true ; } } } } int currentPoint = 0 ; while( box->points[currentPoint] != end1 && box->points[currentPoint+1] != end2 && maxNextLambda > 0 ) { maxNextLambda = 0 ; for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { if( !box->isAssigned(i) && nextAssignation[i] == -1 ) { nextAssignation[i] = assignation[i] ; for(unsigned int j = 0 ; j < data.getnbFacility();++j) { if( box->isOpened(j) && (data.getAllocationObj1Cost(i,j) - data.getAllocationObj2Cost(i,j) ) > ( data.getAllocationObj1Cost(i,assignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ) ) { double temp = ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) / ( ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) - ( data.getAllocationObj1Cost(i,j) - data.getAllocationObj1Cost(i,assignation[i]) ) ) ; if( assignedLambda[i] < temp && temp < 1 ) { nextAssignation[i] = j ; assignedLambda[i] = temp ; } } } if( assignedLambda[i] > maxNextLambda ) maxNextLambda = assignedLambda[i] ; } else if( !box->isAssigned(i) && assignedLambda[i] > maxNextLambda ) { maxNextLambda = assignedLambda[i] ; } } if( maxNextLambda > 0 ) { double temp1 = box->points[currentPoint] ; double temp2 = box->points[currentPoint+1] ; for(unsigned int i = 0 ; i < data.getnbCustomer() ; ++i ) { if( !box->isAssigned(i) && maxNextLambda == assignedLambda[i] ) { temp1 += data.getAllocationObj1Cost(i,nextAssignation[i]) - data.getAllocationObj1Cost(i,assignation[i]) ; temp2 += data.getAllocationObj2Cost(i,nextAssignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ; assignation[i] = nextAssignation[i] ; assignedLambda[i] = 0 ; nextAssignation[i] = -1 ; } } box->points.push_back(temp1); box->points.push_back(temp2); box->edges.push_back(true); currentPoint = currentPoint + 2 ; } } if( box->points[currentPoint] != end1 && box->points[currentPoint+1] != end2) { box->points.push_back(end1); box->points.push_back(end2); box->edges.push_back(true); } box->setHasMoreStepWS(false) ; } void parametricSearchUB(Box* box, Data &data) { vector<int> assignation = vector<int>(data.getnbCustomer(),-1); vector<int> nextAssignation = vector<int>(data.getnbCustomer(),-1); double maxNextLambda = 1 ; double end1 ; double end2 ; vector<double> assignedLambda = vector<double>(data.getnbCustomer(),0); box->points[0] = box->getOriginZ1() ; box->points[1] = box->getOriginZ2() ; end1 = box->points[2]; end2 = box->points[3]; box->points.erase(box->points.begin() + 2 ); box->points.erase(box->points.begin() + 2 ); box->edges.erase( box->edges.begin() ); for(unsigned int i = 0 ; i < data.getnbCustomer(); ++i) { if( !box->isAssigned(i) ) { for(unsigned int j = 0 ; j < data.getnbFacility() ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { box->points[0] += data.getAllocationObj1Cost(i,data.customerSort[i][0][j]) ; box->points[1] += data.getAllocationObj2Cost(i,data.customerSort[i][0][j]) ; assignation[i] = data.customerSort[i][0][j] ; break ; } } } } int currentPoint = 0 ; while( box->points[currentPoint] != end1 && box->points[currentPoint+1] != end2 && maxNextLambda > 0 ) { maxNextLambda = 0 ; for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { if( !box->isAssigned(i) && nextAssignation[i] == -1 ) { nextAssignation[i] = assignation[i] ; for(unsigned int j = 0 ; j < data.getnbFacility();++j) { if( box->isOpened(j) && (data.getAllocationObj1Cost(i,j) - data.getAllocationObj2Cost(i,j) ) > ( data.getAllocationObj1Cost(i,assignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ) ) { double temp = ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) / ( ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) - ( data.getAllocationObj1Cost(i,j) - data.getAllocationObj1Cost(i,assignation[i]) ) ) ; if( assignedLambda[i] < temp && temp < 1 ) { nextAssignation[i] = j ; assignedLambda[i] = temp ; } } } if( assignedLambda[i] > maxNextLambda ) maxNextLambda = assignedLambda[i] ; } else if( !box->isAssigned(i) && assignedLambda[i] > maxNextLambda ) { maxNextLambda = assignedLambda[i] ; } } if( maxNextLambda > 0 ) { double temp1 = box->points[currentPoint] ; double temp2 = box->points[currentPoint+1] ; for(unsigned int i = 0 ; i < data.getnbCustomer() ; ++i ) { if( !box->isAssigned(i) && maxNextLambda == assignedLambda[i] ) { temp1 += data.getAllocationObj1Cost(i,nextAssignation[i]) - data.getAllocationObj1Cost(i,assignation[i]) ; temp2 += data.getAllocationObj2Cost(i,nextAssignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ; assignation[i] = nextAssignation[i] ; assignedLambda[i] = 0 ; nextAssignation[i] = -1 ; } } box->points.push_back(temp1); box->points.push_back(temp2); box->edges.push_back(true); currentPoint = currentPoint + 2 ; } } if( box->points[currentPoint] != end1 && box->points[currentPoint+1] != end2) { box->points.push_back(end1); box->points.push_back(end2); box->edges.push_back(true); } box->setHasMoreStepWS(false) ; } void parametricSearchLB(Box* box, Data &data) { vector<int> assignation = vector<int>(data.getnbCustomer(),-1); vector<int> nextAssignation = vector<int>(data.getnbCustomer(),-1); double maxNextLambda = 1 ; double end1 ; double end2 ; vector<double> assignedLambda = vector<double>(data.getnbCustomer(),0); box->pointsLB[0] = box->getOriginZ1() ; box->pointsLB[1] = box->getOriginZ2() ; end1 = box->pointsLB[2]; end2 = box->pointsLB[3]; box->pointsLB.erase(box->pointsLB.begin() + 2 ); box->pointsLB.erase(box->pointsLB.begin() + 2 ); box->edgesLB.erase( box->edgesLB.begin() ); for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { bool toStop1 = false; for(unsigned int j = 0 ; j < data.getnbFacility() && !toStop1;++j) { for(unsigned int k = 0 ; k < box->possiblyOpenFacility.size() && !toStop1 ; ++k ) { if( data.customerSort[i][0][j] == box->possiblyOpenFacility[k] && !toStop1 ) { box->pointsLB[0] += data.getAllocationObj1Cost(i,box->possiblyOpenFacility[k]) ; box->pointsLB[1] += data.getAllocationObj2Cost(i,box->possiblyOpenFacility[k]) ; assignation[i] = box->possiblyOpenFacility[k] ; toStop1 = true ; } } } } int currentPoint = 0 ; while( box->pointsLB[currentPoint] != end1 && box->pointsLB[currentPoint+1] != end2 && maxNextLambda > 0 ) { maxNextLambda = 0 ; for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { if( !box->isAssigned(i) && nextAssignation[i] == -1 ) { nextAssignation[i] = assignation[i] ; for(unsigned int j = 0 ; j < data.getnbFacility();++j) { if( box->isOpened(j) && (data.getAllocationObj1Cost(i,j) - data.getAllocationObj2Cost(i,j) ) > ( data.getAllocationObj1Cost(i,assignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ) ) { double temp = ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) / ( ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) - ( data.getAllocationObj1Cost(i,j) - data.getAllocationObj1Cost(i,assignation[i]) ) ) ; if( assignedLambda[i] < temp && temp < 1 ) { nextAssignation[i] = j ; assignedLambda[i] = temp ; } } } if( assignedLambda[i] > maxNextLambda ) maxNextLambda = assignedLambda[i] ; } else if( !box->isAssigned(i) && assignedLambda[i] > maxNextLambda ) { maxNextLambda = assignedLambda[i] ; } } if( maxNextLambda > 0 ) { double temp1 = box->pointsLB[currentPoint] ; double temp2 = box->pointsLB[currentPoint+1] ; for(unsigned int i = 0 ; i < data.getnbCustomer() ; ++i ) { if( !box->isAssigned(i) && maxNextLambda == assignedLambda[i] ) { temp1 += data.getAllocationObj1Cost(i,nextAssignation[i]) - data.getAllocationObj1Cost(i,assignation[i]) ; temp2 += data.getAllocationObj2Cost(i,nextAssignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ; assignation[i] = nextAssignation[i] ; assignedLambda[i] = 0 ; nextAssignation[i] = -1 ; } } box->pointsLB.push_back(temp1); box->pointsLB.push_back(temp2); box->edgesLB.push_back(true); currentPoint = currentPoint + 2 ; } } if( box->pointsLB[currentPoint] != end1 && box->pointsLB[currentPoint+1] != end2) { box->pointsLB.push_back(end1); box->pointsLB.push_back(end2); box->edgesLB.push_back(true); } box->setHasMoreStepLB(false) ; } void postProcessing(Box* box, Data &data) { if( !box->getHasEdge() ) { box->clientAllocation.push_back(vector< vector<double> >(data.getnbCustomer(),vector<double>(data.getnbFacility(),0))) ; for(unsigned int i = 0 ; i < data.getnbCustomer(); ++i) { if( !box->isAssigned(i) ) { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { box->clientAllocation[0][i][ data.customerSort[i][0][j] ] = 1 ; stop = true ; } } } else { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { box->clientAllocation[0][i][ data.customerSort[i][0][j] ] = 1 ; stop = true ; } } } } return ; } vector<int> assignation = vector<int>(data.getnbCustomer(),-1); vector<int> nextAssignation = vector<int>(data.getnbCustomer(),-1); vector< double > tempPoints = vector<double>() ; vector< vector< vector<double> > > tempClient = vector< vector< vector<double> > >() ; //vector< vector<double> >(data_.getnbCustomer(),vector<double>(data_.getnbFacility(),0)) double maxNextLambda = 1 ; double end1 = box->getOriginZ1(); double end2 = box->getOriginZ2(); vector< vector<double> > endAlloc = vector< vector<double> >(data.getnbCustomer(),vector<double>(data.getnbFacility(),0)); vector<double> assignedLambda = vector<double>(data.getnbCustomer(),0); tempPoints.push_back(box->getOriginZ1()) ; tempPoints.push_back(box->getOriginZ2()) ; tempClient.push_back(vector< vector<double> >(data.getnbCustomer(),vector<double>(data.getnbFacility(),0))) ; int counter = 0 ; for(unsigned int i = 0 ; i < data.getnbCustomer(); ++i) { if( !box->isAssigned(i) ) { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { tempPoints[0] += data.getAllocationObj1Cost(i,data.customerSort[i][0][j]) ; tempPoints[1] += data.getAllocationObj2Cost(i,data.customerSort[i][0][j]) ; assignation[i] = data.customerSort[i][0][j] ; tempClient[counter][i][ data.customerSort[i][0][j] ] = 1 ; stop = true ; } } } else { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][0][j] ) ) { tempClient[counter][i][ data.customerSort[i][0][j] ] = 1 ; stop = true ; } } } } for(unsigned int i = 0 ; i < data.getnbCustomer(); ++i) { if( !box->isAssigned(i) ) { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][1][j] ) ) { end1 += data.getAllocationObj1Cost(i,data.customerSort[i][1][j]) ; end2 += data.getAllocationObj2Cost(i,data.customerSort[i][1][j]) ; endAlloc[i][ data.customerSort[i][1][j] ] = 1 ; stop = true ; } } } else { bool stop = false ; for(unsigned int j = 0 ; j < data.getnbFacility() && !stop ; ++j) { if( box->isOpened( data.customerSort[i][1][j] ) ) { endAlloc[i][ data.customerSort[i][1][j] ] = 1 ; stop = true ; } } } } counter++ ; int currentPoint = 0 ; while( tempPoints[currentPoint] != end1 && tempPoints[currentPoint+1] != end2 && maxNextLambda > 0 ) { maxNextLambda = 0 ; for(unsigned int i = 0 ; i < data.getnbCustomer();++i) { if( !box->isAssigned(i) && nextAssignation[i] == -1 ) { nextAssignation[i] = assignation[i] ; for(unsigned int j = 0 ; j < data.getnbFacility();++j) { if( box->isOpened(j) && (data.getAllocationObj1Cost(i,j) - data.getAllocationObj2Cost(i,j) ) > ( data.getAllocationObj1Cost(i,assignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ) ) { double temp = ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) / ( ( data.getAllocationObj2Cost(i,j) - data.getAllocationObj2Cost(i,assignation[i]) ) - ( data.getAllocationObj1Cost(i,j) - data.getAllocationObj1Cost(i,assignation[i]) ) ) ; if( assignedLambda[i] < temp && temp < 1 ) { nextAssignation[i] = j ; assignedLambda[i] = temp ; } } } if( assignedLambda[i] > maxNextLambda ) maxNextLambda = assignedLambda[i] ; } else if( !box->isAssigned(i) && assignedLambda[i] > maxNextLambda ) { maxNextLambda = assignedLambda[i] ; } } if( maxNextLambda > 0 ) { double temp1 = tempPoints[currentPoint] ; double temp2 = tempPoints[currentPoint+1] ; tempClient.push_back(vector< vector<double> >(data.getnbCustomer(),vector<double>(data.getnbFacility(),0))) ; for(unsigned int i = 0 ; i < data.getnbCustomer() ; ++i ) { if( !box->isAssigned(i) && maxNextLambda == assignedLambda[i] ) { temp1 += data.getAllocationObj1Cost(i,nextAssignation[i]) - data.getAllocationObj1Cost(i,assignation[i]) ; temp2 += data.getAllocationObj2Cost(i,nextAssignation[i]) - data.getAllocationObj2Cost(i,assignation[i]) ; assignation[i] = nextAssignation[i] ; tempClient[counter][i][ nextAssignation[i] ] = 1 ; assignedLambda[i] = 0 ; nextAssignation[i] = -1 ; } else { for( unsigned int j = 0 ; j < data.getnbFacility() ; ++j ) { tempClient[counter][i][j] = tempClient[counter-1][i][j] ; } } } tempPoints.push_back(temp1); tempPoints.push_back(temp2); counter++ ; currentPoint = currentPoint + 2 ; } } if( tempPoints[currentPoint] != end1 && tempPoints[currentPoint+1] != end2) { tempPoints.push_back(end1); tempPoints.push_back(end2); tempClient.push_back(endAlloc); } for( unsigned int it = 0 ; it < box->points.size() ; it = it+2) { for( unsigned int it2 = 0 ; it2 < tempPoints.size() ; it2 = it2+2) { if( box->points[it] == tempPoints[it2] && box->points[it+1] == tempPoints[it2+1] ) { box->clientAllocation.push_back(tempClient[it2/2]) ; break ; } else if( box->points[it] < tempPoints[it2+2] && box->points[it+1] > tempPoints[it2+3] ) { double percent = ( box->points[it]-tempPoints[it2] ) / ( tempPoints[it2+2]-tempPoints[it2] ) ; vector< vector<double> > matrix = vector< vector<double> >(data.getnbCustomer(),vector<double>(data.getnbFacility(),0)); for( unsigned int i = 0 ; i < data.getnbCustomer() ; ++i ) { if( box->isAssigned(i) ) { for( unsigned int j = 0 ; j < data.getnbFacility() ; ++j ) { matrix[i][j] = tempClient[it2/2][i][j] ; } } else { for( unsigned int j = 0 ; j < data.getnbFacility() ; ++j ) { if( tempClient[it2/2][i][j] && tempClient[it2/2+1][i][j]) { matrix[i][j] = 1 ; } else if( tempClient[it2/2][i][j]) { matrix[i][j] = (1.0-percent) ; } else if( tempClient[it2/2 + 1][i][j] ) { matrix[i][j] = percent ; } else { matrix[i][j] = 0; } } }//endelse }//endfor i box->clientAllocation.push_back(matrix) ; break ; }//endelseif }//endfor it2 }//endfor it } bool isPointDominated(Box *box1, Box *box2) { return ( box1->getMinZ1() >= box2->getMinZ1() && box1->getMinZ2() >= box2->getMinZ2() ); } int dominancePointEdge(Box *box1, Box *box2, Data &data) { if( ( box1->getMinZ1() >= box2->getMaxZ1() && box1->getMaxZ2() <= box2->getMinZ2() ) || ( box1->getMaxZ1() <= box2->getMinZ1() && box1->getMinZ2() >= box2->getMaxZ2() ) ) { /* Dominance Impossible as stated by T.Vincent Nothing to do */ return 1 ; } double a = (box2->getMaxZ2()-box2->getMinZ2())/(box2->getMinZ1()-box2->getMaxZ1()) ; double b = box2->getMaxZ2() - a * box2->getMinZ1() ; double Yproj = a * box1->getMinZ1() + b ; double Xproj = (box1->getMinZ2()-b)/a ; bool below = Yproj > box1->getMinZ2() ; if( !below && ( ( Yproj <= box2->getMaxZ2() && Yproj >= box2->getMinZ2() ) || ( Xproj <= box2->getMaxZ1() && Xproj >= box2->getMinZ1() )|| ( Yproj <= box2->getMinZ2() && Xproj <= box2->getMinZ1() ) ) ) { return -1 ; } else if ( below && Yproj >= box2->getMaxZ2() && Xproj >= box2->getMaxZ1() ) { return 0 ; } /* Starting on the edges */ for( unsigned int it = 0 ; it < box2->points.size()-2 ;) { if( box2->edges[it/2] ) { double a = (box2->points[it+1]-box2->points[it+3])/(box2->points[it]-box2->points[it+2]) ; double b = box2->points[it+1] - a * box2->points[it] ; double Yproj = a * box1->getMinZ1() + b ; double Xproj = (box1->getMinZ2()-b)/a ; bool below = Yproj > box1->getMinZ2() ; if( !below ) { if( ( Yproj <= box2->points[it+1] && Yproj >= box2->points[it+3] ) || ( Xproj <= box2->points[it+2] && Xproj >= box2->points[it] ) || ( Yproj <= box2->points[it+3] && Xproj <= box2->points[it] ) ) { return -1 ; } else { it =it + 2 ; } } else { if( ( Yproj >= box2->points[it+1] && Xproj >= box2->points[it+2] ) ) { box2->edges[it/2] = false ; it = it + 2 ; } else if( Yproj < box2->points[it+1] && Yproj > box2->points[it+3] && Xproj < box2->points[it+2] && Xproj > box2->points[it] ) { box2->points.insert( box2->points.begin() += (it+2) , box1->getMinZ2() ) ; box2->points.insert( box2->points.begin() += (it+2) , Xproj ) ; box2->edges.insert( box2->edges.begin() += (it/2 + 1 ), true ) ; box2->points.insert( box2->points.begin() += (it+2) , Yproj ) ; box2->points.insert( box2->points.begin() += (it+2) , box1->getMinZ1() ) ; box2->edges.insert( box2->edges.begin() += (it/2 + 1 ), false ) ; it = it + 6 ; } else if( Yproj < box2->points[it+1] && Yproj > box2->points[it+3] ) { box2->points.insert( box2->points.begin() += (it+2) , Yproj ) ; box2->points.insert( box2->points.begin() += (it+2) , box1->getMinZ1() ) ; box2->edges.insert( box2->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; } else if( Xproj < box2->points[it+2] && Xproj > box2->points[it] ) { box2->points.insert( box2->points.begin() += (it+2) , box1->getMinZ2() ) ; box2->points.insert( box2->points.begin() += (it+2) , Xproj ) ; box2->edges.insert( box2->edges.begin() += (it/2 + 1 ), true ) ; box2->edges[it/2] = false ; it = it + 4 ; } else { it = it + 2 ; } } } // endif else { it = it + 2 ; } } // endfor int toReturn = 1 ; prefiltering(box2,data); if( box2->points.size() <= 2 || box2->edges.size() == 0 || !box2->getHasEdge() ) { toReturn = 0 ; } return toReturn ; } int dominanceEdgeEdge(Box *box1, Box *box2, Data &data) { if( ( box1->getMinZ1() >= box2->getMaxZ1() && box1->getMaxZ2() <= box2->getMinZ2() ) || ( box1->getMaxZ1() <= box2->getMinZ1() && box1->getMinZ2() >= box2->getMaxZ2() ) ) { /* Dominance Impossible as stated by T.Vincent Nothing to do */ return 0 ; } for( unsigned int it = 0 ; it < box1->points.size()-2 ; it=it+2 ) { if( box1->edges[it/2]) { double a1 = (box1->points[it+1] - box1->points[it+3])/(box1->points[it] - box1->points[it+2]) ; double b1 = box1->points[it+1] - a1 * box1->points[it] ; for( unsigned int it2 = 0 ; it2 < box2->points.size()-2 ; ) { if( box2->edges[it2/2] ) { double a2 = (box2->points[it2+1]-box2->points[it2+3])/(box2->points[it2]-box2->points[it2+2]) ; double b2 = box2->points[it2+1] - a2 * box2->points[it2] ; if( ( box1->points[it+2] <= box2->points[it2] && box1->points[it+3] >= box2->points[it2+1] ) ) { /* Dominance Impossible as stated by T.Vincent. As the edges are lexicographically sorted, further comparison are pointless we can stop */ break ; } else if( ( box1->points[it] >= box2->points[it2+2] && box1->points[it+1] <= box2->points[it2+3] ) ) { /* Dominance Impossible as stated by T.Vincent. As the edges are lexicographically sorted, further comparison are needed to assert it is or not dominated. */ it2 = it2 + 2 ; } else if( fabs(b2-b1) < data.epsilon && fabs(a1-a2) < data.epsilon ) { // The two edges are on the same line if last point of edge from box1 finish before last point of edge from box2, further comparison are pointless as the edges are lexicographically sorted. if( box1->points[it+2] <= box2->points[it2+2] ) break ; else it2=it2+2 ; } else if( fabs(a1-a2) < data.epsilon ) { // The two edges are parallele. Two comparison are needed and similar, if edge from box1 is below or if edge from box2 is below. if( b2 < b1 ) { double Yproj1 = a1 * box2->points[it2] + b1 ; double Xproj1 = box2->points[it2] ; double Xproj2 = (box2->points[it2+3]-b1)/a1 ; double Yproj2 = box2->points[it2+3] ; bool proj1exist = ( Yproj1 < box1->points[it+1] && Yproj1 > box1->points[it+3] ); bool proj2exist = ( Xproj2 < box1->points[it+2] && Xproj2 > box1->points[it] ); if( proj1exist && proj2exist ) { // Edge from box 2 is below and there is two projection on edge from box1 then the part between the projection is dominated. box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; it2 = it2 + 2 ; } else if( proj1exist ) { // Edge from box 2 is below and there is one projection on edge from box1, then the part below the projection is dominated. As the edges are sorted lexicographically, further comparison with edge from box1 are pointless. box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else if( proj2exist ) { // Edge from box2 is below and there is one projection on edge from box1, then the part above the projection is dominated. As the edges are sorted lexicographically, further comparison with edge from box1 are needed. box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; it = it + 2 ; it2 = it2 + 2 ; } else { // Edge from box2 is below and there is no projection on edge from box1, then the edge from box1 is totally dominated and further comparison are pointless box1->edges[it/2] = false ; break ; } }// End edge from box2 below edge from Box1 else { // Similar comparisons but considering that edge from box1 is below edge from box2 double Yproj1 = a2 * box1->points[it] + b2 ; double Xproj1 = box1->points[it] ; double Xproj2 = (box1->points[it+3]-b2)/a2 ; double Yproj2 = box1->points[it+3] ; bool proj1exist = ( Yproj1 < box2->points[it2+1] && Yproj1 > box2->points[it2+3] ); bool proj2exist = ( Xproj2 < box2->points[it2+2] && Xproj2 > box2->points[it2] ); if( proj1exist && proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } else if( proj1exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 2 ; } else if( proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; break ; } else { box2->edges[it2/2] = false ; it2 = it2 + 2 ; } }// End edge from box1 below edge from box2 } else { // Edge are not parallele, will need to check if they have a relative interior or not. bool interiorRelatif ; double Xintersec ; double Yintersec ; Xintersec = (b2-b1)/(a1-a2) ; Yintersec = a1*Xintersec + b1 ; interiorRelatif = ( Xintersec < box1->points[it+2] && Xintersec < box2->points[it2+2] && Xintersec > box1->points[it] && Xintersec > box2->points[it2] ); if( interiorRelatif ) { // The two edges have a relative interior, we need to verify wich edge is first below then above and do the correct comparison, the comparison on each part are equivalent. if( a1 > a2 ) { // a1 and a2 are both negative, if a1 > a2 then the first part of edge from box1 is below the first part of edge from box2 and converse for second part. double testYproj = a2 * box1->points[it] + b2 ; double correspondingX = box1->points[it] ; double testXproj = (box2->points[it2+3]-b1)/a1 ; double correspondingY = box2->points[it2+3] ; if( testYproj >= box2->points[it2+1] ) { // First part of edge from box1 is below first part of edge from box2 and totally dominate first part of edge from box2. We add the intersection point and flag first part of edge from box2 as dominated. box2->points.insert( box2->points.begin() += (it2+2) , Yintersec ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xintersec ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true ) ; it2 = it2 + 4 ; } else { // First part of edge from box1 is below first part of edge from box2 and there is a projection on edge from box2, then the part below the projection and above the intersection point is dominated. We add corresponding point and flag the corresponding part as dominated. box2->points.insert( box2->points.begin() += (it2+2) , Yintersec ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xintersec ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true ) ; box2->points.insert( box2->points.begin() += (it2+2) , testYproj ) ; box2->points.insert( box2->points.begin() += (it2+2) , correspondingX ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 6 ; } if( testXproj >= box1->points[it+2] ) { // Second part of edge from box1 is above second part of edge from box2 and is totally dominated by second part of edge from box2. We add the intersection point and flag second part of edge from box1 as dominated. As the edges are sorted lexicographically, further comparisons are pointless. box1->points.insert( box1->points.begin() += (it+2) , Yintersec ) ; box1->points.insert( box1->points.begin() += (it+2) , Xintersec ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else { // Second part of edge from box1 is above second part of edge from box2 and there is a projection on edge from box1, then the part above the projection and below the intersection point is dominated. We add corresponding point and flag the corresponding part as dominated. As the edges are sorted lexicographically, further comparisons are needed. box1->points.insert( box1->points.begin() += (it+2) , correspondingY ) ; box1->points.insert( box1->points.begin() += (it+2) , testXproj ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true ) ; box1->points.insert( box1->points.begin() += (it+2) , Yintersec ) ; box1->points.insert( box1->points.begin() += (it+2) , Xintersec ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; } }// End comparison if a1 > a2 else { // a1 and a2 are both negative, if a1 < a2 then the first part of edge from box1 is above the first part of edge from box2 and converse for second part. The comparison are equivalent to the previous comparisons. double testYproj = a1 * box2->points[it2] + b1 ; double correspondingX = box2->points[it2] ; double testXproj = (box1->points[it+3]-b2)/a2 ; double correspondingY = box1->points[it+3] ; if( testYproj >= box1->points[it+1] ) { box1->points.insert( box1->points.begin() += (it+2) , Yintersec ) ; box1->points.insert( box1->points.begin() += (it+2) , Xintersec ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true ) ; it = it + 2 ; } else { box1->points.insert( box1->points.begin() += (it+2) , Yintersec ) ; box1->points.insert( box1->points.begin() += (it+2) , Xintersec ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true ) ; box1->points.insert( box1->points.begin() += (it+2) , testYproj ) ; box1->points.insert( box1->points.begin() += (it+2) , correspondingX ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; } if( testXproj >= box2->points[it2+2] ) { box2->points.insert( box2->points.begin() += (it2+2) , Yintersec ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xintersec ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 4 ; } else { box2->points.insert( box2->points.begin() += (it2+2) , correspondingY ) ; box2->points.insert( box2->points.begin() += (it2+2) , testXproj ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true ) ; box2->points.insert( box2->points.begin() += (it2+2) , Yintersec ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xintersec ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } }// End comparison if a1 < a2 } else { // No relative interior, we need to do all other possible comparisons. if( ( Xintersec <= box1->points[it] && Xintersec <= box2->points[it2] ) ) { // The intersection of the line ( constructed from the edges ) is at the left of the two edges. Simple comparison can detect which one is below and which one is above. if( a1 < a2 ) { // a1 and a2 are both negative. As a1 < a2 the line from edge from box1 is below the line from edge from box2. Edge from box1 potentially dominate edge from box2. Comparisons are similar to the parallele case. double Yproj1 = a2 * box1->points[it] + b2 ; double Xproj1 = box1->points[it] ; double Xproj2 = (box1->points[it+3]-b2)/a2 ; double Yproj2 = box1->points[it+3] ; bool proj1exist = ( Yproj1 < box2->points[it2+1] && Yproj1 > box2->points[it2+3] ); bool proj2exist = ( Xproj2 < box2->points[it2+2] && Xproj2 > box2->points[it2] ); if( proj1exist && proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } else if( proj1exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 4 ; } else if( proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; break ; } else { box2->edges[it2/2] = false ; it2 = it2 + 2 ; } }// End a1 < a2 else { // a1 and a2 are both negative. As a1 > a2 the line from edge from box1 is above the line from edge from box2. Edge from box1 is potentially dominated by edge from box2. Comparisons are similar to the parallele case. double Yproj1 = a1 * box2->points[it2] + b1 ; double Xproj1 = box2->points[it2] ; double Xproj2 = (box2->points[it2+3]-b1)/a1 ; double Yproj2 = box2->points[it2+3] ; bool proj1exist = ( Yproj1 < box1->points[it+1] && Yproj1 > box1->points[it+3] ); bool proj2exist = ( Xproj2 < box1->points[it+2] && Xproj2 > box1->points[it] ); if( proj1exist && proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; it2 = it2 + 2 ; } else if( proj1exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else if( proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; it = it + 2 ; it2 = it2 + 2 ; } else { box1->edges[it/2] = false ; break ; } } }// End intersection is at left from both edges else if( ( Xintersec >= box1->points[it+2] && Xintersec >= box2->points[it2+2] )) { // The intersection of the line ( constructed from the edges ) is at the right of the two edges. Simple comparison can detect which one is below and which one is above. if( a1 > a2 ) { // a1 and a2 are both negative. As a1 > a2 the line from edge from box1 is below the line from edge from box2. Edge from box1 potentially dominate edge from box2. Comparisons are similar to the parallele case. double Yproj1 = a2 * box1->points[it] + b2 ; double Xproj1 = box1->points[it] ; double Xproj2 = (box1->points[it+3]-b2)/a2 ; double Yproj2 = box1->points[it+3] ; bool proj1exist = ( Yproj1 < box2->points[it2+1] && Yproj1 > box2->points[it2+3] ); bool proj2exist = ( Xproj2 < box2->points[it2+2] && Xproj2 > box2->points[it2] ); if( proj1exist && proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } else if( proj1exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 4 ; } else if( proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; break ; } else { box2->edges[it2/2] = false ; it2 = it2 + 2 ; } }// End a1 > a2 else { // a1 and a2 are both negative. As a1 < a2 the line from edge from box1 is above the line from edge from box2. Edge from box1 is potentially dominated by edge from box2. Comparisons are similar to the parallele case. double Yproj1 = a1 * box2->points[it2] + b1 ; double Xproj1 = box2->points[it2] ; double Xproj2 = (box2->points[it2+3]-b1)/a1 ; double Yproj2 = box2->points[it2+3] ; bool proj1exist = ( Yproj1 < box1->points[it+1] && Yproj1 > box1->points[it+3] ); bool proj2exist = ( Xproj2 < box1->points[it+2] && Xproj2 > box1->points[it] ); if( proj1exist && proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; it2 = it2 + 2 ; } else if( proj1exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else if( proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; it = it + 2 ; it2 = it2 + 2 ; } else { box1->edges[it/2] = false ; break ; } }// End a1 < a2 }// End intersection point is at the right of both edges else if( Xintersec > box1->points[it] && Xintersec < box1->points[it+2] ) { // Intersection point is inside the edge from box1 if( ( Xintersec < box2->points[it2] && a1 < a2 ) || ( Xintersec > box2->points[it2+2] && a1 > a2 )) { // This condition verifies that edge from box1 is below edge from box2. Edge from box1 potentially dominates edge from box2. Comparisons are then similar to the parallel case. double Yproj1 = a2 * box1->points[it] + b2 ; double Xproj1 = box1->points[it] ; double Xproj2 = (box1->points[it+3]-b2)/a2 ; double Yproj2 = box1->points[it+3] ; bool proj1exist = ( Yproj1 < box2->points[it2+1] && Yproj1 > box2->points[it2+3] ); bool proj2exist = ( Xproj2 < box2->points[it2+2] && Xproj2 > box2->points[it2] ); if( proj1exist && proj2exist ) { // NOT SUPPOSED TO HAPPEN box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } else if( proj1exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 4 ; } else if( proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; break ; } else { box2->edges[it2/2] = false ; it2 = it2 + 2 ; } }// End edge from box1 below edge from box2 else { // This false condition verifies that edge from box1 is above edge from box2. Edge from box1 is then potentially dominated by edge from box2. Comparisons are then similar to the parallel case. double Yproj1 = a1 * box2->points[it2] + b1 ; double Xproj1 = box2->points[it2] ; double Xproj2 = (box2->points[it2+3]-b1)/a1 ; double Yproj2 = box2->points[it2+3] ; bool proj1exist = ( Yproj1 < box1->points[it+1] && Yproj1 > box1->points[it+3] ); bool proj2exist = ( Xproj2 < box1->points[it+2] && Xproj2 > box1->points[it] ); if( proj1exist && proj2exist ) { // NOT SUPPOSED TO HAPPEN box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; it2 = it2 + 2 ; } else if( proj1exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else if( proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; it = it + 2 ; it2 = it2 + 2 ; } else { box1->edges[it/2] = false ; break ; } }// End edge from box1 above edge from box2 } else if( Xintersec > box2->points[it2] && Xintersec < box2->points[it2+2] ) { // Intersection point is inside the edge from box2, all subsequent comparison are similar to previous ones. if(( Xintersec < box1->points[it] && a1 < a2 ) || ( Xintersec > box1->points[it+2] && a1 > a2 )) { // This condition verifies that edge from box1 is below edge from box2. Edge from box1 potentially dominates edge from box2. Comparisons are then similar to the parallel case. double Yproj1 = a2 * box1->points[it] + b2 ; double Xproj1 = box1->points[it] ; double Xproj2 = (box1->points[it+3]-b2)/a2 ; double Yproj2 = box1->points[it+3] ; bool proj1exist = ( Yproj1 < box2->points[it2+1] && Yproj1 > box2->points[it2+3] ); bool proj2exist = ( Xproj2 < box2->points[it2+2] && Xproj2 > box2->points[it2] ); if( proj1exist && proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; break ; } else if( proj1exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj1 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj1 ) ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), false ) ; it2 = it2 + 2 ; } else if( proj2exist ) { box2->points.insert( box2->points.begin() += (it2+2) , Yproj2 ) ; box2->points.insert( box2->points.begin() += (it2+2) , Xproj2 ) ; box2->edges[it2/2] = false ; box2->edges.insert( box2->edges.begin() += (it2/2 + 1 ), true) ; break ; } else { box2->edges[it2/2] = false ; it2 = it2 + 2 ; } }// End edge from box1 below edge from box2 else { // This false condition verifies that edge from box1 is above edge from box2. Edge from box1 is then potentially dominated by edge from box2. Comparisons are then similar to the parallel case. double Yproj1 = a1 * box2->points[it2] + b1 ; double Xproj1 = box2->points[it2] ; double Xproj2 = (box2->points[it2+3]-b1)/a1 ; double Yproj2 = box2->points[it2+3] ; bool proj1exist = ( Yproj1 < box1->points[it+1] && Yproj1 > box1->points[it+3] ); bool proj2exist = ( Xproj2 < box1->points[it+2] && Xproj2 > box1->points[it] ); if( proj1exist && proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; it = it + 4 ; it2 = it2 + 2 ; } else if( proj1exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj1 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj1 ) ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), false ) ; break ; } else if( proj2exist ) { box1->points.insert( box1->points.begin() += (it+2) , Yproj2 ) ; box1->points.insert( box1->points.begin() += (it+2) , Xproj2 ) ; box1->edges[it/2] = false ; box1->edges.insert( box1->edges.begin() += (it/2 + 1 ), true) ; it = it + 2 ; it2 = it2 + 2 ; } else { box1->edges[it/2] = false ; break ; } }// End edge from box1 above edge from box2 } } // End of no Relative Interior } // End of Comparisons } // End of if2 (this is an edge from box2) else { it2 = it2 + 2 ; } } // end of for2 } // end of if1 (this is an edge from box1) } // end of for1 int toReturn = 0 ; prefiltering(box1,data); prefiltering(box2,data); if( box1->points.size() <= 2 || box1->edges.size() == 0 || !box1->getHasEdge() ) { toReturn = 1 ; } else if( box2->points.size() <= 2 || box2->edges.size() == 0 || !box2->getHasEdge() ) { toReturn = -1 ; } return toReturn ; } void prefiltering(Box* box, Data &data) { bool erase = !box->edges[0]; while( erase ) { box->points.erase(box->points.begin()); box->points.erase(box->points.begin()); box->edges.erase(box->edges.begin()); if( box->edges.size() > 0) { erase = !box->edges[0] ; } else { erase = false ; } } if( box->edges.size() > 0 ) { erase = !box->edges[box->edges.size()-1]; while( erase ) { box->points.erase(box->points.begin() += (box->points.size()-1) ); box->points.erase(box->points.begin() += (box->points.size()-1) ); box->edges.erase(box->edges.begin() += (box->edges.size()-1) ); if( box->edges.size() > 0) { erase = !box->edges[box->edges.size()-1] ; } else { erase = false ; } } } for(unsigned int i = 2 ; i < box->points.size()-2 ;) { if( (!box->edges[i/2] && !box->edges[i/2+1]) || fabs(box->points[i] - box->points[i+2]) < data.epsilon || fabs(box->points[i+1] - box->points[i+3]) < data.epsilon ) { box->points.erase(box->points.begin() += (i + 2)); box->points.erase(box->points.begin() += (i + 2)); box->edges.erase(box->edges.begin() += (i/2 + 1)); } else { i=i+2 ; } } if( fabs(box->getMinZ1() - box->getMaxZ1() ) < data.epsilon || fabs(box->getMinZ2() - box->getMaxZ2() ) < data.epsilon ) box->setHasEdge(false) ; } void edgefiltering(vector<Box*> &vectorBox, Data &data) { for( unsigned int it = 0; it < vectorBox.size() ; ++it ) { if( vectorBox[it]->getHasEdge() ) prefiltering(vectorBox[it],data); } for(unsigned int it = 0; it < vectorBox.size();) { unsigned int size = vectorBox.size() ; for(unsigned int it2 = it + 1 ; it2 < size ;) { if( !vectorBox[it]->getHasEdge() && !vectorBox[it2]->getHasEdge() ) { // Both Box are points. We verify using point dominance test if( isPointDominated(vectorBox[it], vectorBox[it2]) ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); it2 = it + 1 ; --size ; } else if( isPointDominated(vectorBox[it2], vectorBox[it]) ) { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); --size ; } else { ++it2 ; } // ++it2; } else if( !vectorBox[it]->getHasEdge() ) { // One box is a point the other has edge. We verify using point edge dominance test int result = dominancePointEdge(vectorBox[it],vectorBox[it2],data); if( result == 1 ) { ++it2 ; } else if( result == -1 ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); it2 = it + 1 ; --size ; } else { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); --size ; } } else if( !vectorBox[it2]->getHasEdge() ) { // One box is a point the other has edge. We verify using point edge dominance test int result = dominancePointEdge(vectorBox[it2],vectorBox[it],data); if( result == 1 ) { ++it2 ; } else if( result == -1 ) { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); --size ; } else { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); it2 = it + 1 ; --size ; } } else { // Both box has edges. We verify using edge edge dominance test int result = dominanceEdgeEdge(vectorBox[it],vectorBox[it2],data) ; if( result == -1 ) { delete vectorBox[it2]; vectorBox.erase(vectorBox.begin() += it2); --size ; } else if( result == 1 ) { delete vectorBox[it]; vectorBox.erase(vectorBox.begin() += it); it2 = it + 1 ; --size ; } else { ++it2 ; } } } it++; } } double computeCorrelation(Data &data) { double correl(0); double meanX(0), meanY(0), num(0), den1(0), den2(0); for(unsigned int i = 0; i < data.getnbCustomer(); i++) { for(unsigned int j = 0; j < data.getnbFacility(); j++) { meanX += data.getAllocationObj1Cost(i,j); meanY += data.getAllocationObj2Cost(i,j); } } meanX /= ( data.getnbCustomer() * data.getnbFacility() ); meanY /= ( data.getnbCustomer() * data.getnbFacility() ); for(unsigned int i = 0; i < data.getnbCustomer(); i++) { for(unsigned int j = 0; j < data.getnbFacility(); j++) { num += (data.getAllocationObj1Cost(i,j) - meanX) * (data.getAllocationObj2Cost(i,j) - meanY) / ( data.getnbCustomer() * data.getnbFacility() ); den1 += pow((data.getAllocationObj1Cost(i,j) - meanX),2) / ( data.getnbCustomer() * data.getnbFacility() ); den2 += pow((data.getAllocationObj2Cost(i,j) - meanY),2) / ( data.getnbCustomer() * data.getnbFacility() ); } } correl = num / (sqrt(den1)*sqrt(den2)); return correl; } void quicksortedge(vector<Box*> &toSort, int begin, int end) { int i = begin, j = end; Box* tmp; double pivot = toSort[(begin + end) / 2]->getMinZ1(); /* partition */ while (i <= j) { while (toSort[i]->getMinZ1() < pivot) i++; while (toSort[j]->getMinZ1() > pivot) j--; if (i <= j) { tmp = toSort[i]; toSort[i] = toSort[j]; toSort[j] = tmp; i++; j--; } }; /* recursion */ if (begin < j) { quicksortedge(toSort, begin, j); } if (i < end) { quicksortedge(toSort, i, end); } } void quicksortCusto(vector<double> &toHelp, vector<double> &lexHelp, vector<int> &toSort, int begin, int end) { int i = begin, j = end; double tmpcost; double tmplex; int tmpfacility; double pivot = toHelp[(begin + end) / 2]; double lexpivot = lexHelp[(begin + end) / 2]; /* partition */ while (i <= j) { bool cntn = true ; while (toHelp[i] <= pivot && cntn && i < end) { if( toHelp[i] < pivot ) { i++; } else if( lexHelp[i] < lexpivot ) { // Verification to be sure all customer preferences are sorted by lexicographical order i++; } else { cntn = false ; } } cntn = true ; while (toHelp[j] >= pivot && cntn && j > begin ) { if( toHelp[j] > pivot ) { j--; } else if( lexHelp[j] > lexpivot ) { // Verification to be sure all customer preferences are sorted by lexicographical order j--; } else { cntn = false ; } } if (i <= j) { tmpfacility = toSort[i]; tmpcost = toHelp[i]; tmplex = lexHelp[i]; toSort[i] = toSort[j]; toHelp[i] = toHelp[j]; lexHelp[i] = lexHelp[j]; toSort[j] = tmpfacility; toHelp[j] = tmpcost; lexHelp[j] = tmplex; i++; j--; } }; /* recursion */ if (begin < j) { quicksortCusto(toHelp, lexHelp, toSort, begin, j); } if (i < end) { quicksortCusto(toHelp, lexHelp, toSort, i, end); } } void quicksortFacility(vector<double> &toSort, int begin, int end, Data &data) { int i = begin, j = end; int tmp; int tmp2; int pivot = toSort[(begin + end) / 2]; /* partition */ while (i <= j) { while (toSort[i] > pivot) i++; while (toSort[j] < pivot) j--; if (i <= j) { tmp = toSort[i]; tmp2 = data.facilitySort[i]; toSort[i] = toSort[j]; data.facilitySort[i] = data.facilitySort[j]; toSort[j] = tmp; data.facilitySort[j] = tmp2 ; i++; j--; } }; /* recursion */ if (begin < j) { quicksortFacility(toSort, begin, j, data); } if (i < end) { quicksortFacility(toSort, i, end, data); } } bool isAlreadyIn(vector<string> openedFacility, Box* box) { for(unsigned int it = 0 ; it < openedFacility.size() ; ++it ) { if( openedFacility[it] == box->getId() ) return true ; } return false ; } void sortFacility(Data &data, vector<double> clientfacilitycost1,vector<double> clientfacilitycost2) { vector<double> sortFacility = vector<double>(data.getnbFacility(),0); for( unsigned int i = 0 ; i < data.getnbFacility() ; ++i ) sortFacility[i] = clientfacilitycost1[i] + data.getLocationObj1Cost(i) + clientfacilitycost2[i] + data.getLocationObj2Cost(i) ; quicksortFacility(sortFacility,0,data.getnbFacility()-1,data); } void crono_start(clock_t &start_utime) { start_utime = clock() ; } void crono_stop(clock_t &stop_utime) { stop_utime = clock() ; } double crono_ms(clock_t start_utime, clock_t stop_utime) { return ( (double) stop_utime - (double) start_utime ) / CLOCKS_PER_SEC * 1000.0 ; } void quicksortFacilityOBJ1(vector<double> &toSort, int begin, int end) { int i = begin, j = end; double tmp; int pivot = toSort[(begin + end) / 2]; /* partition */ while (i <= j) { while (toSort[i] < pivot) i++; while (toSort[j] > pivot) j--; if (i <= j) { tmp = toSort[i]; toSort[i] = toSort[j]; toSort[j] = tmp; i++; j--; } }; /* recursion */ if (begin < j) { quicksortFacilityOBJ1(toSort, begin, j); } if (i < end) { quicksortFacilityOBJ1(toSort, i, end); } } void quicksortFacilityOBJ2(vector<double> &toSort, int begin, int end) { int i = begin, j = end; double tmp; int pivot = toSort[(begin + end) / 2]; /* partition */ while (i <= j) { while (toSort[i] < pivot) i++; while (toSort[j] > pivot) j--; if (i <= j) { tmp = toSort[i]; toSort[i] = toSort[j]; toSort[j] = tmp; i++; j--; } }; /* recursion */ if (begin < j) { quicksortFacilityOBJ2(toSort, begin, j); } if (i < end) { quicksortFacilityOBJ2(toSort, i, end); } }
31.631393
446
0.566866
vOptSolver
40ada292edc5cb7e6296d9ed7974b96c9ec1aa7f
10,754
cpp
C++
application/platform/glx/glx_context.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
application/platform/glx/glx_context.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
application/platform/glx/glx_context.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#include "glx_context.h" #include "glx_window.h" #include <natus/graphics/backend/gl/gl3.h> #include <natus/ogl/gl/gl.h> #include <natus/ogl/glx/glx.h> #include <natus/ntd/string/split.hpp> using namespace natus::application ; using namespace natus::application::glx ; //***********************n***************************************** context::context( void_t ) { _bend_ctx = natus::memory::global_t::alloc( natus::application::glx::gl_context( this ), "[context] : backend gl_context" ) ; } //**************************************************************** context::context( gl_info_in_t gli, Window wnd, Display * disp ) { _bend_ctx = natus::memory::global_t::alloc( natus::application::glx::gl_context( this ), "[context] : backend gl_context" ) ; _display = disp ; _wnd = wnd ; this_t::create_the_context( gli ) ; } //**************************************************************** context::context( this_rref_t rhv ) { _display = rhv._display ; rhv._display = NULL ; _wnd = rhv._wnd ; rhv._wnd = 0 ; _context = rhv._context ; rhv._context = 0 ; natus_move_member_ptr( _bend_ctx, rhv ) ; _bend_ctx->change_owner( this ) ; } //**************************************************************** context::this_ref_t context::operator = ( this_rref_t rhv ) { _display = rhv._display ; rhv._display = NULL ; _wnd = rhv._wnd ; rhv._wnd = 0 ; _context = rhv._context ; rhv._context = 0 ; natus_move_member_ptr( _bend_ctx, rhv ) ; _bend_ctx->change_owner( this ) ; return *this ; } //**************************************************************** context::~context( void_t ) { this_t::deactivate() ; natus::memory::global_t::dealloc( _bend_ctx ) ; } //*************************************************************** natus::application::result context::activate( void_t ) { //glXMakeCurrent( _display, _wnd, NULL ) ; //XLockDisplay( _display ) ; auto const res = glXMakeCurrent( _display, _wnd, _context ) ; //XUnlockDisplay( _display ) ; natus::log::global_t::warning( natus::core::is_not(res), natus_log_fn( "glXMakeCurrent" ) ) ; return natus::application::result::ok ; } //*************************************************************** natus::application::result context::deactivate( void_t ) { auto const res = glXMakeCurrent( _display, 0, 0 ) ; natus::log::global_t::warning( natus::core::is_not(res), natus_log_fn( "glXMakeCurrent" ) ) ; return natus::application::result::ok ; } //*************************************************************** natus::application::result context::vsync( bool_t const on_off ) { natus::ogl::glx::glXSwapInterval( _display, _wnd, on_off ? 1 : 0 ) ; return natus::application::result::ok ; } //************************************************************** natus::application::result context::swap( void_t ) { glXSwapBuffers( _display, _wnd ) ; const GLenum glerr = natus::ogl::glGetError( ) ; natus::log::global_t::warning( glerr != GL_NO_ERROR, natus_log_fn( "glXSwapBuffers" ) ) ; return natus::application::result::ok ; } natus::graphics::backend_res_t context::create_backend( void_t ) noexcept { natus::application::gl_version glv ; this->get_gl_version( glv ) ; if( glv.major >= 3 ) { return natus::graphics::gl3_backend_res_t( natus::graphics::gl3_backend_t( _bend_ctx ) ) ; } return natus::graphics::null_backend_res_t( natus::graphics::null_backend_t() ) ; } //************************************************************** natus::application::result context::create_context( Display* display, Window wnd, GLXContext context ) { _display = display ; _wnd = wnd ; // the context comes in already create _context = context ; return natus::application::result::ok ; } //*************************************************************** natus::application::result context::is_extension_supported( natus::ntd::string_cref_t extension_name ) { this_t::strings_t ext_list ; if( natus::application::no_success( get_glx_extension(ext_list) ) ) return natus::application::result::failed_wgl ; this_t::strings_t::iterator iter = ext_list.begin() ; while( iter != ext_list.end() ) { if( *iter == extension_name ) return natus::application::result::ok ; ++iter ; } return natus::application::result::invalid_extension ; } //***************************************************************** natus::application::result context::get_glx_extension( this_t::strings_out_t /*ext_list*/ ) { return natus::application::result::ok ; } //**************************************************************** natus::application::result context::get_gl_extension( this_t::strings_out_t ext_list ) { const GLubyte * ch = natus::ogl::glGetString( GL_EXTENSIONS ) ; if( !ch ) return natus::application::result::failed ; natus::ntd::string_t extension_string( (const char*)ch) ; natus::ntd::string_ops::split( extension_string, ' ', ext_list ) ; return natus::application::result::ok ; } //**************************************************************** natus::application::result context::get_gl_version( natus::application::gl_version & version ) const { const GLubyte* ch = natus::ogl::glGetString(GL_VERSION) ; if( !ch ) return natus::application::result::failed ; natus::ntd::string_t version_string = natus::ntd::string((const char*)ch) ; GLint major = 0;//boost::lexical_cast<GLint, std::string>(*token) ; GLint minor = 0;//boost::lexical_cast<GLint, std::string>(*(++token)); { natus::ogl::glGetIntegerv( GL_MAJOR_VERSION, &major ) ; GLenum err = natus::ogl::glGetError() ; if( err != GL_NO_ERROR ) { natus::ntd::string_t const es = ::std::to_string(err) ; natus::log::global::error( "[context::get_gl_version] : get gl major <"+es+">" ) ; } } { natus::ogl::glGetIntegerv( GL_MINOR_VERSION, &minor) ; GLenum err = natus::ogl::glGetError() ; if( err != GL_NO_ERROR ) { natus::ntd::string_t es = ::std::to_string(err) ; natus::log::global::error( "[context::get_gl_version] : get gl minor <"+es+">" ) ; } } version.major = major ; version.minor = minor ; return natus::application::result::ok ; } //**************************************************************** void_t context::clear_now( natus::math::vec4f_t const & vec ) { natus::ogl::glClearColor( vec.x(), vec.y(), vec.z(), vec.w() ) ; natus::ogl::glClear( GL_COLOR_BUFFER_BIT ) ; GLenum const gler = natus::ogl::glGetError() ; natus::log::global_t::error( gler != GL_NO_ERROR, "[context::clear_now] : glClear" ) ; } //*************************************************************** natus::application::result context::create_the_context( gl_info_cref_t gli ) { auto res = natus::ogl::glx::init( _display, DefaultScreen( _display ) ) ; if( natus::log::global_t::error( natus::ogl::no_success(res), "[glx_window::create_glx_window] : init glx") ) { return natus::application::result::failed ; } int glx_major, glx_minor ; if( !glXQueryVersion( _display, &glx_major, &glx_minor ) ) { natus::log::global_t::error( "[glx_window::create_glx_window] : glXQueryVersion") ; return natus::application::result::failed ; } if( glx_major < 1 ) return natus::application::result::failed_glx ; if( glx_minor < 3 ) return natus::application::result::failed_glx ; // determine the GL version by creating a simple 1.0 context. natus::application::gl_version glv ; if( !this_t::determine_gl_version( glv ) ) { natus::log::global_t::error( natus_log_fn( "failed to determine gl version ") ) ; return natus::application::result::failed ; } int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, glv.major, GLX_CONTEXT_MINOR_VERSION_ARB, glv.minor, None } ; GLXContext context = natus::ogl::glx::glXCreateContextAttribs( _display, natus::application::glx::window::get_config(), 0, True, context_attribs ); if( natus::log::global_t::error( !context, natus_log_fn( "glXCreateContextAttribs" )) ) { return natus::application::result::failed ; } natus::ogl::gl::init() ; //this_t::activate() ; glXMakeCurrent( _display, _wnd, context ) ; { gl_version version ; if( !success( this_t::get_gl_version( version ) ) ) { natus::log::global_t::error( natus_log_fn( "" ) ) ; this_t::deactivate() ; return result::failed_gfx_context_creation ; } natus::log::global_t::status( "GL Version: " + ::std::to_string(version.major) + "." + ::std::to_string(version.minor) ) ; } { auto const res = this_t::vsync( gli.vsync_enabled ) ; natus::log::global_t::warning( natus::application::no_success(res), natus_log_fn("vsync") ) ; } glXMakeCurrent( _display, 0, 0 ) ; _context = context ; return natus::application::result::ok ; } //**************************************************************** bool_t context::determine_gl_version( gl_version & gl_out ) const { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 1,//gli.version.major, GLX_CONTEXT_MINOR_VERSION_ARB, 0,//gli.version.minor, None } ; GLXContext context = natus::ogl::glx::glXCreateContextAttribs( _display, natus::application::glx::window::get_config(), 0, True, context_attribs ); if( natus::log::global_t::error( !context, natus_log_fn( "glXCreateContextAttribs") ) ) { return false ; } natus::ogl::gl::init() ; gl_version version ; glXMakeCurrent( _display, _wnd, context ) ; { if( !success( this_t::get_gl_version( version ) ) ) { natus::log::global_t::error( natus_log_fn( "" ) ) ; glXMakeCurrent( _display, 0, 0 ) ; glXDestroyContext( _display, context ) ; return false ; } natus::log::global_t::status( "[determine_gl_version] : GL Version: " + ::std::to_string(version.major) + "." + ::std::to_string(version.minor) ) ; } glXMakeCurrent( _display, 0, 0 ) ; glXDestroyContext( _display, context ) ; gl_out = version ; return true ; }
31.444444
101
0.556816
aconstlink
40b19aca603359a140e201070d083b186e3ccd88
1,748
cpp
C++
QuadTree/main.cpp
szebest/SFML
b3d48d23777aef73e4287c783b188fdfa7e40656
[ "MIT" ]
2
2020-02-13T19:24:23.000Z
2021-02-03T14:48:58.000Z
QuadTree/main.cpp
szebest/SFML
b3d48d23777aef73e4287c783b188fdfa7e40656
[ "MIT" ]
null
null
null
QuadTree/main.cpp
szebest/SFML
b3d48d23777aef73e4287c783b188fdfa7e40656
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <string> #include <vector> #include <cmath> #include <iostream> #include "QuadTree.h" #include "Functions.h" #define WIDTH 1600 #define HEIGHT 900 #define FRAMETIME 16666 using namespace std; int main() { int wynik=0; int a = 100000; int b = 50000; try { int c = 0; wynik = a * b; if (b > 0 && a > std::numeric_limits< int >::max() / b) throw std::overflow_error("adding a and b would cause overflow"); } catch (std::overflow_error e) { std::cout << e.what() << '\n'; } std::cout << wynik; srand(time(NULL)); float r_time=0; sf::Clock zegar; sf::Clock zegar2; sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "SFML"); QuadTree q(Rectangle(0, 0, WIDTH, HEIGHT), 4); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { q.insert(Point((sf::Vector2f)sf::Mouse::getPosition(window))); } } } if (zegar2.getElapsedTime().asMicroseconds() >= FRAMETIME - r_time) { zegar2.restart(); zegar.restart(); std::vector<Point> points = q.getPointsInsideRange(Rectangle(0, 0, WIDTH, HEIGHT)); window.clear(sf::Color::Black); for (int i = 0; i < points.size(); i++) { sf::Vertex point(sf::Vector2f(points[i].getX(), points[i].getY()), sf::Color::White); window.draw(&point, 1, sf::Points); } q.drawRectangles(window); window.display(); r_time=zegar.getElapsedTime().asMicroseconds(); } } return 0; }
20.325581
89
0.591533
szebest
40b50e590a7ebe4dd51ddb6ca387a271214b3ea4
2,430
cpp
C++
unionfind.cpp
im-red/maze
b443ffd7653f355d316537dced8a326160bf5b53
[ "MIT" ]
4
2020-09-08T08:05:53.000Z
2022-02-14T10:25:26.000Z
unionfind.cpp
im-red/maze
b443ffd7653f355d316537dced8a326160bf5b53
[ "MIT" ]
null
null
null
unionfind.cpp
im-red/maze
b443ffd7653f355d316537dced8a326160bf5b53
[ "MIT" ]
1
2019-02-02T01:33:57.000Z
2019-02-02T01:33:57.000Z
/********************************************************************************* * MIT License * * Copyright (c) 2020 Jia Lihong * * 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 "unionfind.h" using namespace std; UnionFind::UnionFind(int n) : m_index2parent(static_cast<size_t>(n)) , m_index2treeSize(static_cast<size_t>(n)) , m_nodeCount(n) , m_connectionCount(0) { for (int i = 0; i < n; i++) { m_index2parent[static_cast<size_t>(i)] = i; m_index2treeSize[static_cast<size_t>(i)] = 1; } } UnionFind::~UnionFind() { } void UnionFind::connect(int p, int q) { int i = root(p); int j = root(q); if (i == j) { return; } if (m_index2treeSize[static_cast<size_t>(i)] < m_index2treeSize[static_cast<size_t>(j)]) { m_index2parent[static_cast<size_t>(i)] = j; m_index2treeSize[static_cast<size_t>(j)] += m_index2treeSize[static_cast<size_t>(i)]; } else { m_index2parent[static_cast<size_t>(j)] = i; m_index2treeSize[static_cast<size_t>(i)] += m_index2treeSize[static_cast<size_t>(j)]; } m_connectionCount++; } int UnionFind::root(int p) { while (p != m_index2parent[static_cast<size_t>(p)]) { p = m_index2parent[static_cast<size_t>(p)]; } return p; }
31.558442
93
0.639918
im-red
40b6767a57c6743448b369bb0d585249fac61891
1,734
cpp
C++
libcaf_core/src/ipv4_subnet.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
2,517
2015-01-04T22:19:43.000Z
2022-03-31T12:20:48.000Z
libcaf_core/src/ipv4_subnet.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
894
2015-01-07T14:21:21.000Z
2022-03-30T06:37:18.000Z
libcaf_core/src/ipv4_subnet.cpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
570
2015-01-21T18:59:33.000Z
2022-03-31T19:00:02.000Z
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #include "caf/ipv4_subnet.hpp" #include "caf/detail/mask_bits.hpp" namespace caf { // -- constructors, destructors, and assignment operators -------------------- ipv4_subnet::ipv4_subnet() : prefix_length_(0) { // nop } ipv4_subnet::ipv4_subnet(ipv4_address network_address, uint8_t prefix_length) : address_(network_address), prefix_length_(prefix_length) { detail::mask_bits(address_.bytes(), prefix_length_); } // -- properties --------------------------------------------------------------- bool ipv4_subnet::contains(ipv4_address addr) const noexcept { return address_ == addr.network_address(prefix_length_); } bool ipv4_subnet::contains(ipv4_subnet other) const noexcept { // We can only contain a subnet if it's prefix is greater or equal. if (prefix_length_ > other.prefix_length_) return false; return prefix_length_ == other.prefix_length_ ? address_ == other.address_ : address_ == other.address_.network_address(prefix_length_); } // -- comparison --------------------------------------------------------------- int ipv4_subnet::compare(const ipv4_subnet& other) const noexcept { auto sub_res = address_.compare(other.address_); return sub_res != 0 ? sub_res : static_cast<int>(prefix_length_) - other.prefix_length_; } std::string to_string(ipv4_subnet x) { auto result = to_string(x.network_address()); result += '/'; result += std::to_string(x.prefix_length()); return result; } } // namespace caf
32.111111
80
0.664937
seewpx
8ad61eec7148a1d8616a17976e2d146cde3f2958
862
hpp
C++
Krakoa/Source/UI/ImGui/ControllersUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
1
2020-04-05T13:37:48.000Z
2020-04-05T13:37:48.000Z
Krakoa/Source/UI/ImGui/ControllersUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
Krakoa/Source/UI/ImGui/ControllersUI.hpp
KingKiller100/Krakoa-Engine
0f2a5a5109e256a384abe8dc21eacaa45c1de610
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../../Graphics/Colour.hpp" namespace krakoa { namespace gfx { class Font; } namespace ui { bool DrawVec3Controller(const std::string_view& label, kmaths::Vector3f& values, const std::array<gfx::Colour, 3>& btnColours , float incrementVal = 0.1f, kmaths::Vector3f::Type resetValue = 0.f , float columnWidth = 100.f); bool DrawVec3Controller(const std::string_view& label, kmaths::Vector3f& values, const std::array<gfx::Colour, 3>& btnColours, const gfx::Font& font , float incrementVal = 0.1f, kmaths::Vector3f::Type resetValue = 0.f , float columnWidth = 100.f); bool DrawColourController(const std::string_view& label, gfx::Colour& value, float columnWidth = 100.f); bool DrawColourController(const std::string_view& label, gfx::Colour& value, const gfx::Font& font, float columnWidth = 100.f); } }
34.48
129
0.713457
KingKiller100
8ada4449acc048edf639563debef412070fd57a8
16,936
cc
C++
engine/source/platform/platformVideo.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/platform/platformVideo.cc
v3rc3tti/Torque2D
b4cc8826b1b7c2f91037ee08743fbe31b6e3d867
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/platform/platformVideo.cc
v3rc3tti/Torque2D
b4cc8826b1b7c2f91037ee08743fbe31b6e3d867
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "platform/platformVideo.h" #include "gui/guiCanvas.h" #include "console/console.h" #include "game/gameInterface.h" #include "platformVideo_ScriptBinding.h" extern void GameDeactivate( bool noRender ); extern void GameReactivate(); #ifdef TORQUE_OS_ANDROID extern int _AndroidGetScreenWidth(); extern int _AndroidGetScreenHeight(); #endif // Static class data: Vector<DisplayDevice*> Video::smDeviceList; DisplayDevice* Video::smCurrentDevice; bool Video::smCritical = false; bool Video::smNeedResurrect = false; Resolution DisplayDevice::smCurrentRes; bool DisplayDevice::smIsFullScreen; //------------------------------------------------------------------------------ void Video::init() { Con::printSeparator(); Con::printf("Video initialization:"); destroy(); } //------------------------------------------------------------------------------ void Video::destroy() { if ( smCurrentDevice ) { smCritical = true; smCurrentDevice->shutdown(); smCritical = false; } smCurrentDevice = NULL; for ( U32 i = 0; i < (U32)smDeviceList.size(); i++ ) delete smDeviceList[i]; smDeviceList.clear(); } //------------------------------------------------------------------------------ bool Video::installDevice( DisplayDevice *dev ) { if ( dev ) { smDeviceList.push_back( dev ); return true; } return false; } //------------------------------------------------------------------------------ bool Video::setDevice( const char *renderName, U32 width, U32 height, U32 bpp, bool fullScreen ) { S32 deviceIndex = NO_DEVICE; S32 iOpenGL = -1; S32 iD3D = -1; bool bOpenglRender = true; //(bool)(dStricmp(renderName,"OpenGL") == 0); bool bD3DRender = false; //(bool)(dStricmp(renderName,"D3D") == 0); bool bAllowD3D = false; //Con::getBoolVariable("$pref::Video::allowD3D"); bool bAllowOpengl = true; //Con::getBoolVariable("$pref::Video::allowOpenGL"); for ( S32 i = 0; i < smDeviceList.size(); i++ ) { if ( dStrcmp( smDeviceList[i]->mDeviceName, renderName ) == 0 ) deviceIndex = i; if ( dStrcmp( smDeviceList[i]->mDeviceName, "OpenGL" ) == 0 ) iOpenGL = i; if ( dStrcmp( smDeviceList[i]->mDeviceName, "D3D" ) == 0 ) iD3D = i; } if ( deviceIndex == NO_DEVICE ) { Con::warnf( ConsoleLogEntry::General, "\"%s\" display device not found!", renderName ); return false; } // Change the display device: if ( smDeviceList[deviceIndex] == NULL ) return false; if (smCurrentDevice && smCurrentDevice != smDeviceList[deviceIndex]) { Con::printf( "Deactivating the previous display device..." ); Game->textureKill(); smNeedResurrect = true; smCurrentDevice->shutdown(); } if (iOpenGL != -1 && !bAllowOpengl ) { // change to D3D, delete OpenGL in the recursive call if ( bOpenglRender ) { U32 w, h, d; if( fullScreen ) dSscanf(Con::getVariable("$pref::Video::resolution"), "%d %d %d", &w, &h, &d); else dSscanf(Con::getVariable("$pref::Video::windowedRes"), "%d %d %d", &w, &h, &d); return setDevice("D3D",w,h,d,fullScreen); } else { delete smDeviceList[iOpenGL]; smDeviceList.erase(iOpenGL); } } else if (iD3D != -1 && !bAllowD3D ) { // change to OpenGL, delete D3D in the recursive call if ( bD3DRender ) { U32 w, h, d; if( fullScreen ) dSscanf(Con::getVariable("$pref::Video::resolution"), "%d %d %d", &w, &h, &d); else dSscanf(Con::getVariable("$pref::Video::windowedRes"), "%d %d %d", &w, &h, &d); return setDevice("OpenGL",w,h,d,fullScreen); } else { delete smDeviceList[iD3D]; smDeviceList.erase(iD3D); } } else if (iD3D != -1 && bOpenglRender && !Con::getBoolVariable("$pref::Video::preferOpenGL") && !Con::getBoolVariable("$pref::Video::appliedPref")) { U32 w, h, d; if( fullScreen ) dSscanf(Con::getVariable("$pref::Video::resolution"), "%d %d %d", &w, &h, &d); else dSscanf(Con::getVariable("$pref::Video::windowedRes"), "%d %d %d", &w, &h, &d); Con::setBoolVariable("$pref::Video::appliedPref", true); return setDevice("D3D",w,h,d,fullScreen); } else Con::setBoolVariable("$pref::Video::appliedPref", true); Con::printf( "Activating the %s display device...", renderName ); smCurrentDevice = smDeviceList[deviceIndex]; smCritical = true; bool result = smCurrentDevice->activate( width, height, bpp, fullScreen ); smCritical = false; if ( result ) { if (smNeedResurrect) { Game->textureResurrect(); smNeedResurrect = false; } //if (sgOriginalGamma != -1.0 || Video::getGammaCorrection(sgOriginalGamma)) //Video::setGammaCorrection(sgOriginalGamma + sgGammaCorrection); Con::evaluate("resetCanvas();"); } // Show Maximum Texture Size reported by the graphics hardware. GLint maxTextureSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); if ( maxTextureSize > 0 ) Con::printf("Max Texture Size reported as: %d", maxTextureSize); else Con::warnf("Max Texture Size reported as: %d !", maxTextureSize); // The video mode activate may have failed above, return that status return( result ); } extern bool retinaEnabled; //------------------------------------------------------------------------------ bool Video::setScreenMode( U32 width, U32 height, U32 bpp, bool fullScreen ) { if ( smCurrentDevice ) { //MIN_RESOLUTION defined in platformWin32/platformGL.h #ifdef TORQUE_OS_IOS if(width == 0) width = IOS_DEFAULT_RESOLUTION_X; if(height == 0) height = IOS_DEFAULT_RESOLUTION_Y; if(bpp == 0) bpp = IOS_DEFAULT_RESOLUTION_BIT_DEPTH; //if(retinaEnabled) //{ // width *=2; // height *=2; //} #elif TORQUE_OS_ANDROID if(width == 0) width = _AndroidGetScreenWidth(); if(height == 0) height = _AndroidGetScreenHeight(); if(bpp == 0) bpp = ANDROID_DEFAULT_RESOLUTION_BIT_DEPTH; #else if(width == 0) width = MIN_RESOLUTION_X; if(height == 0) height = MIN_RESOLUTION_Y; if(bpp == 0) bpp = MIN_RESOLUTION_BIT_DEPTH; #endif// TORQUE_OS_IOS smCritical = true; bool result = smCurrentDevice->setScreenMode( width, height, bpp, fullScreen ); smCritical = false; return( result ); } return( false ); } //------------------------------------------------------------------------------ void Video::deactivate( bool force ) { if ( smCritical ) return; bool doDeactivate = force ? true : DisplayDevice::isFullScreen(); Game->gameDeactivate( doDeactivate ); if ( smCurrentDevice && doDeactivate ) { smCritical = true; Game->textureKill(); smCurrentDevice->shutdown(); Platform::minimizeWindow(); smCritical = false; } } //------------------------------------------------------------------------------ void Video::reactivate( bool force ) { if ( smCritical ) return; bool doReactivate = force ? true : DisplayDevice::isFullScreen(); if ( smCurrentDevice && doReactivate ) { Resolution res = DisplayDevice::getResolution(); smCritical = true; smCurrentDevice->activate(res.w,res.h,res.bpp,DisplayDevice::isFullScreen()); Game->textureResurrect(); smCritical = false; if (sgOriginalGamma != -1.0) Video::setGammaCorrection(sgOriginalGamma + sgGammaCorrection); } Game->gameReactivate(); } //------------------------------------------------------------------------------ bool Video::setResolution( U32 width, U32 height, U32 bpp ) { if ( smCurrentDevice ) { if ( bpp == 0 ) bpp = DisplayDevice::getResolution().bpp; smCritical = true; bool result = smCurrentDevice->setResolution( width, height, bpp ); smCritical = false; return( result ); } return( false ); } //------------------------------------------------------------------------------ bool Video::toggleFullScreen() { if ( smCurrentDevice ) { smCritical = true; bool result = smCurrentDevice->toggleFullScreen(); smCritical = false; return( result ); } return( false ); } //------------------------------------------------------------------------------ DisplayDevice* Video::getDevice( const char* renderName ) { for ( S32 i = 0; i < smDeviceList.size(); i++ ) { if ( dStrcmp( smDeviceList[i]->mDeviceName, renderName ) == 0 ) return( smDeviceList[i] ); } return( NULL ); } //------------------------------------------------------------------------------ bool Video::prevRes() { if ( smCurrentDevice ) { smCritical = true; bool result = smCurrentDevice->prevRes(); smCritical = false; return( result ); } return( false ); } //------------------------------------------------------------------------------ bool Video::nextRes() { if ( smCurrentDevice ) { smCritical = true; bool result = smCurrentDevice->nextRes(); smCritical = false; return( result ); } return( false ); } //------------------------------------------------------------------------------ Resolution Video::getResolution() { return DisplayDevice::getResolution(); } //------------------------------------------------------------------------------ const char* Video::getDeviceList() { U32 deviceCount = smDeviceList.size(); if ( deviceCount > 0 ) // It better be... { U32 strLen = 0, i; for ( i = 0; i < deviceCount; i++ ) strLen += ( dStrlen( smDeviceList[i]->mDeviceName ) + 1 ); char* returnString = Con::getReturnBuffer( strLen ); dStrcpy( returnString, smDeviceList[0]->mDeviceName ); for ( i = 1; i < deviceCount; i++ ) { dStrcat( returnString, "\t" ); dStrcat( returnString, smDeviceList[i]->mDeviceName ); } return( returnString ); } return( NULL ); } //------------------------------------------------------------------------------ const char* Video::getResolutionList() { if ( smCurrentDevice ) return smCurrentDevice->getResolutionList(); else return NULL; } //------------------------------------------------------------------------------ const char* Video::getDriverInfo() { if ( smCurrentDevice ) return smCurrentDevice->getDriverInfo(); else return NULL; } //------------------------------------------------------------------------------ bool Video::isFullScreen() { return DisplayDevice::isFullScreen(); } //------------------------------------------------------------------------------ void Video::swapBuffers() { if ( smCurrentDevice ) smCurrentDevice->swapBuffers(); } //------------------------------------------------------------------------------ bool Video::getGammaCorrection(F32 &g) { if (smCurrentDevice) return smCurrentDevice->getGammaCorrection(g); return false; } //------------------------------------------------------------------------------ bool Video::setGammaCorrection(F32 g) { if (smCurrentDevice) return smCurrentDevice->setGammaCorrection(g); return false; } //------------------------------------------------------------------------------ bool Video::getVerticalSync() { if (smCurrentDevice) return smCurrentDevice->getVerticalSync(); return( false ); } //------------------------------------------------------------------------------ bool Video::setVerticalSync( bool on ) { if ( smCurrentDevice ) return( smCurrentDevice->setVerticalSync( on ) ); return( false ); } //------------------------------------------------------------------------------ DisplayDevice::DisplayDevice() { mDeviceName = NULL; } //------------------------------------------------------------------------------ void DisplayDevice::init() { smCurrentRes = Resolution( 0, 0, 0 ); smIsFullScreen = false; } //------------------------------------------------------------------------------ bool DisplayDevice::prevRes() { U32 resIndex; for ( resIndex = mResolutionList.size() - 1; resIndex > 0; resIndex-- ) { if ( mResolutionList[resIndex].bpp == smCurrentRes.bpp && mResolutionList[resIndex].w <= smCurrentRes.w && mResolutionList[resIndex].h != smCurrentRes.h ) break; } if ( mResolutionList[resIndex].bpp == smCurrentRes.bpp ) return( Video::setResolution( mResolutionList[resIndex].w, mResolutionList[resIndex].h, mResolutionList[resIndex].bpp ) ); return( false ); } //------------------------------------------------------------------------------ bool DisplayDevice::nextRes() { U32 resIndex; for ( resIndex = 0; resIndex < (U32)mResolutionList.size() - 1; resIndex++ ) { if ( mResolutionList[resIndex].bpp == smCurrentRes.bpp && mResolutionList[resIndex].w >= smCurrentRes.w && mResolutionList[resIndex].h != smCurrentRes.h ) break; } if ( mResolutionList[resIndex].bpp == smCurrentRes.bpp ) return( Video::setResolution( mResolutionList[resIndex].w, mResolutionList[resIndex].h, mResolutionList[resIndex].bpp ) ); return( false ); } //------------------------------------------------------------------------------ // This function returns a string containing all of the available resolutions for this device // in the format "<bit depth> <width> <height>", separated by tabs. // const char* DisplayDevice::getResolutionList() { if (Con::getBoolVariable("$pref::Video::clipHigh", false)) for (S32 i = mResolutionList.size()-1; i >= 0; --i) if (mResolutionList[i].w > 1152 || mResolutionList[i].h > 864) mResolutionList.erase(i); if (Con::getBoolVariable("$pref::Video::only16", false)) for (S32 i = mResolutionList.size()-1; i >= 0; --i) if (mResolutionList[i].bpp == 32) mResolutionList.erase(i); U32 resCount = mResolutionList.size(); if ( resCount > 0 ) { char* tempBuffer = new char[resCount * 15]; tempBuffer[0] = 0; for ( U32 i = 0; i < resCount; i++ ) { char newString[15]; dSprintf( newString, sizeof( newString ), "%d %d %d\t", mResolutionList[i].w, mResolutionList[i].h, mResolutionList[i].bpp ); dStrcat( tempBuffer, newString ); } tempBuffer[dStrlen( tempBuffer ) - 1] = 0; char* returnString = Con::getReturnBuffer( dStrlen( tempBuffer ) + 1 ); dStrcpy( returnString, tempBuffer ); delete [] tempBuffer; return returnString; } return NULL; }
29.35182
135
0.515529
close-code
8ae18f16310a52aafa69bfb71ab2a44ae66b50ab
5,314
cpp
C++
Geometry/convex_cut.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
197
2018-08-19T06:49:14.000Z
2022-03-26T04:11:48.000Z
Geometry/convex_cut.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
null
null
null
Geometry/convex_cut.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
15
2018-09-14T09:15:12.000Z
2021-11-16T12:43:43.000Z
// // 凸多角形の切断, O(n) // // verified: // AOJ Course CGL_4_C Convex Polygon - Convex Cut // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=jp // /* 問題例 ・AOJ 2385 ・AOJ 2160 */ //////////////////////////// // 基本要素 (点, 線分, 円) //////////////////////////// #include <iostream> #include <vector> #include <cmath> #include <iomanip> #include <algorithm> using namespace std; using DD = double; const DD INF = 1LL<<60; // to be set appropriately const DD EPS = 1e-10; // to be set appropriately const DD PI = acosl(-1.0); DD torad(int deg) {return (DD)(deg) * PI / 180;} DD todeg(DD ang) {return ang * 180 / PI;} /* Point */ struct Point { DD x, y; Point(DD x = 0.0, DD y = 0.0) : x(x), y(y) {} friend ostream& operator << (ostream &s, const Point &p) {return s << '(' << p.x << ", " << p.y << ')';} }; inline Point operator + (const Point &p, const Point &q) {return Point(p.x + q.x, p.y + q.y);} inline Point operator - (const Point &p, const Point &q) {return Point(p.x - q.x, p.y - q.y);} inline Point operator * (const Point &p, DD a) {return Point(p.x * a, p.y * a);} inline Point operator * (DD a, const Point &p) {return Point(a * p.x, a * p.y);} inline Point operator * (const Point &p, const Point &q) {return Point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);} inline Point operator / (const Point &p, DD a) {return Point(p.x / a, p.y / a);} inline Point conj(const Point &p) {return Point(p.x, -p.y);} inline Point rot(const Point &p, DD ang) {return Point(cos(ang) * p.x - sin(ang) * p.y, sin(ang) * p.x + cos(ang) * p.y);} inline Point rot90(const Point &p) {return Point(-p.y, p.x);} inline DD cross(const Point &p, const Point &q) {return p.x * q.y - p.y * q.x;} inline DD dot(const Point &p, const Point &q) {return p.x * q.x + p.y * q.y;} inline DD norm(const Point &p) {return dot(p, p);} inline DD abs(const Point &p) {return sqrt(dot(p, p));} inline DD amp(const Point &p) {DD res = atan2(p.y, p.x); if (res < 0) res += PI*2; return res;} inline bool eq(const Point &p, const Point &q) {return abs(p - q) < EPS;} inline bool operator < (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x < q.x : p.y < q.y);} inline bool operator > (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x > q.x : p.y > q.y);} inline Point operator / (const Point &p, const Point &q) {return p * conj(q) / norm(q);} /* Line */ struct Line : vector<Point> { Line(Point a = Point(0.0, 0.0), Point b = Point(0.0, 0.0)) { this->push_back(a); this->push_back(b); } friend ostream& operator << (ostream &s, const Line &l) {return s << '{' << l[0] << ", " << l[1] << '}';} }; /* Circle */ struct Circle : Point { DD r; Circle(Point p = Point(0.0, 0.0), DD r = 0.0) : Point(p), r(r) {} friend ostream& operator << (ostream &s, const Circle &c) {return s << '(' << c.x << ", " << c.y << ", " << c.r << ')';} }; /////////////////////// // 多角形 /////////////////////// // 多角形の面積 DD Area(const vector<Point> &pol) { DD res = 0.0; for (int i = 0; i < pol.size(); ++i) { res += cross(pol[i], pol[(i+1)%pol.size()]); } return res/2.0L; } // convex cut int ccw_for_convexcut(const Point &a, const Point &b, const Point &c) { if (cross(b-a, c-a) > EPS) return 1; if (cross(b-a, c-a) < -EPS) return -1; if (dot(b-a, c-a) < -EPS) return 2; if (norm(b-a) < norm(c-a) - EPS) return -2; return 0; } vector<Point> crosspoint_for_convexcut(const Line &l, const Line &m) { vector<Point> res; DD d = cross(m[1] - m[0], l[1] - l[0]); if (abs(d) < EPS) return vector<Point>(); res.push_back(l[0] + (l[1] - l[0]) * cross(m[1] - m[0], m[1] - l[0]) / d); return res; } vector<Point> ConvexCut(const vector<Point> &pol, const Line &l) { vector<Point> res; for (int i = 0; i < pol.size(); ++i) { Point p = pol[i], q = pol[(i+1)%pol.size()]; if (ccw_for_convexcut(l[0], l[1], p) != -1) { if (res.size() == 0) res.push_back(p); else if (!eq(p, res[res.size()-1])) res.push_back(p); } if (ccw_for_convexcut(l[0], l[1], p) * ccw_for_convexcut(l[0], l[1], q) < 0) { vector<Point> temp = crosspoint_for_convexcut(Line(p, q), l); if (temp.size() == 0) continue; else if (res.size() == 0) res.push_back(temp[0]); else if (!eq(temp[0], res[res.size()-1])) res.push_back(temp[0]); } } return res; } // Voronoi-diagram (今回は使わない) Line bisector(const Point &p, const Point &q) { Point c = (p + q) / 2.0L; Point v = (q - p) * Point(0.0L, 1.0L); v = v / abs(v); return Line(c - v, c + v); } vector<Point> Voronoi(vector<Point> pol, const vector<Point> &ps, int ind) { for (int i = 0; i < ps.size(); ++i) { if (i == ind) continue; Line l = bisector(ps[ind], ps[i]); pol = ConvexCut(pol, l); } return pol; } int main() { int n; cin >> n; vector<Point> pol(n); for (int i = 0; i < n; ++i) cin >> pol[i].x >> pol[i].y; int Q; cin >> Q; for (int _ = 0; _ < Q; ++_) { Point x, y; cin >> x.x >> x.y >> y.x >> y.y; Line l(x, y); auto cutted = ConvexCut(pol, l); cout << fixed << setprecision(10) << Area(cutted) << endl; } }
34.732026
124
0.535002
landcelita
8ae4c44940ccd042ec9e228ec297e881c93f12d9
3,768
hpp
C++
lib/libstereo/src/costs/scale.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
lib/libstereo/src/costs/scale.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
lib/libstereo/src/costs/scale.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#ifndef _FTL_LIBSTEREO_COSTS_EXP_HPP_ #define _FTL_LIBSTEREO_COSTS_EXP_HPP_ #include "array2d.hpp" #include "dsbase.hpp" #include <cuda_runtime.h> namespace impl { template <typename A> struct ExpCost : DSImplBase<float> { typedef float Type; ExpCost(ushort w, ushort h, ushort dmin, ushort dmax) : DSImplBase<float>({w,h,dmin,dmax}), cost_a(w,h,dmin,dmax) {} __host__ __device__ inline float operator()(const int y, const int x, const int d) const { return 1.0f-expf(-cost_a(y,x,d)*l); } A cost_a; float l=1.0; static constexpr Type COST_MAX = A::COST_MAX; }; template <typename A> struct LinearCost : DSImplBase<float> { typedef float Type; LinearCost(ushort w, ushort h, ushort dmin, ushort dmax) : DSImplBase<float>({w,h,dmin,dmax}), cost_a(w,h,dmin,dmax) {} __host__ __device__ inline float operator()(const int y, const int x, const int d) const { return cost_a(y,x,d)*s*a; } A cost_a; float a=1.0; float s=1.0; static constexpr Type COST_MAX = A::COST_MAX; }; template <typename A, typename T> struct WeightedCost : DSImplBase<T> { typedef T Type; WeightedCost(ushort w, ushort h, ushort dmin, ushort dmax) : DSImplBase<Type>({w,h,dmin,dmax}), cost(w,h,dmin,dmax) {} __host__ __device__ inline Type operator()(const int y, const int x, const int d) const { const float w = max(weights_l(y,x), weights_r(y,x)); return round(cost(y,x,d)*w); } A cost; Array2D<float>::Data weights_l; Array2D<float>::Data weights_r; static constexpr Type COST_MAX = A::COST_MAX; }; } template <typename A> class ExpCost : public DSBase<impl::ExpCost<typename A::DataType>> { public: typedef impl::ExpCost<typename A::DataType> DataType; typedef float Type; ExpCost(int width, int height, int disp_min, int disp_max, A &a, float l) : DSBase<DataType>(width, height, disp_min, disp_max), cost_a(a) {}; void set() { this->data().cost_a = cost_a.data(); } void set(float l) { this->data().cost_a = cost_a.data(); this->data().l = l; } static constexpr float COST_MAX = A::COST_MAX; protected: A &cost_a; }; template <typename A> class LinearCost : public DSBase<impl::LinearCost<typename A::DataType>> { public: typedef impl::LinearCost<typename A::DataType> DataType; typedef float Type; LinearCost(int width, int height, int disp_min, int disp_max, A &a, float l) : DSBase<DataType>(width, height, disp_min, disp_max), cost_a(a) { this->data().s = l; this->data().a = 1.0f/COST_MAX; } void set() { this->data().cost_a = cost_a.data(); } void set(float s) { this->data().cost_a = cost_a.data(); this->data().s = s; } static const typename A::Type COST_MAX = A::COST_MAX; protected: A &cost_a; }; template <typename A, typename T=unsigned short> class WeightedCost : public DSBase<impl::WeightedCost<typename A::DataType, T>> { public: typedef impl::WeightedCost<typename A::DataType, T> DataType; typedef T Type; WeightedCost(int width, int height, int disp_min, int disp_max, A &a, Array2D<float> &wl, Array2D<float> &wr) : DSBase<DataType>(width, height, disp_min, disp_max), cost(&a), weights_l(&wl), weights_r(&wr) { } WeightedCost(int width, int height, int disp_min, int disp_max) : DSBase<DataType>(width, height, disp_min, disp_max), cost(nullptr), weights_l(nullptr), weights_r(nullptr) { } void setCost(A &c) { cost = &c; } void setWeights(Array2D<float> &wl, Array2D<float> &wr) { weights_l = &wl; weights_r = &wr; } void set() { this->data().cost = cost->data(); this->data().weights_l = weights_l->data(); this->data().weights_r = weights_r->data(); } static const T COST_MAX = A::COST_MAX; protected: Array2D<float> *weights_l; Array2D<float> *weights_r; A *cost; }; #endif
23.848101
110
0.682856
knicos
8ae756e0e1200302848a1d19e4b8bc26aa9fb1e1
295
hpp
C++
src/vulkan/vulkan_vertex_descriptor.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_vertex_descriptor.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/vulkan/vulkan_vertex_descriptor.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #include "buffer_layout.hpp" namespace cl::vulkan { VkVertexInputBindingDescription CreateInputBindingDescription(const BufferLayout& layout); std::vector<VkVertexInputAttributeDescription>CreateInputAttribDescriptions(const BufferLayout& layout); }
22.692308
104
0.837288
zfccxt
8aea56225c6e2d6fea53f0e88c7b59327aebdc48
824
hpp
C++
C++/Multiplayer/Step 5 - Weapons/shared/components/AnimatedAppearance.hpp
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
13
2016-07-14T16:27:25.000Z
2021-03-31T23:32:46.000Z
C++/Multiplayer/Step 5 - Weapons/shared/components/AnimatedAppearance.hpp
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
5
2018-03-22T16:11:39.000Z
2021-05-30T16:34:06.000Z
C++/Multiplayer/Step 5 - Weapons/shared/components/AnimatedAppearance.hpp
ProfPorkins/GameTech
aa45062d9003c593bf19f65708efcb99a13063c3
[ "MIT" ]
6
2018-03-22T16:00:02.000Z
2020-04-11T12:46:23.000Z
#pragma once #include "components/Component.hpp" #include <chrono> #include <string> #include <vector> // -------------------------------------------------------------- // // Specifies the an animated visual appearance. // // -------------------------------------------------------------- namespace components { class AnimatedAppearance : public Component { public: AnimatedAppearance(std::string texture, std::vector<std::chrono::milliseconds> spriteTime) : m_texture(texture), m_spriteTime(spriteTime) { } auto getTexture() { return m_texture; } const auto& getSpriteTime() { return m_spriteTime; } private: std::string m_texture; std::vector<std::chrono::milliseconds> m_spriteTime; }; } // namespace components
24.969697
100
0.541262
ProfPorkins
8aea83ee4cd24ba6be71bee4e4e71df6bde1149f
310
cpp
C++
Timus/1180.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Timus/1180.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Timus/1180.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
# include <iostream> # include <cstring> using namespace std; int ln,sum; char s[300]; int main() { cin>>s; ln=strlen(s); for (int i=0 ; i<ln ; i++) { sum+=s[i]-48; } switch(sum%3) { case 0: cout<<"2"; break; case 1: cout<<"1\n1"; break; case 2: cout<<"1\n2"; break; } return 0; }
10.689655
30
0.53871
s9v
8aeaaba5ab6b7a84194efe5c7b6be163d9be4da9
288
cpp
C++
Chapter3/Practice/1045.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
1
2022-02-13T02:22:39.000Z
2022-02-13T02:22:39.000Z
Chapter3/Practice/1045.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
null
null
null
Chapter3/Practice/1045.cpp
flics04/XXXASYBT_CppBase
0086df68497197f40286889b18f2d8c28eb833bb
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int x, y; int status0 = 1, status1 = 0; cin >> x >> y; if (x >= 10) cout << status0 << endl; else if (y >= 20) cout << status0 << endl; else cout << status1 << endl; return 0; }
15.157895
33
0.479167
flics04
8aeffd6605ebb7bbe49f0c6dccba55323564ac87
7,482
cpp
C++
src/loop071.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
4
2016-11-07T12:50:14.000Z
2020-04-30T19:48:05.000Z
src/loop071.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
1
2017-04-17T12:00:16.000Z
2017-04-17T12:00:16.000Z
src/loop071.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
null
null
null
#include "demoloop.h" #include "graphics/shader.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <functional> #include <array> #include "graphics/polyline.h" using namespace std; using namespace demoloop; const uint32_t CYCLE_LENGTH = 4; const float farPlane = 40.0; template<size_t slices, size_t stacks> array<Vertex, stacks * slices * 6> parametric(std::function<Vertex(float, float, uint32_t, uint32_t)> func) { array<Vertex, (stacks + 1) * (slices + 1)> vertices; uint32_t index = 0; const uint32_t sliceCount = slices + 1; for (uint32_t i = 0; i <= stacks; ++i) { const float v = static_cast<float>(i) / stacks; for (uint32_t j = 0; j <= slices; ++j) { const float u = static_cast<float>(j) / slices; vertices[index++] = func(u, v, slices, stacks); } } array<Vertex, stacks * slices * 6> indices; index = 0; for (uint32_t i = 0; i < stacks; ++i) { for (uint32_t j = 0; j < slices; ++j) { const float a = i * sliceCount + j; const float b = i * sliceCount + j + 1; const float c = ( i + 1 ) * sliceCount + j + 1; const float d = ( i + 1 ) * sliceCount + j; // faces one and two indices[index++] = vertices[a]; indices[index++] = vertices[b]; indices[index++] = vertices[d]; indices[index++] = vertices[b]; indices[index++] = vertices[c]; indices[index++] = vertices[d]; } } return indices; } template<size_t N> array<Vertex, N / 3 * 2> getWireframeGeometry(const array<Vertex, N> &in) { array<Vertex, N / 3 * 2> out; const uint32_t numTris = N / 3; for (uint32_t i = 0; i < numTris; ++i) { uint32_t j = 0; const uint32_t index = 2 * i; const uint32_t index1 = i * 3 + j; out[index + 0] = in[index1]; const uint32_t index2 = i * 3 + (j + 1) % 3; out[index + 1] = in[index2]; } return out; } template<size_t N> array<Vertex, N> getFuckedUpWireframe(const array<Vertex, N> &in) { array<Vertex, N> out; const uint32_t numTris = N / 3; for (uint32_t i = 0; i < numTris; ++i) { const uint32_t x = 3; const uint32_t index = i * x; for (uint32_t j = 0; j < x; ++j) { out[index + j] = in[i * x + (j % 3)]; } } return out; } const static std::string surfaceShaderCode = R"===( #ifdef GL_ES #extension GL_OES_standard_derivatives : require #endif #define DEMOLOOP_M_PI 3.1459 #ifdef VERTEX vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) { return transform_proj * model * vertpos; } #endif #ifdef PIXEL vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) { vec2 fw = fwidth(tc); float width = max(fw.x, fw.y); vec2 p0 = tc - .5 * width; vec2 p1 = tc + .5 * width; #define BUMPINT(x, d) (floor(x) + (1.0 / (1.0 - (d))) * max((x) - floor(x) - (d), 0.0)) vec2 i = (BUMPINT(p1, 0.85) - BUMPINT(p0, 0.85)) / width; color.rgb *= i.x * 0.25 + i.y * 0.25; // color.rgb *= i.x * i.y + (1.0 - i.x) * (1.0 - i.y); // checkerboard return color; } #endif )==="; // the assumption is that this takes the kind of data you would feed to gl.lines template<size_t N> array<Vertex, N * 3> getLineGeometry(const array<Vertex, N> &in, float halfWidth) { array<Vertex, N * 3> out; const auto& getNormal = [](const glm::vec3& v, float scale) { return glm::vec3(-v.y * scale, v.x * scale, v.z * scale); }; for (uint32_t i = 0; i < N; i+=2) { const glm::vec3& q = *(glm::vec3*)(&in[i + 0]); const glm::vec3& r = *(glm::vec3*)(&in[i + 1]); const glm::vec3 s = r - q; const glm::vec3 ns = getNormal(s, halfWidth / glm::length(s)); const glm::vec3 a = q + ns; const glm::vec3 b = r + ns; const glm::vec3 c = q - ns; const glm::vec3 d = r - ns; // these offsets look a little weird but it's just because we're incrementing by two in the loop memcpy(&out[i * 3 + 0].x, &a.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 1].x, &b.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 2].x, &c.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 3].x, &b.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 4].x, &d.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 5].x, &c.x, sizeof(glm::vec3)); memcpy(&out[i * 3 + 0].r, &in[i + 0].r, sizeof(uint8_t) * 4); memcpy(&out[i * 3 + 1].r, &in[i + 1].r, sizeof(uint8_t) * 4); memcpy(&out[i * 3 + 2].r, &in[i + 0].r, sizeof(uint8_t) * 4); memcpy(&out[i * 3 + 3].r, &in[i + 1].r, sizeof(uint8_t) * 4); memcpy(&out[i * 3 + 4].r, &in[i + 1].r, sizeof(uint8_t) * 4); memcpy(&out[i * 3 + 5].r, &in[i + 0].r, sizeof(uint8_t) * 4); // AB // CD // ns1------ns2 // | | // q ------ r // | | // (-ns1)----(-ns2) // anchors.push_back(q); // anchors.push_back(q); // normals.push_back(ns); // normals.push_back(-ns); // s = (r - q); // len_s = glm::length(s); // ns = glm::vec3(-s.y * (hw / len_s), s.x * (hw / len_s), 0); // anchors.push_back(q); // anchors.push_back(q); // normals.push_back(-ns); // normals.push_back(ns); } return out; } class Loop052 : public Demoloop { public: Loop052() : Demoloop(CYCLE_LENGTH, 1280, 1280, 0, 0, 0), surfaceShader({surfaceShaderCode, surfaceShaderCode}) {} void Update() { const float cycle_ratio = getCycleRatio(); // cycle_ratio = 0; float mx = (static_cast<float>(getMouseX()) / width - 0.5) * 2.0; // mx = cosf(-cycle_ratio * DEMOLOOP_M_PI * 2); float my = (static_cast<float>(getMouseY()) / height - 0.5) * 2.0; // my = sinf(-cycle_ratio * DEMOLOOP_M_PI * 2 * 2); const float eyeMoveFactor = -0.4; const glm::vec3 eye = glm::vec3(mx * eyeMoveFactor, my * eyeMoveFactor, 3); const glm::vec3 up = glm::vec3(0, 1, 0); const glm::vec3 target = glm::vec3(0, 0, farPlane); gl.getTransform() = glm::lookAt(eye, target, up); gl.getProjection() = glm::perspective(static_cast<float>(DEMOLOOP_M_PI) / 4.0f, (float)width / (float)height, 0.1f, farPlane); auto verticesFunction = [cycle_ratio, mx, my](const float u, const float v, const uint32_t slices, const uint32_t stacks) { float z = u * farPlane - fmod(cycle_ratio * farPlane, farPlane / slices); float zr = z / farPlane; float rotation = (v + cycle_ratio) * DEMOLOOP_M_PI * 2 + powf(zr, 2.0) * DEMOLOOP_M_PI * 4.0 * powf(sinf(cycle_ratio * DEMOLOOP_M_PI * 2), 3); float x = cosf(rotation) * powf(1.0 - zr, 3) - mx * 20 * powf(zr, 3); float y = sinf(rotation) * powf(1.0 - zr, 3) - my * 20 * powf(zr, 3); const RGB c = hsl2rgb(zr + cycle_ratio, 1, 0.5); return Vertex(x, y, z, z + cycle_ratio * slices, v * stacks, c.r, c.g, c.b, 255); }; const uint32_t SIDES = 5; auto vertices = parametric<50, SIDES>(verticesFunction); glm::mat4 transform; surfaceShader.attach(); gl.triangles(vertices.data(), vertices.size(), transform); surfaceShader.detach(); // auto wireframe = getWireframeGeometry(vertices); // glLineWidth(5.0); // gl.lines(wireframe.data(), wireframe.size(), transform); { const auto fuckedUpVerts = getFuckedUpWireframe(parametric<5, SIDES>(verticesFunction)); const auto lineVerts = getLineGeometry(fuckedUpVerts, 0.2); gl.triangles(lineVerts.data(), lineVerts.size()); } } private: Shader surfaceShader; MiterJoinPolyline polyline; }; int main(int, char**){ Loop052 test; test.Run(); return 0; }
29.690476
130
0.587677
TannerRogalsky
8af054103b718119b4dea6b6834e861e1d203be6
17,043
cpp
C++
Modules/SceneSerialization/test/mitkSceneIOTestScenarioProvider.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Modules/SceneSerialization/test/mitkSceneIOTestScenarioProvider.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Modules/SceneSerialization/test/mitkSceneIOTestScenarioProvider.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSceneIOTestScenarioProvider.h" #include "mitkPointSet.h" #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkSurface.h" #include "mitkGeometryData.h" #include "mitkProperties.h" #include <vtkPolyData.h> #include <vtkPolygon.h> #include <vtkCellArray.h> namespace { std::string VeryLongText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.Donec a diam lectus.Sed sit amet ipsum mauris.Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit.Donec et mollis dolor.Praesent et diam eget libero egestas mattis sit amet vitae augue.Nam tincidunt congue enim, ut porta lorem lacinia consectetur.Donec ut libero sed arcu vehicula ultricies a non tortor.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Aenean ut gravida lorem.Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.Pellentesque auctor nisi id magna consequat sagittis.Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet.Ut convallis libero in urna ultrices accumsan.Donec sed odio eros.Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus.Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.In rutrum accumsan ultricies.Mauris vitae nisi at sem facilisis semper ac in est.\n" "Vivamus fermentum semper porta.Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio.Maecenas convallis ullamcorper ultricies.Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi.Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis.Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci.Fusce eget orci a orci congue vestibulum.Ut dolor diam, elementum et vestibulum eu, porttitor vel elit.Curabitur venenatis pulvinar tellus gravida ornare.Sed et erat faucibus nunc euismod ultricies ut id justo.Nullam cursus suscipit nisi, et ultrices justo sodales nec.Fusce venenatis facilisis lectus ac semper.Aliquam at massa ipsum.Quisque bibendum purus convallis nulla ultrices ultricies.Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi.Fusce vel volutpat elit.Nam sagittis nisi dui.\r\n" "Suspendisse lectus leo, consectetur in tempor sit amet, placerat quis neque.Etiam luctus porttitor lorem, sed suscipit est rutrum non.Curabitur lobortis nisl a enim congue semper.Aenean commodo ultrices imperdiet.Vestibulum ut justo vel sapien venenatis tincidunt.Phasellus eget dolor sit amet ipsum dapibus condimentum vitae quis lectus.Aliquam ut massa in turpis dapibus convallis.Praesent elit lacus, vestibulum at malesuada et, ornare et est.Ut augue nunc, sodales ut euismod non, adipiscing vitae orci.Mauris ut placerat justo.Mauris in ultricies enim.Quisque nec est eleifend nulla ultrices egestas quis ut quam.Donec sollicitudin lectus a mauris pulvinar id aliquam urna cursus.Cras quis ligula sem, vel elementum mi.Phasellus non ullamcorper urna.\t\n" "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.In euismod ultrices facilisis.Vestibulum porta sapien adipiscing augue congue id pretium lectus molestie.Proin quis dictum nisl.Morbi id quam sapien, sed vestibulum sem.Duis elementum rutrum mauris sed convallis.Proin vestibulum magna mi.Aenean tristique hendrerit magna, ac facilisis nulla hendrerit ut.Sed non tortor sodales quam auctor elementum.Donec hendrerit nunc eget elit pharetra pulvinar.Suspendisse id tempus tortor.Aenean luctus, elit commodo laoreet commodo, justo nisi consequat massa, sed vulputate quam urna quis eros.Donec vel." ; } // --------------- SceneIOTestScenarioProvider::Scenario --------------- mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Scenario::BuildDataStorage() const { return (*m_ScenarioProvider.*m_ProviderMethod)(); // calls function } mitk::SceneIOTestScenarioProvider::Scenario::Scenario(const std::string& _key, const SceneIOTestScenarioProvider* _scenarioProvider, SceneIOTestScenarioProvider::BuilderMethodPointer _providerMethod, bool _isSerializable, const std::string& _referenceArchiveFilename, bool _isReferenceLoadable, double _comparisonPrecision) : key(_key) , serializable(_isSerializable) , referenceArchiveFilename(_referenceArchiveFilename) , referenceArchiveLoadable(_isReferenceLoadable) , comparisonPrecision(_comparisonPrecision) , m_ScenarioProvider(_scenarioProvider) , m_ProviderMethod(_providerMethod) { } // --------------- SceneIOTestScenarioProvider --------------- mitk::SceneIOTestScenarioProvider::ScenarioList mitk::SceneIOTestScenarioProvider::GetAllScenarios() const { return m_Scenarios; } void mitk::SceneIOTestScenarioProvider::AddScenario(const std::string& key, BuilderMethodPointer creator, bool isSerializable, const std::string& referenceArchiveFilename, bool isReferenceLoadable, double comparisonPrecision) { Scenario newScenario(key, this, creator, isSerializable, referenceArchiveFilename, isReferenceLoadable, comparisonPrecision); m_Scenarios.push_back(newScenario); } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::EmptyStorage() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::OneEmptyNode() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); storage->Add(node); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::OneEmptyNamedNode() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Urmel"); storage->Add(node); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::ManyTopLevelNodes() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); for ( auto i = 0; i < m_HowMuchIsMany; ++i ) { mitk::DataNode::Pointer node = DataNode::New(); std::stringstream s; s << "Node #" << i; node->SetName(s.str()); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::LineOfManyOnlyChildren() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer parent; for ( auto i = 0; i < m_HowMuchIsMany; ++i ) { mitk::DataNode::Pointer node = DataNode::New(); std::stringstream s; s << "Node #" << i; node->SetName(s.str()); storage->Add(node, parent); parent = node; } return storage; } #define AddNode(name) \ storage->Add(name); #define DefineNode(name) \ mitk::DataNode::Pointer name = mitk::DataNode::New(); \ name->SetName( #name ); #define DefNode0(name) \ DefineNode(name) \ AddNode(name) #define DefNode1(source, name) \ DefineNode(name) \ storage->Add(name, source); #define DefNode2(source1, source2, name) \ DefineNode(name) \ { mitk::DataStorage::SetOfObjects::Pointer sources = mitk::DataStorage::SetOfObjects::New(); \ sources->push_back(source1); \ sources->push_back(source2); \ storage->Add(name, sources); } #define DefNode3(source1, source2, source3, name) \ DefineNode(name) \ { mitk::DataStorage::SetOfObjects::Pointer sources = mitk::DataStorage::SetOfObjects::New(); \ sources->push_back(source1); \ sources->push_back(source2); \ sources->push_back(source3); \ storage->Add(name, sources); } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::ComplicatedFamilySituation() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); // constructing a hierarchy with multiple levels // and a couple of multiple parent relations. // Anybody, feel free to make this something // meaningful and/or visualize it :-) DefNode0(Color) DefNode0(White) DefNode1(Color, Green) DefNode1(Color, Election) DefNode1(Color, Red) DefNode1(Green, Yellow) DefNode1(Election, Looser) DefNode1(Election, FreeBeer) DefNode1(Election, Winner) DefNode1(Looser, Tears) DefNode1(Looser, Anger) DefNode1(FreeBeer, OpenSource); DefNode1(White, Sweet) DefNode2(White, Sweet, Sugar) DefNode2(Red, Sweet, Tomatoe) DefNode2(Tomatoe, Sugar, Ketchup) DefNode1(Ketchup, BBQSauce) DefNode1(Tomatoe, ATLAS) DefNode0(Fish) DefNode0(OperatingSystem) DefNode1(Fish, Bird) DefNode1(Bird, Penguin) DefNode3(Penguin, OperatingSystem, OpenSource, Linux) return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Image() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // Image of ints mitk::Image::Pointer image3Dints = mitk::ImageGenerator::GenerateRandomImage<int>(10, 5, 7, // dim 1, 0.5, 0.5,// spacing 1, // time steps 3000, -1000); // random max / min mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Image-Int"); node->SetData(image3Dints); storage->Add(node); } { // Image of doubles mitk::Image::Pointer image3Ddouble = mitk::ImageGenerator::GenerateRandomImage<double>(5, 10, 8, // dim 1, 0.5, 0.5,// spacing 2, // time steps 3000, -1000); // random max / min mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Image-Double"); node->SetData(image3Ddouble); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Surface() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // Surface vtkSmartPointer<vtkPoints> points1 = vtkSmartPointer<vtkPoints>::New(); points1->InsertNextPoint(0.0, 0.0, 0.0); points1->InsertNextPoint(1.0, 0.0, 0.0); points1->InsertNextPoint(0.0, 1.0, 0.0); points1->InsertNextPoint(1.0, 1.0, 0.0); vtkSmartPointer<vtkPolygon> polygon1 = vtkSmartPointer<vtkPolygon>::New(); polygon1->GetPointIds()->SetNumberOfIds(4); polygon1->GetPointIds()->SetId(0, 0); polygon1->GetPointIds()->SetId(1, 1); polygon1->GetPointIds()->SetId(2, 2); polygon1->GetPointIds()->SetId(3, 3); vtkSmartPointer<vtkPolygon> polygon2 = vtkSmartPointer<vtkPolygon>::New(); polygon2->GetPointIds()->SetNumberOfIds(4); polygon2->GetPointIds()->SetId(0, 3); polygon2->GetPointIds()->SetId(1, 2); polygon2->GetPointIds()->SetId(2, 0); polygon2->GetPointIds()->SetId(3, 1); //generate polydatas vtkSmartPointer<vtkCellArray> polygonArray1 = vtkSmartPointer<vtkCellArray>::New(); polygonArray1->InsertNextCell(polygon1); vtkSmartPointer<vtkPolyData> polydata1 = vtkSmartPointer<vtkPolyData>::New(); polydata1->SetPoints(points1); polydata1->SetPolys(polygonArray1); vtkSmartPointer<vtkCellArray> polygonArray2 = vtkSmartPointer<vtkCellArray>::New(); polygonArray2->InsertNextCell(polygon2); vtkSmartPointer<vtkPolyData> polyDataTwo = vtkSmartPointer<vtkPolyData>::New(); polyDataTwo->SetPoints(points1); polyDataTwo->SetPolys(polygonArray2); //generate surfaces mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(polydata1); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Surface"); node->SetData(surface); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::PointSet() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // PointSet mitk::PointSet::Pointer ps = mitk::PointSet::New(); mitk::PointSet::PointType p; mitk::FillVector3D(p, 1.0, -2.0, 33.0); ps->SetPoint(0, p); mitk::FillVector3D(p, 100.0, -200.0, 3300.0); ps->SetPoint(1, p); mitk::FillVector3D(p, 2.0, -3.0, 22.0); ps->SetPoint(2, p, mitk::PTCORNER); // add point spec mitk::DataNode::Pointer node = DataNode::New(); node->SetName("PointSet"); node->SetData(ps); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::GeometryData() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // GeometryData mitk::GeometryData::Pointer gdata = mitk::GeometryData::New(); // define Geometry3D parameters mitk::AffineTransform3D::MatrixType matrix; matrix[0][0] = 1.1; matrix[1][1] = 2.2; matrix[2][2] = 3.3; mitk::AffineTransform3D::OffsetType offset; mitk::FillVector3D(offset, 0.1, 0.2, 0.3); bool isImageGeometry(false); unsigned int frameOfReferenceID(47); mitk::BaseGeometry::BoundsArrayType bounds; bounds[0] = std::numeric_limits<mitk::ScalarType>::min(); bounds[1] = -52.723; bounds[2] = -0.002; bounds[3] = 918273645.18293746; bounds[4] = -0.002; bounds[5] = +52.723; mitk::Point3D origin; mitk::FillVector3D(origin, 5.1, 5.2, 5.3); mitk::Vector3D spacing; mitk::FillVector3D(spacing, 2.1, 2.2, 2.3); // build GeometryData from matrix/offset/etc. mitk::AffineTransform3D::Pointer newTransform = mitk::AffineTransform3D::New(); newTransform->SetMatrix(matrix); newTransform->SetOffset(offset); mitk::Geometry3D::Pointer newGeometry = mitk::Geometry3D::New(); newGeometry->SetFrameOfReferenceID(frameOfReferenceID); newGeometry->SetImageGeometry(isImageGeometry); newGeometry->SetIndexToWorldTransform(newTransform); newGeometry->SetBounds(bounds); newGeometry->SetOrigin(origin); newGeometry->SetSpacing(spacing); mitk::GeometryData::Pointer geometryData = mitk::GeometryData::New(); geometryData->SetGeometry(newGeometry); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("GeometryData"); node->SetData(geometryData); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::SpecialProperties() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Camion"); node->SetProperty("", StringProperty::New("Colis")); // no name! node->SetProperty("Livre", StringProperty::New( VeryLongText ) ); // defined at the top of this file node->SetProperty(VeryLongText.c_str(), StringProperty::New( "Shorty" ) ); node->GetPropertyList("Chapitre1")->SetProperty("Page 1", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre1")->SetProperty("Page 2", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre 2")->SetProperty("Page", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre 3")->SetProperty("Page", StringProperty::New( VeryLongText )); node->GetPropertyList(VeryLongText)->SetProperty("Page", StringProperty::New( VeryLongText )); // not working (NaN etc.) //node->SetProperty("NotAFloat", FloatProperty::New( sqrt(-1.0) ) ); node->SetProperty("sqrt(2)", FloatProperty::New( -sqrt(2.0) ) ); node->SetProperty("sqrt(3)", FloatProperty::New( sqrt(3.0) ) ); // most values work fine, just min/max double produces serialization precision errors node->SetProperty("sqrt(4)", DoubleProperty::New( -sqrt(4.0) ) ); node->SetProperty("sqrt(5)", DoubleProperty::New( sqrt(5.0) ) ); //node->SetProperty("maxd", DoubleProperty::New( std::numeric_limits<double>::max() ) ); node->SetProperty("zero", DoubleProperty::New( 0.0 ) ); node->SetProperty("minzero", DoubleProperty::New( -0.0 ) ); //node->SetProperty("mind", DoubleProperty::New( std::numeric_limits<double>::min() ) ); storage->Add(node); return storage; }
40.007042
965
0.6953
samsmu
8af1561af9e4085c4abdb54a0a4f9d0ba13adb92
5,360
cxx
C++
source/Tools/DownsampleDeformations3D.cxx
tobiasgass/ETH-SegReg
6d908a91ad49cc42ffc74a1c00a16fad61016f51
[ "BSD-2-Clause-FreeBSD" ]
15
2015-04-15T06:49:06.000Z
2021-09-01T09:09:50.000Z
source/Tools/DownsampleDeformations3D.cxx
tobiasgass/ETH-SegReg
6d908a91ad49cc42ffc74a1c00a16fad61016f51
[ "BSD-2-Clause-FreeBSD" ]
14
2015-03-09T19:09:47.000Z
2015-09-04T15:31:12.000Z
source/Tools/DownsampleDeformations3D.cxx
tobiasgass/ETH-SegReg
6d908a91ad49cc42ffc74a1c00a16fad61016f51
[ "BSD-2-Clause-FreeBSD" ]
10
2015-04-08T09:17:44.000Z
2017-08-12T17:30:15.000Z
#include "Log.h" #include <stdio.h> #include <iostream> #include "ArgumentParser.h" #include "ImageUtils.h" #include <itkWarpImageFilter.h> #include "TransformationUtils.h" using namespace std; using namespace itk; int main(int argc, char ** argv) { feraiseexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW); typedef short PixelType; const unsigned int D=3; typedef Image<PixelType,D> ImageType; typedef ImageType::Pointer ImagePointerType; typedef ImageType::ConstPointer ImageConstPointerType; typedef Vector<double,D> LabelType; typedef Image<LabelType,D> LabelImageType; typedef LabelImageType::Pointer LabelImagePointerType; typedef ImageType::IndexType IndexType; LabelImagePointerType deformation1 = ImageUtils<LabelImageType>::readImage(argv[1]); double resamplingFactor=atof(argv[2]); ImagePointerType refImage=TransfUtils<ImageType,double,double,double>::createEmptyImage(deformation1); ImagePointerType refImageLowRes=FilterUtils<ImageType>::LinearResample(refImage,resamplingFactor,false); if (0){ LabelImagePointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::computeBSplineTransformFromDeformationField(deformation1,refImageLowRes) ; LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::computeDeformationFieldFromBSplineTransform(lowResDeformation,refImage) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"BsplineConversion :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } if (0){ typedef TransfUtils<ImageType,double,double,double>::BSplineTransformPointerType BSplineTransformPointerType; BSplineTransformPointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::computeITKBSplineTransformFromDeformationField(deformation1,refImageLowRes) ; ImagePointerType fixedImage=ImageUtils<ImageType>::readImage(argv[4]); ImagePointerType movingImage=ImageUtils<ImageType>::readImage(argv[5]); ImageUtils<ImageType>::writeImage("warped.nii",TransfUtils<ImageType,double,double,double>::deformImage(movingImage,fixedImage,lowResDeformation)); LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::computeDeformationFieldFromITKBSplineTransform(lowResDeformation,refImage) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"ITKBsplineConversion :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } if (1){ LabelImagePointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::bSplineInterpolateDeformationField(deformation1,refImageLowRes,false) ; LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::bSplineInterpolateDeformationField(lowResDeformation,refImage,false) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"BsplineResampling (without smoothing) :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } if (1){ LabelImagePointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::bSplineInterpolateDeformationField(deformation1,refImageLowRes,true) ; LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::bSplineInterpolateDeformationField(lowResDeformation,refImage,true) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"BsplineResampling (with smoothing) :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } if (1){ LabelImagePointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::linearInterpolateDeformationField(deformation1,refImageLowRes,false) ; LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::linearInterpolateDeformationField(lowResDeformation,refImage,false) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"linear resampling (without smoothing) :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } if (1){ LabelImagePointerType lowResDeformation= TransfUtils<ImageType,double,double,double>::linearInterpolateDeformationField(deformation1,refImageLowRes,true) ; LabelImagePointerType highResDeformation= TransfUtils<ImageType,double,double,double>::linearInterpolateDeformationField(lowResDeformation,refImage,true) ; LabelImagePointerType difference=TransfUtils<ImageType,double,double,double>::subtract(deformation1,highResDeformation); LOG<<"linear resampling (with smoothing) :"<<TransfUtils<ImageType,double,double,double>::computeDeformationNorm(difference)<<endl; } //ImageUtils<LabelImageType>::writeImage(argv[3],lowResDeformation); LOG<<"deformed image "<<argv[1]<<endl; return 1; }
60.224719
177
0.793097
tobiasgass
8af1a59e746d100a7029a722b971de0a5986f12a
290
inl
C++
LiberoEngine/src/Entity.inl
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
LiberoEngine/src/Entity.inl
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
LiberoEngine/src/Entity.inl
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
#pragma once #include "Entity.h" namespace Libero { template<class Type> inline const EntityTypeID Entity<Type>::GetStaticTypeID() const { return m_Stat_TypeID; } template<class Type> inline const EntityTypeID Entity<Type>::StaticGetStaticTypeID() { return m_Stat_TypeID; } }
16.111111
64
0.751724
Kair0z
8af3ef805efa749ddad0fb061216639c2a943e95
6,632
cpp
C++
Marlin/src/HAL/AVR/fastio.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/HAL/AVR/fastio.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/HAL/AVR/fastio.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Fast I/O for extended pins */ #ifdef __AVR__ #include "fastio.h" #ifdef FASTIO_EXT_START #include "../shared/Marduino.h" #define _IS_EXT(P) WITHIN(P, FASTIO_EXT_START, FASTIO_EXT_END) void extDigitalWrite(const int8_t pin, const uint8_t state) { #define _WCASE(N) case N: WRITE(N, state); break switch (pin) { default: digitalWrite(pin, state); #if _IS_EXT(70) _WCASE(70); #endif #if _IS_EXT(71) _WCASE(71); #endif #if _IS_EXT(72) _WCASE(72); #endif #if _IS_EXT(73) _WCASE(73); #endif #if _IS_EXT(74) _WCASE(74); #endif #if _IS_EXT(75) _WCASE(75); #endif #if _IS_EXT(76) _WCASE(76); #endif #if _IS_EXT(77) _WCASE(77); #endif #if _IS_EXT(78) _WCASE(78); #endif #if _IS_EXT(79) _WCASE(79); #endif #if _IS_EXT(80) _WCASE(80); #endif #if _IS_EXT(81) _WCASE(81); #endif #if _IS_EXT(82) _WCASE(82); #endif #if _IS_EXT(83) _WCASE(83); #endif #if _IS_EXT(84) _WCASE(84); #endif #if _IS_EXT(85) _WCASE(85); #endif #if _IS_EXT(86) _WCASE(86); #endif #if _IS_EXT(87) _WCASE(87); #endif #if _IS_EXT(88) _WCASE(88); #endif #if _IS_EXT(89) _WCASE(89); #endif #if _IS_EXT(90) _WCASE(90); #endif #if _IS_EXT(91) _WCASE(91); #endif #if _IS_EXT(92) _WCASE(92); #endif #if _IS_EXT(93) _WCASE(93); #endif #if _IS_EXT(94) _WCASE(94); #endif #if _IS_EXT(95) _WCASE(95); #endif #if _IS_EXT(96) _WCASE(96); #endif #if _IS_EXT(97) _WCASE(97); #endif #if _IS_EXT(98) _WCASE(98); #endif #if _IS_EXT(99) _WCASE(99); #endif #if _IS_EXT(100) _WCASE(100); #endif } } uint8_t extDigitalRead(const int8_t pin) { #define _RCASE(N) case N: return READ(N) switch (pin) { default: return digitalRead(pin); #if _IS_EXT(70) _RCASE(70); #endif #if _IS_EXT(71) _RCASE(71); #endif #if _IS_EXT(72) _RCASE(72); #endif #if _IS_EXT(73) _RCASE(73); #endif #if _IS_EXT(74) _RCASE(74); #endif #if _IS_EXT(75) _RCASE(75); #endif #if _IS_EXT(76) _RCASE(76); #endif #if _IS_EXT(77) _RCASE(77); #endif #if _IS_EXT(78) _RCASE(78); #endif #if _IS_EXT(79) _RCASE(79); #endif #if _IS_EXT(80) _RCASE(80); #endif #if _IS_EXT(81) _RCASE(81); #endif #if _IS_EXT(82) _RCASE(82); #endif #if _IS_EXT(83) _RCASE(83); #endif #if _IS_EXT(84) _RCASE(84); #endif #if _IS_EXT(85) _RCASE(85); #endif #if _IS_EXT(86) _RCASE(86); #endif #if _IS_EXT(87) _RCASE(87); #endif #if _IS_EXT(88) _RCASE(88); #endif #if _IS_EXT(89) _RCASE(89); #endif #if _IS_EXT(90) _RCASE(90); #endif #if _IS_EXT(91) _RCASE(91); #endif #if _IS_EXT(92) _RCASE(92); #endif #if _IS_EXT(93) _RCASE(93); #endif #if _IS_EXT(94) _RCASE(94); #endif #if _IS_EXT(95) _RCASE(95); #endif #if _IS_EXT(96) _RCASE(96); #endif #if _IS_EXT(97) _RCASE(97); #endif #if _IS_EXT(98) _RCASE(98); #endif #if _IS_EXT(99) _RCASE(99); #endif #if _IS_EXT(100) _RCASE(100); #endif } } #if 0 /** * Set Timer 5 PWM frequency in Hz, from 3.8Hz up to ~16MHz * with a minimum resolution of 100 steps. * * DC values -1.0 to 1.0. Negative duty cycle inverts the pulse. */ uint16_t set_pwm_frequency_hz(const_float_t hz, const float dca, const float dcb, const float dcc) { float count = 0; if (hz > 0 && (dca || dcb || dcc)) { count = float(F_CPU) / hz; // 1x prescaler, TOP for 16MHz base freq. uint16_t prescaler; // Range of 30.5Hz (65535) 64.5KHz (>31) if (count >= 255. * 256.) { prescaler = 1024; SET_CS(5, PRESCALER_1024); } else if (count >= 255. * 64.) { prescaler = 256; SET_CS(5, PRESCALER_256); } else if (count >= 255. * 8.) { prescaler = 64; SET_CS(5, PRESCALER_64); } else if (count >= 255.) { prescaler = 8; SET_CS(5, PRESCALER_8); } else { prescaler = 1; SET_CS(5, PRESCALER_1); } count /= float(prescaler); const float pwm_top = round(count); // Get the rounded count ICR5 = (uint16_t)pwm_top - 1; // Subtract 1 for TOP OCR5A = pwm_top * ABS(dca); // Update and scale DCs OCR5B = pwm_top * ABS(dcb); OCR5C = pwm_top * ABS(dcc); _SET_COM(5, A, dca ? (dca < 0 ? COM_SET_CLEAR : COM_CLEAR_SET) : COM_NORMAL); // Set compare modes _SET_COM(5, B, dcb ? (dcb < 0 ? COM_SET_CLEAR : COM_CLEAR_SET) : COM_NORMAL); _SET_COM(5, C, dcc ? (dcc < 0 ? COM_SET_CLEAR : COM_CLEAR_SET) : COM_NORMAL); SET_WGM(5, FAST_PWM_ICRn); // Fast PWM with ICR5 as TOP //SERIAL_ECHOLNPGM("Timer 5 Settings:"); //SERIAL_ECHOLNPGM(" Prescaler=", prescaler); //SERIAL_ECHOLNPGM(" TOP=", ICR5); //SERIAL_ECHOLNPGM(" OCR5A=", OCR5A); //SERIAL_ECHOLNPGM(" OCR5B=", OCR5B); //SERIAL_ECHOLNPGM(" OCR5C=", OCR5C); } else { // Restore the default for Timer 5 SET_WGM(5, PWM_PC_8); // PWM 8-bit (Phase Correct) SET_COMS(5, NORMAL, NORMAL, NORMAL); // Do nothing SET_CS(5, PRESCALER_64); // 16MHz / 64 = 250KHz OCR5A = OCR5B = OCR5C = 0; } return round(count); } #endif #endif // FASTIO_EXT_START #endif // __AVR__
22.948097
102
0.569059
tom-2273
8af7b7452f9e0db153f823174a512a8879eafd75
3,225
cpp
C++
GAG/test/CompositionTest.cpp
hh1985/multi_hs_seq
9cf4e70fb59283da30339499952c43a0684f7e77
[ "Apache-2.0" ]
2
2015-04-03T14:44:45.000Z
2015-04-15T13:38:39.000Z
GAG/test/CompositionTest.cpp
hh1985/multi_hs_seq
9cf4e70fb59283da30339499952c43a0684f7e77
[ "Apache-2.0" ]
null
null
null
GAG/test/CompositionTest.cpp
hh1985/multi_hs_seq
9cf4e70fb59283da30339499952c43a0684f7e77
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: CompositionTest.cpp * * Description: Test file for class Composition. * * Version: 1.0 * Created: 04/28/2012 12:26:57 AM * Revision: none * Compiler: msvc * * Author: Han Hu (HH), hh.earlydays@gmail.com * Organization: Boston University * * ===================================================================================== */ #include <GAGPL/CHEMISTRY/Composition.h> #include <iostream> int main ( int argc, char *argv[] ) { using namespace gag; // The Periodic Table should be loaded at least once; PeriodicTable& pt = PeriodicTable::Instance(); //pt.load(); /* Set composition. */ Composition cp("C7H20OHCl3"); const std::map<std::string, int>& cp_map = cp.get(); for(std::map<std::string, int>::const_iterator iter = cp_map.begin(); iter != cp_map.end(); iter++) { std::cout << iter->first << " " << iter->second << std::endl; } std::cout << "Mass: " << cp.getMass() << std::endl; std::cout << "size is: " << cp.getCompositionString().length() << std::endl; /* Add composition. */ cp.add("CCa2"); std::cout << "String: " << cp.getCompositionString() << std::endl; //cp_map = cp.get(); for(std::map<std::string, int>::const_iterator iter = cp_map.begin(); iter != cp_map.end(); iter++) { std::cout << iter->first << " " << iter->second << std::endl; } std::cout << "Mass: " << cp.getMass() << std::endl; std::cout << "size is: " << cp.getCompositionString().length() << std::endl; /* Substract composition */ cp.deduct("COH"); std::cout << "String: " << cp.getCompositionString() << std::endl; //cp_map = cp.get(); for(std::map<std::string, int>::const_iterator iter = cp_map.begin(); iter != cp_map.end(); iter++) { std::cout << iter->first << " " << iter->second << std::endl; } std::cout << "Mass: " << cp.getMass() << std::endl; std::cout << "size is: " << cp.getCompositionString().length() << std::endl; /* Assignment */ Composition cm = cp; std::cout << "CP String: " << cp.getCompositionString() << std::endl; const std::map<std::string, int>& cm_map = cm.get(); for(std::map<std::string, int>::const_iterator iter = cp_map.begin(); iter != cp_map.end(); iter++) { std::cout << iter->first << " " << iter->second << std::endl; } std::cout << "CP Mass: " << cp.getMass() << std::endl; std::cout << "CP size is: " << cp.getCompositionString().length() << std::endl; /* clear */ cp.clear(); std::cout << "After clear, size is: " << cp.getCompositionString().length() << std::endl; std::cout << "**************************************" << std::endl; std::cout << " Test 2: Comparison " << std::endl; std::cout << "**************************************" << std::endl; Composition comp0("C3HO3"); Composition comp1("H2O"); std::cout << "Compare" << comp0.getCompositionString() << " and " << comp1.getCompositionString() << std::endl; std::cout << "Results: "; if(comp1 < comp0) std::cout << "smaller" << std::endl; else std::cout << "larger" << std::endl; return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
32.25
112
0.537984
hh1985
8af8f6bd53bb9dfa652e6270d81024d0437f5fd8
394
cpp
C++
eclide/TabPane.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
8
2016-08-29T13:34:18.000Z
2020-12-04T15:20:36.000Z
eclide/TabPane.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
221
2016-06-20T19:51:48.000Z
2022-03-29T20:46:46.000Z
eclide/TabPane.cpp
dehilsterlexis/eclide-1
0c1685cc7165191b5033d450c59aec479f01010a
[ "Apache-2.0" ]
13
2016-06-24T15:59:31.000Z
2022-01-01T11:48:20.000Z
#include "StdAfx.h" #include "TabPane.h" void CTabPane::SetNamePath(const CString & sPathName) { CString pathName = sPathName; TCHAR szTitle [_MAX_FNAME], szExt[_MAX_FNAME]; _tsplitpath(pathName.GetBuffer(_MAX_PATH), NULL, NULL, szTitle, szExt); pathName.ReleaseBuffer(); lstrcat(szTitle, szExt); m_path = sPathName; if (szTitle) m_name = szTitle; }
23.176471
75
0.680203
dehilsterlexis
8afe2acb8caceeb56a0db2bc1d470d2f81d97d8a
18,158
hpp
C++
Drivers/InpaintingWithVerification.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
39
2015-01-01T07:59:51.000Z
2021-10-01T18:11:46.000Z
Drivers/InpaintingWithVerification.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
1
2019-04-24T09:56:15.000Z
2019-04-24T14:45:46.000Z
Drivers/InpaintingWithVerification.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
18
2015-01-11T15:10:23.000Z
2022-02-24T20:02:10.000Z
/*========================================================================= * * Copyright David Doria 2012 daviddoria@gmail.com * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef InpaintingWithVerification_HPP #define InpaintingWithVerification_HPP // Custom #include "Utilities/IndirectPriorityQueue.h" // Submodules #include <Helpers/Helpers.h> // Pixel descriptors #include "PixelDescriptors/ImagePatchPixelDescriptor.h" // Descriptor visitors #include "Visitors/DescriptorVisitors/ImagePatchDescriptorVisitor.hpp" #include "Visitors/DescriptorVisitors/CompositeDescriptorVisitor.hpp" // Nearest neighbors visitor #include "Visitors/NearestNeighborsDisplayVisitor.hpp" // Nearest neighbors #include "NearestNeighbor/LinearSearchKNNProperty.hpp" #include "NearestNeighbor/DefaultSearchBest.hpp" #include "NearestNeighbor/LinearSearchBest/Property.hpp" #include "NearestNeighbor/VisualSelectionBest.hpp" #include "NearestNeighbor/FirstValidDescriptor.hpp" // Pixel descriptors #include "PixelDescriptors/ImagePatchPixelDescriptor.h" #include "PixelDescriptors/ImagePatchVectorized.h" #include "PixelDescriptors/ImagePatchVectorizedIndices.h" // Acceptance visitors #include "Visitors/AcceptanceVisitors/AverageDifferenceAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/CompositeAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/ANDAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/DilatedSourceHoleTargetValidAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/DilatedSourceValidTargetValidAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/SourceHoleTargetValidCompare.hpp" #include "Visitors/AcceptanceVisitors/SourceValidTargetValidCompare.hpp" #include "Visitors/AcceptanceVisitors/HoleSizeAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/VarianceFunctor.hpp" #include "Visitors/AcceptanceVisitors/AverageFunctor.hpp" #include "Visitors/AcceptanceVisitors/ScoreThresholdAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/CorrelationAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/PatchDistanceAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/HistogramDifferenceAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/HoleHistogramDifferenceAcceptanceVisitor.hpp" // #include "Visitors/AcceptanceVisitors/QuadrantHistogramCompareAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/AllQuadrantHistogramCompareAcceptanceVisitor.hpp" //#include "Visitors/AcceptanceVisitors/IntraSourcePatchAcceptanceVisitor.hpp" #include "Visitors/AcceptanceVisitors/NeverAccept.hpp" // Information visitors #include "Visitors/InformationVisitors/DisplayVisitor.hpp" // Inpainting visitors #include "Visitors/InpaintingVisitor.hpp" #include "Visitors/AcceptanceVisitors/DefaultAcceptanceVisitor.hpp" #include "Visitors/InpaintingVisitor.hpp" #include "Visitors/ReplayVisitor.hpp" #include "Visitors/InformationVisitors/LoggerVisitor.hpp" #include "Visitors/CompositeInpaintingVisitor.hpp" #include "Visitors/InformationVisitors/DebugVisitor.hpp" // Nearest neighbors #include "NearestNeighbor/LinearSearchBest/Property.hpp" // Initializers #include "Initializers/InitializeFromMaskImage.hpp" #include "Initializers/InitializePriority.hpp" // Inpainters #include "Inpainters/CompositePatchInpainter.hpp" #include "Inpainters/PatchInpainter.hpp" // Difference functions #include "DifferenceFunctions/ImagePatchDifference.hpp" #include "DifferenceFunctions/SumAbsolutePixelDifference.hpp" #include "DifferenceFunctions/SumSquaredPixelDifference.hpp" // Utilities #include "Utilities/PatchHelpers.h" // Inpainting #include "Algorithms/InpaintingAlgorithmWithVerification.hpp" // Priority #include "Priority/PriorityCriminisi.h" // Boost #include <boost/graph/grid_graph.hpp> #include <boost/property_map/property_map.hpp> // GUI #include "Interactive/BasicViewerWidget.h" #include "Interactive/TopPatchesWidget.h" #include "Interactive/TopPatchesDialog.h" #include "Interactive/PriorityViewerWidget.h" template <typename TImage> void InpaintingWithVerification(TImage* const originalImage, Mask* const mask, const unsigned int patchHalfWidth) { itk::ImageRegion<2> fullRegion = originalImage->GetLargestPossibleRegion(); // Blur the image typedef TImage BlurredImageType; // Usually the blurred image is the same type as the original image. typename BlurredImageType::Pointer blurredImage = BlurredImageType::New(); float blurVariance = 2.0f; MaskOperations::MaskedBlur(originalImage, mask, blurVariance, blurredImage.GetPointer()); ITKHelpers::WriteRGBImage(blurredImage.GetPointer(), "BlurredImage.png"); typedef ImagePatchPixelDescriptor<TImage> ImagePatchPixelDescriptorType; // Create the graph typedef boost::grid_graph<2> VertexListGraphType; boost::array<std::size_t, 2> graphSideLengths = { { fullRegion.GetSize()[0], fullRegion.GetSize()[1] } }; VertexListGraphType graph(graphSideLengths); typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType; // Get the index map typedef boost::property_map<VertexListGraphType, boost::vertex_index_t>::const_type IndexMapType; IndexMapType indexMap(get(boost::vertex_index, graph)); // Create the priority map typedef boost::vector_property_map<float, IndexMapType> PriorityMapType; PriorityMapType priorityMap(num_vertices(graph), indexMap); // Create the boundary status map. A node is on the current boundary if this property is true. // This property helps the boundaryNodeQueue because we can mark here if a node has become no longer // part of the boundary, so when the queue is popped we can check this property to see if it should // actually be processed. typedef boost::vector_property_map<bool, IndexMapType> BoundaryStatusMapType; BoundaryStatusMapType boundaryStatusMap(num_vertices(graph), indexMap); // Create the descriptor map. This is where the data for each pixel is stored. typedef boost::vector_property_map<ImagePatchPixelDescriptorType, IndexMapType> ImagePatchDescriptorMapType; ImagePatchDescriptorMapType imagePatchDescriptorMap(num_vertices(graph), indexMap); //ImagePatchDescriptorMapType smallImagePatchDescriptorMap(num_vertices(graph), indexMap); // Create the patch inpainter. typedef PatchInpainter<TImage> OriginalImageInpainterType; OriginalImageInpainterType originalImageInpainter(patchHalfWidth, originalImage, mask); typedef PatchInpainter<BlurredImageType> BlurredImageInpainterType; BlurredImageInpainterType blurredImageInpainter(patchHalfWidth, originalImage, mask); // Create a composite inpainter. CompositePatchInpainter inpainter; inpainter.AddInpainter(&originalImageInpainter); inpainter.AddInpainter(&blurredImageInpainter); // Create the priority function // typedef PriorityRandom PriorityType; // PriorityType priorityFunction; typedef PriorityCriminisi<TImage> PriorityType; PriorityType priorityFunction(blurredImage, mask, patchHalfWidth); // Queue typedef IndirectPriorityQueue<VertexListGraphType> BoundaryNodeQueueType; BoundaryNodeQueueType boundaryNodeQueue(graph); // Create the descriptor visitor typedef ImagePatchDescriptorVisitor<VertexListGraphType, TImage, ImagePatchDescriptorMapType> ImagePatchDescriptorVisitorType; ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(originalImage, mask, imagePatchDescriptorMap, patchHalfWidth); typedef SumSquaredPixelDifference<typename TImage::PixelType> PixelDifferenceType; typedef ImagePatchDifference<ImagePatchPixelDescriptorType, PixelDifferenceType > ImagePatchDifferenceType; typedef CompositeDescriptorVisitor<VertexListGraphType> CompositeDescriptorVisitorType; CompositeDescriptorVisitorType compositeDescriptorVisitor; compositeDescriptorVisitor.AddVisitor(&imagePatchDescriptorVisitor); typedef CompositeAcceptanceVisitor<VertexListGraphType> CompositeAcceptanceVisitorType; CompositeAcceptanceVisitorType compositeAcceptanceVisitor; // typedef ANDAcceptanceVisitor<VertexListGraphType> CompositeAcceptanceVisitorType; // CompositeAcceptanceVisitorType compositeAcceptanceVisitor; // Source region to source region comparisons // SourceValidTargetValidCompare<VertexListGraphType, TImage, AverageFunctor> // validRegionAverageAcceptance(image, mask, patchHalfWidth, // AverageFunctor(), 100, "validRegionAverageAcceptance"); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&validRegionAverageAcceptance); // We don't want to do this - the variation over the patch makes this no good. // Prefer the DilatedRegionAcceptanceVisitor with a VarianceFunctor instead. // SourceValidTargetValidCompare<VertexListGraphType, TImage, VarianceFunctor> // validRegionVarianceAcceptance(image, mask, patchHalfWidth, // VarianceFunctor(), 1000, "validRegionVarianceAcceptance"); // compositeAcceptanceVisitor.AddVisitor(&validRegionVarianceAcceptance); // If the hole is less than 15% of the patch, always accept the initial best match HoleSizeAcceptanceVisitor<VertexListGraphType> holeSizeAcceptanceVisitor(mask, patchHalfWidth, .15); compositeAcceptanceVisitor.AddOverrideVisitor(&holeSizeAcceptanceVisitor); // HistogramDifferenceAcceptanceVisitor<VertexListGraphType, TImage> // histogramDifferenceAcceptanceVisitor(image, mask, patchHalfWidth, 2.0f); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&histogramDifferenceAcceptanceVisitor); // // HoleHistogramDifferenceAcceptanceVisitor<VertexListGraphType, TImage> // holeHistogramDifferenceAcceptanceVisitor(image, mask, patchHalfWidth, 2.0f); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&holeHistogramDifferenceAcceptanceVisitor); // QuadrantHistogramCompareAcceptanceVisitor<VertexListGraphType, TImage> // quadrantHistogramCompareAcceptanceVisitor(image, mask, patchHalfWidth, 2.0f); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&quadrantHistogramCompareAcceptanceVisitor); // AllQuadrantHistogramCompareAcceptanceVisitor<VertexListGraphType, TImage> // allQuadrantHistogramCompareAcceptanceVisitor(image, mask, patchHalfWidth, 8.0f); // 8 (2 for each quadrant) is reasonable // AllQuadrantHistogramCompareAcceptanceVisitor<VertexListGraphType, TImage> // allQuadrantHistogramCompareAcceptanceVisitor(image, mask, patchHalfWidth, 1.0f); // Crazy low // compositeAcceptanceVisitor.AddRequiredPassVisitor(&allQuadrantHistogramCompareAcceptanceVisitor); // ScoreThresholdAcceptanceVisitor<VertexListGraphType, ImagePatchDescriptorMapType, // ImagePatchDifferenceType> scoreThresholdAcceptanceVisitor(mask, patchHalfWidth, // imagePatchDescriptorMap, 10); // compositeAcceptanceVisitor.AddOverrideVisitor(&scoreThresholdAcceptanceVisitor); // Source region to hole region comparisons // SourceHoleTargetValidCompare<VertexListGraphType, TImage, AverageFunctor> // holeRegionAverageAcceptance(image, mask, patchHalfWidth, // AverageFunctor(), 100, "holeRegionAverageAcceptance"); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&holeRegionAverageAcceptance); // SourceHoleTargetValidCompare<VertexListGraphType, TImage, VarianceFunctor> // holeRegionVarianceAcceptance(image, mask, patchHalfWidth, // VarianceFunctor(), 1000, "holeRegionVarianceAcceptance"); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&holeRegionVarianceAcceptance); // Compare the source region variance in the target patch to the source region variance in the source patch // DilatedSourceValidTargetValidAcceptanceVisitor<VertexListGraphType, TImage, VarianceFunctor> // dilatedValidValidVarianceDifferenceAcceptanceVisitor(image, mask, patchHalfWidth, // VarianceFunctor(), 1000, // "dilatedVarianceDifferenceAcceptanceVisitor"); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&dilatedValidValidVarianceDifferenceAcceptanceVisitor); // Compare the hole variance to the source region variance // DilatedSourceHoleTargetValidAcceptanceVisitor<VertexListGraphType, TImage, VarianceFunctor> // dilatedHoleValidVarianceDifferenceAcceptanceVisitor(image, mask, patchHalfWidth, // VarianceFunctor(), 1000, // "dilatedHoleValidVarianceDifferenceAcceptanceVisitor"); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&dilatedHoleValidVarianceDifferenceAcceptanceVisitor); // PatchDistanceAcceptanceVisitor<VertexListGraphType> patchDistanceAcceptanceVisitor(100); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&patchDistanceAcceptanceVisitor); // CorrelationAcceptanceVisitor<VertexListGraphType, TImage> correlationAcceptanceVisitor(image, mask, patchHalfWidth, 100); // compositeAcceptanceVisitor.AddRequiredPassVisitor(&correlationAcceptanceVisitor); // IntraSourcePatchAcceptanceVisitor<VertexListGraphType, TImage> // intraSourcePatchAcceptanceVisitor(image, mask, patchHalfWidth, 100); // compositeAcceptanceVisitor.AddVisitor(&intraSourcePatchAcceptanceVisitor); // Create the inpainting visitor // typedef InpaintingVisitor<VertexListGraphType, TImage, BoundaryNodeQueueType, // ImagePatchDescriptorVisitorType, AcceptanceVisitorType, // PriorityType, PriorityMapType, BoundaryStatusMapType> // InpaintingVisitorType; // InpaintingVisitorType inpaintingVisitor(image, mask, boundaryNodeQueue, // imagePatchDescriptorVisitor, compositeAcceptanceVisitor, // priorityMap, &priorityFunction, patchHalfWidth, // boundaryStatusMap); typedef InpaintingVisitor<VertexListGraphType, BoundaryNodeQueueType, CompositeDescriptorVisitorType, CompositeAcceptanceVisitorType, PriorityType, TImage> InpaintingVisitorType; InpaintingVisitorType inpaintingVisitor(mask, boundaryNodeQueue, compositeDescriptorVisitor, compositeAcceptanceVisitor, &priorityFunction, patchHalfWidth, "InpaintingVisitor", originalImage); // typedef DisplayVisitor<VertexListGraphType, TImage> DisplayVisitorType; // DisplayVisitorType displayVisitor(image, mask, patchHalfWidth); // typedef DebugVisitor<VertexListGraphType, TImage, BoundaryStatusMapType, BoundaryNodeQueueType> DebugVisitorType; // DebugVisitorType debugVisitor(image, mask, patchHalfWidth, boundaryStatusMap, boundaryNodeQueue); LoggerVisitor<VertexListGraphType> loggerVisitor("log.txt"); typedef CompositeInpaintingVisitor<VertexListGraphType> CompositeInpaintingVisitorType; CompositeInpaintingVisitorType compositeInpaintingVisitor; compositeInpaintingVisitor.AddVisitor(&inpaintingVisitor); // compositeInpaintingVisitor.AddVisitor(&displayVisitor); // compositeInpaintingVisitor.AddVisitor(&debugVisitor); compositeInpaintingVisitor.AddVisitor(&loggerVisitor); InitializePriority(mask, boundaryNodeQueue, &priorityFunction); // Initialize the boundary node queue from the user provided mask image. InitializeFromMaskImage<CompositeInpaintingVisitorType, VertexDescriptorType>(mask, &compositeInpaintingVisitor); std::cout << "PatchBasedInpaintingNonInteractive: There are " << boundaryNodeQueue.size() << " nodes in the boundaryNodeQueue" << std::endl; // Create the nearest neighbor finders typedef LinearSearchKNNProperty<ImagePatchDescriptorMapType, ImagePatchDifferenceType > KNNSearchType; KNNSearchType knnSearch(imagePatchDescriptorMap, 100000); // typedef LinearSearchKNNProperty<ImagePatchDescriptorMapType, // ImagePatchDifference<ImagePatchPixelDescriptorType> > KNNSearchType; // KNNSearchType knnSearch(smallImagePatchDescriptorMap, 1000); // For debugging we use LinearSearchBestProperty instead of DefaultSearchBest because it can output the difference value. typedef LinearSearchBestProperty<ImagePatchDescriptorMapType, ImagePatchDifferenceType > BestSearchType; BestSearchType bestSearch(imagePatchDescriptorMap); // TopPatchesDialog<TImage> topPatchesDialog(image, mask, patchHalfWidth); // typedef VisualSelectionBest<TImage> ManualSearchType; // ManualSearchType manualSearchBest(image, mask, patchHalfWidth, &topPatchesDialog); // By using this, essentially what we are saying is "if the acceptance tests fail, just use the first node". typedef FirstValidDescriptor<ImagePatchDescriptorMapType> ManualSearchType; ManualSearchType manualSearchBest(imagePatchDescriptorMap); // Run the remaining inpainting without interaction InpaintingAlgorithmWithVerification(graph, compositeInpaintingVisitor, &boundaryNodeQueue, knnSearch, bestSearch, &manualSearchBest, &patchInpainter); } #endif
51.88
135
0.774094
jingtangliao
c100f7a238c95561ac0ef8428c2e2926b3695794
365
cpp
C++
PROJECT_EULER Problem-34.cpp
m4l1c1ou5/PROJECT_EULER
8b1fdbffe8e1eecd74c67664a2d5cdddf353bad7
[ "CC0-1.0" ]
1
2020-08-27T12:27:22.000Z
2020-08-27T12:27:22.000Z
PROJECT_EULER Problem-34.cpp
m4l1c1ou5/PROJECT_EULER
8b1fdbffe8e1eecd74c67664a2d5cdddf353bad7
[ "CC0-1.0" ]
null
null
null
PROJECT_EULER Problem-34.cpp
m4l1c1ou5/PROJECT_EULER
8b1fdbffe8e1eecd74c67664a2d5cdddf353bad7
[ "CC0-1.0" ]
null
null
null
#include<iostream> using namespace std; int main(){ int h[10],mul=1,ans=0; h[0]=1; for(int i=1;i<=9;i++){ mul*=i; h[i]=mul; } for(int i=10;i<=10000000;i++){ int n=i,sum=0; while(n>0){ sum+=h[n%10]; n=n/10; } if(sum==i){ ans+=i; } } cout<<ans; }
16.590909
34
0.380822
m4l1c1ou5
c100f939588cc08ee6ad0089b244f0f441ee6c62
1,785
cpp
C++
src/LightBulb/Teaching/TeachingLessonBooleanInput.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
5
2016-02-04T06:14:42.000Z
2017-02-06T02:21:43.000Z
src/LightBulb/Teaching/TeachingLessonBooleanInput.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
41
2015-04-15T21:05:45.000Z
2015-07-09T12:59:02.000Z
src/LightBulb/Teaching/TeachingLessonBooleanInput.cpp
domin1101/LightBulb
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
null
null
null
// Includes #include "LightBulb/Teaching/TeachingLessonBooleanInput.hpp" #include "LightBulb/NeuralNetwork/NeuralNetwork.hpp" #include "LightBulb/Function/ActivationFunction/AbstractActivationFunction.hpp" // Library includes #include "LightBulb/NeuronDescription/NeuronDescription.hpp" namespace LightBulb { TeachingLessonBooleanInput::TeachingLessonBooleanInput(Vector<>* teachingPattern_, TeachingInput<char>* teachingInput_) { teachingInput.reset(teachingInput_); teachingPattern.reset(teachingPattern_); teachingInputLinear.reset(new TeachingInput<>(teachingInput_->getValues().getEigenValue().size())); } const TeachingInput<>& TeachingLessonBooleanInput::getTeachingInput(const AbstractActivationFunction& activationFunction) const { // Check if the neuralNetwork has a boolean acitvationFunction in all outputNeurons if (!activationFunction.hasAMaxAndMinimum()) throw std::invalid_argument("The activationFunction of the outputNeurons is linear, but your teaching input is boolean."); // Go through all teaching input values for (unsigned int i = 0; i < teachingInput->getValues().getEigenValue().size(); i++) { if (teachingInput->exists(i)) { // If the boolean value is true, set the maximum of the activationFunction, else the minimum if (teachingInput->get(i)) teachingInputLinear->set(i, activationFunction.getMaximum()); else teachingInputLinear->set(i, activationFunction.getMinimum()); } } // Return the vector with double values return *teachingInputLinear.get(); } TeachingInput<char>& TeachingLessonBooleanInput::getBooleanTeachingInput() const { return *teachingInput.get(); } const Vector<>& TeachingLessonBooleanInput::getTeachingPattern() const { return *teachingPattern.get(); } }
35
128
0.773669
domin1101
c108ddbf81c4ddf24f27aa3b3e9a8b908aace577
259
cpp
C++
SDLSandbox/SDLSandbox/Source/Factory/ProgressBarSpawner.cpp
kyuuzou/poison-strike
f9d0c41575ed94fd725ca48457e0eb54bf58cc4d
[ "MIT" ]
null
null
null
SDLSandbox/SDLSandbox/Source/Factory/ProgressBarSpawner.cpp
kyuuzou/poison-strike
f9d0c41575ed94fd725ca48457e0eb54bf58cc4d
[ "MIT" ]
null
null
null
SDLSandbox/SDLSandbox/Source/Factory/ProgressBarSpawner.cpp
kyuuzou/poison-strike
f9d0c41575ed94fd725ca48457e0eb54bf58cc4d
[ "MIT" ]
1
2022-03-16T23:01:04.000Z
2022-03-16T23:01:04.000Z
/* * Miniclip Challenge: Poison Strike * @author Nelson Rodrigues */ #include "ProgressBarSpawner.h" #include "../Actors/ProgressBar.h" using namespace Challenge; GameObject* ProgressBarSpawner::spawn () const { return new ProgressBar (); }
18.5
49
0.702703
kyuuzou
c10c3dcdc886cf7c44a806c26a7522047aee1752
14,835
cpp
C++
Engine/modules/Verve/Core/VObject.cpp
Pecon/Torque3D-1
81777348c8ab2fa49cbc534315294c3bee7ae3aa
[ "MIT" ]
417
2020-06-01T15:55:15.000Z
2022-03-31T12:50:51.000Z
Engine/modules/Verve/Core/VObject.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
186
2020-06-02T19:12:39.000Z
2022-02-15T02:22:27.000Z
Engine/modules/Verve/Core/VObject.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
84
2020-06-01T15:54:44.000Z
2022-03-24T13:52:59.000Z
//----------------------------------------------------------------------------- // Verve // Copyright (C) 2014 - Violent Tulip // // 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 "Verve/Core/VObject.h" #include "Verve/Core/VController.h" #include "console/consoleTypes.h" //----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT( VObject ); //----------------------------------------------------------------------------- VObject::VObject( void ) : mController( NULL ), mLabel( String::EmptyString ), mEnabled( true ) { // Void. }; VObject::~VObject( void ) { // Remove. remove(); } void VObject::initPersistFields( void ) { // Don't Use Parent Fields. // Parent::initPersistFields(); addProtectedField( "Enabled", TypeBool, Offset( mEnabled, VObject ), &setEnabled, &defaultProtectedGetFn, "Enable or Disable the object from playback." ); addProtectedField( "Label", TypeRealString, Offset( mLabel, VObject ), &setLabel, &defaultProtectedGetFn, "The label this object is referenced by." ); } //----------------------------------------------------------------------------- // // Reference Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VObject::getObject( pLabel ); // // Returns the object with the given label. If no object belongs to this object // with that label, then a NULL value is returned. // //----------------------------------------------------------------------------- VObject *VObject::getObject( const String &pLabel ) { VObject *node = ( VObject* )mChildNode; while ( node ) { // Compare Names. if ( node->getLabel().equal( pLabel, String::NoCase ) ) { // Valid. return node; } // Next Sibling. node = ( VObject* )node->mSiblingNextNode; } // Invalid. return NULL; } //----------------------------------------------------------------------------- // // Property Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VObject::isEnabled(); // // Returns whether this object is enabled. // //----------------------------------------------------------------------------- bool VObject::isEnabled( void ) { VObject *parent = dynamic_cast<VObject*>( getParent() ); if ( parent && !parent->isEnabled() ) { return false; } return mEnabled; } //----------------------------------------------------------------------------- // // VObject::isControllerPlaying(); // // Returns whether the root controller is currently playing. // //----------------------------------------------------------------------------- bool VObject::isControllerPlaying( void ) { if ( getController() ) { return getController()->isPlaying(); } return false; } //----------------------------------------------------------------------------- // // VObject::isControllerPaused(); // // Returns whether the root controller is currently paused. // //----------------------------------------------------------------------------- bool VObject::isControllerPaused( void ) { if ( getController() ) { return getController()->isPaused(); } return false; } //----------------------------------------------------------------------------- // // VObject::isControllerStopped(); // // Returns whether the root controller is currently stopped. // //----------------------------------------------------------------------------- bool VObject::isControllerStopped( void ) { if ( getController() ) { return getController()->isStopped(); } return true; } //----------------------------------------------------------------------------- // // VObject::isControllerPlayingForward(); // // Returns whether the root controller is currently playing forward. // //----------------------------------------------------------------------------- bool VObject::isControllerPlayingForward( void ) { if ( getController() ) { return getController()->isPlayingForward(); } return true; } //----------------------------------------------------------------------------- // // VObject::isControllerLooping(); // // Returns whether the root controller is looping the sequence. // //----------------------------------------------------------------------------- bool VObject::isControllerLooping( void ) { if ( getController() ) { return getController()->isLooping(); } return true; } //----------------------------------------------------------------------------- // // VObject::getControllerTime(); // // Returns the current time of the root controller. // //----------------------------------------------------------------------------- S32 VObject::getControllerTime( void ) { if ( getController() ) { return getController()->getTime(); } return 0; } //----------------------------------------------------------------------------- // // VObject::getControllerTimeScale(); // // Returns the current timescale of the root controller. // //----------------------------------------------------------------------------- F32 VObject::getControllerTimeScale( void ) { if ( getController() ) { return getController()->getTimeScale(); } return 1.f; } //----------------------------------------------------------------------------- // // VObject::getControllerDuration(); // // Returns the duration of the root controller. // //----------------------------------------------------------------------------- S32 VObject::getControllerDuration( void ) { if ( getController() ) { return getController()->getDuration(); } return 0; } //----------------------------------------------------------------------------- // // VObject::setLabel( pLabel ); // // Set the label property. // // If the project was built using the VT_EDITOR preprocessor argument, then the // label will not be changed if the target name is already used in the parent // object. // //----------------------------------------------------------------------------- void VObject::setLabel( const String &pLabel ) { #ifdef VT_EDITOR if ( mParentNode ) { // Empty Label? if ( mLabel.isEmpty() ) { // Set Uniqu Label. setLabelUnique( pLabel ); return; } for ( VObject *walk = ( VObject* )mChildNode; walk != NULL; walk = ( VObject* )walk->mSiblingNextNode ) { if ( walk != this ) { if ( pLabel == walk->getLabel() ) { // Exit. return; } } } } #endif // Set Label. mLabel = pLabel; } //----------------------------------------------------------------------------- // // VObject::setLabelUnique( pLabel ); // // If the label that has been passed is already in use, then a new label will // be generated by appending an index to the label. For example: MyLabel // becomes MyLabel0 ... MyLabelN // //----------------------------------------------------------------------------- void VObject::setLabelUnique( const String &pLabel ) { if ( mParentNode && pLabel.isNotEmpty() ) { for ( VObject *walk = ( VObject* )mChildNode; walk != NULL; walk = ( VObject* )walk->mSiblingNextNode ) { if ( walk != this ) { if ( pLabel == walk->getLabel() ) { // Strip Trailing Number. S32 i = -1; String labelBase( String::GetTrailingNumber( pLabel, i ) ); i++; // Construct New Name. String labelBuffer = String::ToString( "%s%d", labelBase.c_str(), i ); // Set Name. setLabelUnique( labelBuffer ); // Exit. return; } } } } // Set Name. mLabel = pLabel; } //----------------------------------------------------------------------------- // // Callback Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VObject::onAttach(); // // Callback made when this object is attached to another node. // //----------------------------------------------------------------------------- void VObject::onAttach( void ) { VTreeNode::onAttach(); // Store Controller. mController = dynamic_cast<VController*>( getRoot() ); #ifdef VT_EDITOR if ( isProperlyAdded() ) { Con::executef( this, "onAttach" ); } #endif } //----------------------------------------------------------------------------- // // VObject::onDetach(); // // Callback made when this object is detached from a parent node. // //----------------------------------------------------------------------------- void VObject::onDetach( void ) { VTreeNode::onDetach(); // Clear Controller. mController = NULL; #ifdef VT_EDITOR if ( isProperlyAdded() ) { Con::executef( this, "onDetach" ); } #endif } #ifdef VT_EDITOR //----------------------------------------------------------------------------- // // Debug Methods. // //----------------------------------------------------------------------------- ConsoleMethod( VObject, writeFile, bool, 3, 3, "( string pFileName ) - Save to a given filename.\n" "@param pFileName The target file to write to.\n" "@return Returns true if the write was successful." ) { // Write Target File. return VPersistence::writeFile( argv[2], object ); } ConsoleMethod( VObject, readFile, bool, 3, 3, "( string pFileName ) - Clears the object and loads the new data from the given filename.\n" "@param pFileName The target file to read from.\n" "@return Returns true if the read was successful." ) { // Read Target File. return VPersistence::readFile( argv[2], object ); } ConsoleMethod( VObject, getRoot, S32, 2, 2, "( void ) - Get the root object.\n" "@return Returns the SimObjectId for the root object." ) { // Fetch Object. VObject *objectRef = ( VObject* )object->getRoot(); // Return Object ID. return ( objectRef ) ? objectRef->getId() : 0; } ConsoleMethod( VObject, getParent, S32, 2, 2, "( void ) - Get the parent object.\n" "@return Returns the SimObjectId for the parent object." ) { // Fetch Object. VObject *objectRef = ( VObject* )object->mParentNode; // Return Object ID. return ( objectRef ) ? objectRef->getId() : 0; } ConsoleMethod( VObject, getIndex, S32, 2, 2, "( void ) - Get the index of this object relative to its siblings.\n" "@return Returns the index of this object." ) { return object->getIndex(); } ConsoleMethod( VObject, getCount, S32, 2, 2, "( void ) - Get the number of child objects.\n" "@return Returns the number of child objects." ) { return object->size(); } ConsoleMethod( VObject, getObject, S32, 3, 3, "( int pIndex ) - Get the object corresponding to the given index.\n" "@param pIndex The index of the object you wish to retrieve.\n" "@return Returns the SimObjectID for the object." ) { // Fetch Object. VObject *objectRef = ( VObject* )object->at( dAtoi( argv[2] ) ); // Return Object ID. return ( objectRef ) ? objectRef->getId() : 0; } ConsoleMethod( VObject, clear, void, 2, 2, "( void ) - Detaches and deletes all of the child objects.\n" "@return No return value." ) { // Clear Sequence Lists. object->clear(); } ConsoleMethod( VObject, addObject, void, 3, 3, "( SimObject pObject ) - Add a child object to this node.\n" "@param pObject The SimObjectID of the object to be added to this node.\n" "@return No return value." ) { VObject *child = dynamic_cast<VObject*>( Sim::findObject( argv[2] ) ); if ( child ) { child->addTo( object ); } } ConsoleMethod( VObject, removeObject, void, 3, 3, "( SimObject pObject ) - Remove the target object from this node.\n" "@param pObject The SimObjectID of the object to be removed from this node.\n" "@return No return value." ) { VObject *child = dynamic_cast<VObject*>( Sim::findObject( argv[2] ) ); if ( child && child->getParent() == object ) { child->remove(); } } ConsoleMethod( VObject, setLabelUnique, void, 3, 3, "( string pLabel ) - Force this label to be unique.\n" "@param pLabel The name you wish to reference this object by.\n" "@return No return value." ) { // Set Label. object->setLabelUnique( argv[2] ); } #endif
30.714286
164
0.45305
Pecon
c10c82ba2163c4fcd80d3d96ca55ce529e3f7e3d
4,087
cpp
C++
tests/spinlock_test.cpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
101
2017-01-19T10:38:06.000Z
2021-12-16T22:29:45.000Z
tests/spinlock_test.cpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
25
2017-01-18T09:22:15.000Z
2022-03-30T12:50:32.000Z
tests/spinlock_test.cpp
alishewn/yamc
f4ed5182c04c674c0e19992410578b327d768831
[ "MIT" ]
15
2017-10-28T03:54:42.000Z
2022-03-28T20:39:12.000Z
/* * spinlock_test.cpp */ #include <type_traits> #include "gtest/gtest.h" #include "naive_spin_mutex.hpp" #include "ttas_spin_mutex.hpp" #include "yamc_testutil.hpp" #if defined(__linux__) || defined(__APPLE__) #include "posix_native_mutex.hpp" #define ENABLE_POSIX_NATIVE_MUTEX #endif #define TEST_THREADS 20 #define TEST_ITERATION 100000u using SpinMutexTypes = ::testing::Types< yamc::spin::basic_mutex<yamc::backoff::exponential<>>, yamc::spin_weak::basic_mutex<yamc::backoff::exponential<>>, yamc::spin_ttas::basic_mutex<yamc::backoff::exponential<>>, yamc::spin::basic_mutex<yamc::backoff::yield>, yamc::spin_weak::basic_mutex<yamc::backoff::yield>, yamc::spin_ttas::basic_mutex<yamc::backoff::yield>, yamc::spin::basic_mutex<yamc::backoff::busy>, yamc::spin_weak::basic_mutex<yamc::backoff::busy>, yamc::spin_ttas::basic_mutex<yamc::backoff::busy> #if defined(ENABLE_POSIX_NATIVE_MUTEX) && YAMC_POSIX_SPINLOCK_SUPPORTED , yamc::posix::spinlock #endif >; template <typename Mutex> struct SpinMutexTest : ::testing::Test {}; TYPED_TEST_SUITE(SpinMutexTest, SpinMutexTypes); // mutex::lock() TYPED_TEST(SpinMutexTest, BasicLock) { TypeParam mtx; std::size_t counter = 0; yamc::test::task_runner( TEST_THREADS, [&](std::size_t /*id*/) { for (std::size_t n = 0; n < TEST_ITERATION; ++n) { std::lock_guard<TypeParam> lk(mtx); counter = counter + 1; } }); EXPECT_EQ(TEST_ITERATION * TEST_THREADS, counter); } // mutex::try_lock() TYPED_TEST(SpinMutexTest, TryLock) { TypeParam mtx; std::size_t counter = 0; yamc::test::task_runner( TEST_THREADS, [&](std::size_t /*id*/) { for (std::size_t n = 0; n < TEST_ITERATION; ++n) { while (!mtx.try_lock()) { std::this_thread::yield(); } std::lock_guard<TypeParam> lk(mtx, std::adopt_lock); counter = counter + 1; } }); EXPECT_EQ(TEST_ITERATION * TEST_THREADS, counter); } // mutex::try_lock() failure TYPED_TEST(SpinMutexTest, TryLockFail) { yamc::test::barrier step(2); TypeParam mtx; yamc::test::join_thread thd([&]{ EXPECT_NO_THROW(mtx.lock()); step.await(); // b1 step.await(); // b2 EXPECT_NO_THROW(mtx.unlock()); }); { step.await(); // b1 EXPECT_FALSE(mtx.try_lock()); step.await(); // b2 } } // lockfree property of atomic<int> TEST(AtomicTest, LockfreeInt) { // std::atomic<int> type is always lock-free EXPECT_EQ(2, ATOMIC_INT_LOCK_FREE); } // YAMC_BACKOFF_* macros TEST(BackoffTest, Macro) { bool yamc_backoff_spin_default = std::is_same<YAMC_BACKOFF_SPIN_DEFAULT, yamc::backoff::exponential<>>::value; EXPECT_TRUE(yamc_backoff_spin_default); EXPECT_EQ(4000, YAMC_BACKOFF_EXPONENTIAL_INITCOUNT); } // backoff::exponential<100> TEST(BackoffTest, Exponential100) { using BackoffPolicy = yamc::backoff::exponential<100>; BackoffPolicy::state state; EXPECT_EQ(100u, state.initcount); EXPECT_EQ(100u, state.counter); for (int i = 0; i < 100; ++i) { BackoffPolicy::wait(state); // wait 100 } EXPECT_EQ(0u, state.counter); for (int i = 0; i < 2000; ++i) { BackoffPolicy::wait(state); } EXPECT_EQ(1u, state.initcount); EXPECT_EQ(0u, state.counter); BackoffPolicy::wait(state); EXPECT_EQ(1u, state.initcount); EXPECT_EQ(0u, state.counter); } // backoff::exponential<1> TEST(BackoffTest, Exponential1) { using BackoffPolicy = yamc::backoff::exponential<1>; BackoffPolicy::state state; EXPECT_EQ(1u, state.initcount); EXPECT_EQ(1u, state.counter); BackoffPolicy::wait(state); EXPECT_EQ(1u, state.initcount); EXPECT_EQ(0u, state.counter); } // backoff::yield TEST(BackoffTest, Yield) { using BackoffPolicy = yamc::backoff::yield; // NOTE: backoff::yield class has no observable behavior nor state BackoffPolicy::state state; BackoffPolicy::wait(state); } // backoff::busy TEST(BackoffTest, Busy) { using BackoffPolicy = yamc::backoff::busy; // NOTE: backoff::busy class has no observable behavior nor state BackoffPolicy::state state; BackoffPolicy::wait(state); }
25.867089
112
0.69195
alishewn
c10e43c073692e60a01abc7a0fbdbe9b01da87d0
25,556
cpp
C++
NOLF/ObjectDLL/Breakable.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
65
2015-02-28T03:35:14.000Z
2021-09-23T05:43:33.000Z
NOLF/ObjectDLL/Breakable.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
null
null
null
NOLF/ObjectDLL/Breakable.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
27
2015-02-28T07:42:01.000Z
2022-02-11T01:35:20.000Z
// ----------------------------------------------------------------------- // // // MODULE : Breakable.CPP // // PURPOSE : A Breakable object // // CREATED : 1/14/99 // // (c) 1999-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "Breakable.h" #include "Trigger.h" #include "ClientServerShared.h" #include "ServerUtilities.h" #include "ObjectMsgs.h" #include "SoundMgr.h" #include "PlayerObj.h" #include "Spawner.h" BEGIN_CLASS(Breakable) // New properties... ADD_REALPROP_FLAG(BreakTime, 2.0f, 0) ADD_STRINGPROP_FLAG(BreakSound, "Snd\\Event\\Break.wav", PF_FILENAME) ADD_REALPROP_FLAG(BreakSoundRadius, 500.0f, PF_RADIUS) ADD_STRINGPROP_FLAG(ImpactSound, "Snd\\Event\\BreakImpact.wav", PF_FILENAME) ADD_REALPROP_FLAG(ImpactSoundRadius, 1000.0f, PF_RADIUS) ADD_BOOLPROP(TouchActivate, LTTRUE) ADD_BOOLPROP(DestroyOnImpact, LTFALSE) ADD_BOOLPROP(DestroyAfterBreak, LTFALSE) ADD_BOOLPROP(CrushObjects, LTFALSE) ADD_VECTORPROP_VAL(ScreenShakeAmount, 1.5f, 1.5f, 1.5f) PROP_DEFINEGROUP(Physics, PF_GROUP4) ADD_REALPROP_FLAG(FallVelocity, -1000.0f, PF_GROUP4) ADD_REALPROP_FLAG(RotationTime, 15.0f, PF_GROUP4) ADD_BOOLPROP_FLAG(AdjustPitch, LTTRUE, PF_GROUP4) ADD_REALPROP_FLAG(PitchDelta, 4.0f, PF_GROUP4) ADD_BOOLPROP_FLAG(AdjustYaw, LTTRUE, PF_GROUP4) ADD_REALPROP_FLAG(YawDelta, 2.0f, PF_GROUP4) ADD_BOOLPROP_FLAG(AdjustRoll, LTTRUE, PF_GROUP4) ADD_REALPROP_FLAG(RollDelta, 5.5f, PF_GROUP4) // Property overrides... ADD_BOOLPROP_FLAG(NeverDestroy, LTFALSE, PF_GROUP1) PROP_DEFINEGROUP(StateFlags, PF_GROUP4 | PF_HIDDEN) ADD_BOOLPROP_FLAG(ActivateTrigger, LTTRUE, PF_GROUP4 | PF_HIDDEN) ADD_BOOLPROP_FLAG(StartOpen, LTFALSE, PF_GROUP4 | PF_HIDDEN) ADD_BOOLPROP_FLAG(TriggerClose, LTTRUE, PF_GROUP4 | PF_HIDDEN) ADD_BOOLPROP_FLAG(RemainsOpen, LTTRUE, PF_GROUP4 | PF_HIDDEN) ADD_BOOLPROP_FLAG(ForceMove, LTFALSE, PF_GROUP4 | PF_HIDDEN) ADD_VISIBLE_FLAG(1, PF_HIDDEN) ADD_SOLID_FLAG(1, PF_HIDDEN) ADD_BOOLPROP_FLAG(BoxPhysics, LTFALSE, PF_HIDDEN) ADD_BOOLPROP_FLAG(Locked, LTTRUE, PF_HIDDEN) ADD_BOOLPROP_FLAG(IsKeyframed, LTTRUE, PF_HIDDEN) // Moves... ADD_BOOLPROP_FLAG(LoopSounds, LTTRUE, PF_HIDDEN) ADD_REALPROP_FLAG(Speed, 0.0f, PF_HIDDEN) ADD_REALPROP_FLAG(MoveDelay, 0.0f, PF_HIDDEN) ADD_REALPROP_FLAG(MoveDist, 0.0f, PF_HIDDEN) ADD_VECTORPROP_VAL_FLAG(MoveDir, 0.0f, 0.0f, 0.0f, PF_HIDDEN) ADD_VECTORPROP_VAL_FLAG(SoundPos, 0.0f, 0.0f, 0.0f, PF_HIDDEN) ADD_STRINGPROP_FLAG(PortalName, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(OpenSound, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(CloseSound, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(LockedSound, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(OpenedCommand, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(ClosedCommand, "", PF_HIDDEN) ADD_REALPROP_FLAG(SoundRadius, 1000.0f, PF_RADIUS | PF_HIDDEN) ADD_REALPROP_FLAG(OpenWaitTime, 4.0f, PF_HIDDEN) ADD_REALPROP_FLAG(CloseWaitTime, 0.0f, PF_HIDDEN) ADD_REALPROP_FLAG(ClosingSpeed, 0.0f, PF_HIDDEN) ADD_BOOLPROP(AITriggerable, 0) PROP_DEFINEGROUP(Waveform, PF_GROUP5 | PF_HIDDEN) ADD_BOOLPROP_FLAG(Linear, LTTRUE, PF_GROUP5 | PF_HIDDEN) ADD_BOOLPROP_FLAG(Sine, LTFALSE, PF_GROUP5 | PF_HIDDEN) ADD_BOOLPROP_FLAG(SlowOff, LTFALSE, PF_GROUP5 | PF_HIDDEN) ADD_BOOLPROP_FLAG(SlowOn, LTFALSE, PF_GROUP5 | PF_HIDDEN) ADD_STRINGPROP_FLAG(Attachments, "", PF_HIDDEN) ADD_BOOLPROP_FLAG(RemoveAttachments, LTTRUE, PF_HIDDEN) ADD_VECTORPROP_VAL_FLAG(AttachDir, 0.0f, 200.0f, 0.0f, PF_HIDDEN) ADD_STRINGPROP_FLAG(ShadowLights, "", PF_OBJECTLINK | PF_HIDDEN) END_CLASS_DEFAULT(Breakable, Door, NULL, NULL) // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::Breakable() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // Breakable::Breakable() : Door() { m_fRotVel = 0.0f; m_fBreakTime = 0.0f; m_fBreakSoundRadius = 0.0f; m_fImpactSoundRadius = 0.0f; m_hstrBreakSound = LTNULL; m_hstrImpactSound = LTNULL; m_bFalling = LTFALSE; m_bStarted = LTFALSE; m_bCrushObjects = LTFALSE; m_bTouchActivate = LTTRUE; m_bDestroyOnImpact = LTFALSE; m_bDestroyAfterBreak = LTFALSE; m_hBreakObj = LTNULL; m_vShakeAmount.Init(); m_vFinalPos.Init(); m_vTotalDelta.Init(); m_vDelta.Init(); m_vStartingPitchYawRoll.Init(); m_vPitchYawRoll.Init(); m_vSign.Init(1, 1, 1); m_vAdjust.Init(1, 1, 1); m_vVel.Init(0, -1000.0f, 0); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::~Breakable() // // PURPOSE: Deallocate object // // ----------------------------------------------------------------------- // Breakable::~Breakable() { FREE_HSTRING(m_hstrBreakSound); FREE_HSTRING(m_hstrImpactSound); if (m_hBreakObj) { g_pLTServer->BreakInterObjectLink(m_hObject, m_hBreakObj); } } // --------------------------------------------------------------------------- // // // ROUTINE: Breakable::EngineMessageFn() // // PURPOSE: Handler for engine messages // // --------------------------------------------------------------------------- // uint32 Breakable::EngineMessageFn(uint32 messageID, void *pData, float fData) { switch (messageID) { case MID_UPDATE: { // Door changes this, so save original value... LTBOOL bFirstUpdate = m_bFirstUpdate; uint32 dwRet = Door::EngineMessageFn(messageID, pData, fData); // Ignore the first update... if (!bFirstUpdate) { Update(); } return dwRet; } break; case MID_PRECREATE: { // Need to call base class to have the object name read in before // we call PostPropRead() uint32 dwRet = Door::EngineMessageFn(messageID, pData, fData); if (fData == PRECREATE_WORLDFILE) { ReadProp((ObjectCreateStruct*)pData); } return dwRet; } break; case MID_INITIALUPDATE: { CacheFiles(); } break; case MID_SAVEOBJECT: { Save((HMESSAGEWRITE)pData); } break; case MID_LOADOBJECT: { Load((HMESSAGEREAD)pData); } break; case MID_LINKBROKEN : { HOBJECT hLink = (HOBJECT)pData; if (hLink) { if (hLink == m_hBreakObj) { m_hBreakObj = LTNULL; } } } break; default : break; } return Door::EngineMessageFn(messageID, pData, fData); } // --------------------------------------------------------------------------- // // // ROUTINE: Breakable::ReadProp() // // PURPOSE: Reads breakable properties // // --------------------------------------------------------------------------- // void Breakable::ReadProp(ObjectCreateStruct *pStruct) { GenericProp genProp; if (g_pLTServer->GetPropGeneric("BreakTime", &genProp) == LT_OK) { m_fBreakTime = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("BreakSoundRadius", &genProp) == LT_OK) { m_fBreakSoundRadius = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("ImpactSoundRadius", &genProp) == LT_OK) { m_fImpactSoundRadius = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("DestroyOnImpact", &genProp) == LT_OK) { m_bDestroyOnImpact = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("DestroyAfterBreak", &genProp) == LT_OK) { m_bDestroyAfterBreak = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("CrushObjects", &genProp) == LT_OK) { m_bCrushObjects = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("TouchActivate", &genProp) == LT_OK) { m_bTouchActivate = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("BreakSound", &genProp) == LT_OK) { if (genProp.m_String[0]) { m_hstrBreakSound = g_pLTServer->CreateString(genProp.m_String); } } if (g_pLTServer->GetPropGeneric("ImpactSound", &genProp) == LT_OK) { if (genProp.m_String[0]) { m_hstrImpactSound = g_pLTServer->CreateString(genProp.m_String); } } if (g_pLTServer->GetPropGeneric("ScreenShakeAmount", &genProp ) == LT_OK) { m_vShakeAmount = genProp.m_Vec; } g_pLTServer->GetPropRotationEuler("Rotation", &m_vStartingPitchYawRoll); m_vPitchYawRoll = m_vStartingPitchYawRoll; if (g_pLTServer->GetPropGeneric("AdjustPitch", &genProp) == LT_OK) { m_vAdjust.x = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("PitchDelta", &genProp) == LT_OK) { m_vTotalDelta.x = MATH_DEGREES_TO_RADIANS(genProp.m_Float); } if (g_pLTServer->GetPropGeneric("AdjustYaw", &genProp) == LT_OK) { m_vAdjust.y = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("YawDelta", &genProp) == LT_OK) { m_vTotalDelta.y = MATH_DEGREES_TO_RADIANS(genProp.m_Float); } if (g_pLTServer->GetPropGeneric("AdjustRoll", &genProp) == LT_OK) { m_vAdjust.z = genProp.m_Float; } if (g_pLTServer->GetPropGeneric("RollDelta", &genProp) == LT_OK) { m_vTotalDelta.z = MATH_DEGREES_TO_RADIANS(genProp.m_Float); } if (g_pLTServer->GetPropGeneric("RotationTime", &genProp) == LT_OK) { if (genProp.m_Float > 0.0f) { m_fRotVel = MATH_CIRCLE / genProp.m_Float; } else { m_fRotVel = MATH_CIRCLE; } } if (g_pLTServer->GetPropGeneric("FallVelocity", &genProp) == LT_OK) { m_vVel.y = genProp.m_Float; } } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::Update() // // PURPOSE: Update the breakable // // ----------------------------------------------------------------------- // void Breakable::Update() { LTFLOAT fTime = g_pLTServer->GetTime(); g_pLTServer->SetNextUpdate(m_hObject, 0.001f); // See if it is time to stop the breaking... if (!m_BreakTimer.Stopped()) { // Update the breaking... UpdateBreaking(); } else if (!m_bFalling) { m_bFalling = StopBreak(); } if (m_bFalling) { UpdateFalling(); } } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::StartBreak() // // PURPOSE: Start the breaking... // // ----------------------------------------------------------------------- // void Breakable::StartBreak(HOBJECT hObj) { if (m_bStarted) return; m_bStarted = LTTRUE; // If an object caused us to break, give him a little upward // velocity... if (hObj) { m_hBreakObj = hObj; g_pLTServer->CreateInterObjectLink(m_hObject, m_hBreakObj); if (IsPlayer(hObj) && m_vShakeAmount.Mag() > 0.0f) { CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject(hObj); if (pPlayer) { HCLIENT hClient = pPlayer->GetClient(); if (hClient) { HMESSAGEWRITE hMessage = g_pLTServer->StartMessage(hClient, MID_SHAKE_SCREEN); g_pLTServer->WriteToMessageVector(hMessage, &m_vShakeAmount); g_pLTServer->EndMessage(hMessage); } } } } // Play the breaking sound... if (m_hstrBreakSound) { LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); char* pSnd = g_pLTServer->GetStringData(m_hstrBreakSound); if (pSnd) { g_pServerSoundMgr->PlaySoundFromPos(vPos, pSnd, m_fBreakSoundRadius, SOUNDPRIORITY_MISC_MEDIUM); } } // Use box physics (faster)... uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags |= FLAG_BOXPHYSICS; // Turn off the touch notify flag if we don't do crushing damage... if (!m_bCrushObjects) { dwFlags &= ~FLAG_TOUCH_NOTIFY; } g_pLTServer->SetObjectFlags(m_hObject, dwFlags); m_BreakTimer.Start(m_fBreakTime); m_vDelta.Init(); g_pLTServer->SetNextUpdate(m_hObject, 0.001f); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::StopBreak() // // PURPOSE: Stop the breaking... // // ----------------------------------------------------------------------- // LTBOOL Breakable::StopBreak() { if (m_bDestroyAfterBreak) { Destroy(); return LTFALSE; } // Determine how far we can fall before we'll hit the ground... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); IntersectQuery IQuery; IntersectInfo IInfo; IQuery.m_From = vPos; IQuery.m_To = vPos; IQuery.m_To.y -= 10000.0f; IQuery.m_Flags = INTERSECT_HPOLY | IGNORE_NONSOLID; if (g_pLTServer->IntersectSegment(&IQuery, &IInfo)) { m_vFinalPos = IInfo.m_Point; } else { m_vFinalPos = IQuery.m_To; } // Turn off our solid flag so anything on top of us will // fall normally... (i.e., they won't land on us while they // are falling)... uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags &= ~FLAG_SOLID; g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // If the player caused us to break, make sure the client // moves (this will make gravity pull the object down)... if (m_hBreakObj && IsPlayer(m_hBreakObj)) { CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject(m_hBreakObj); if (pPlayer) { pPlayer->TeleportClientToServerPos(); } g_pLTServer->BreakInterObjectLink(m_hObject, m_hBreakObj); m_hBreakObj = LTNULL; } // Create break fx... CreateBreakFX(); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::UpdateBreaking() // // PURPOSE: Update the breaking... // // ----------------------------------------------------------------------- // void Breakable::UpdateBreaking() { LTFLOAT fDeltaTime = g_pLTServer->GetFrameTime(); LTFLOAT fDelta = 0.0f; if (m_vAdjust.x) { fDelta = ((m_vSign.x > 0.0f ? m_fRotVel : -m_fRotVel) * fDeltaTime); m_vPitchYawRoll.x += fDelta; m_vDelta.x += fDelta; if (fabs(m_vDelta.x) >= m_vTotalDelta.x) { m_vDelta.x = (m_vSign.x * m_vTotalDelta.x); m_vPitchYawRoll.x = m_vStartingPitchYawRoll.x + m_vDelta.x; m_vSign.x *= -1.0f; } } if (m_vAdjust.y) { fDelta = ((m_vSign.y > 0.0f ? m_fRotVel : -m_fRotVel) * fDeltaTime); m_vPitchYawRoll.y += fDelta; m_vDelta.y += fDelta; if (fabs(m_vDelta.y) >= m_vTotalDelta.y) { m_vDelta.y = (m_vSign.y * m_vTotalDelta.y); m_vPitchYawRoll.y = m_vStartingPitchYawRoll.y + m_vDelta.y; m_vSign.y *= -1.0f; } } if (m_vAdjust.z) { fDelta = ((m_vSign.z > 0.0f ? m_fRotVel : -m_fRotVel) * fDeltaTime); m_vPitchYawRoll.z += fDelta; m_vDelta.z += fDelta; if (fabs(m_vDelta.z) >= m_vTotalDelta.z) { m_vDelta.z = (m_vSign.z * m_vTotalDelta.z); m_vPitchYawRoll.z = m_vStartingPitchYawRoll.z + m_vDelta.z; m_vSign.z *= -1.0f; } } // Shake, rattle, and roll... LTRotation rRot; g_pLTServer->GetObjectRotation(m_hObject, &rRot); g_pLTServer->SetupEuler(&rRot, m_vPitchYawRoll.x, m_vPitchYawRoll.y, m_vPitchYawRoll.z); g_pLTServer->SetObjectRotation(m_hObject, &rRot); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::UpdateFalling() // // PURPOSE: Update the falling state... // // ----------------------------------------------------------------------- // void Breakable::UpdateFalling() { LTVector vOldPos; g_pLTServer->GetObjectPos(m_hObject, &vOldPos); LTVector vPos = vOldPos; vPos += (m_vVel * g_pLTServer->GetFrameTime()); LTBOOL bDone = LTFALSE; if (vPos.y < m_vFinalPos.y) { vPos.y = m_vFinalPos.y; bDone = LTTRUE; } g_pLTServer->TeleportObject(m_hObject, &vPos); if (vPos.Equals(m_vFinalPos, 10.0f)) { bDone = LTTRUE; } if (bDone) { m_bFalling = LTFALSE; uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags |= FLAG_SOLID; g_pLTServer->SetObjectFlags(m_hObject, dwFlags); g_pLTServer->SetNextUpdate(m_hObject, 0.0f); // Create impact fx... CreateImpactFX(); if (m_bDestroyOnImpact) { Destroy(); } else { // Play the impact sound... if (m_hstrImpactSound) { LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); char* pSnd = g_pLTServer->GetStringData(m_hstrImpactSound); if (pSnd) { g_pServerSoundMgr->PlaySoundFromPos(vPos, pSnd, m_fImpactSoundRadius, SOUNDPRIORITY_MISC_MEDIUM); } } } } } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::Destroy() // // PURPOSE: Die // // ----------------------------------------------------------------------- // void Breakable::Destroy() { // Destroy us... HOBJECT hObj = LTNULL; LTVector vDir(0, 0, 0); DamageStruct damage; damage.eType = DT_EXPLODE; damage.fDamage = damage.kInfiniteDamage; damage.hDamager = hObj; damage.vDir = vDir; damage.DoDamage(this, m_hObject); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::CrushObject() // // PURPOSE: Crush the specified object // // ----------------------------------------------------------------------- // void Breakable::CrushObject(HOBJECT hObj) { if (!hObj) return; LTVector vPos; LTVector vHisPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pLTServer->GetObjectPos(m_hObject, &vHisPos); LTVector vDir = vPos - vHisPos; vDir.Norm(); DamageStruct damage; damage.eType = DT_CRUSH; damage.fDamage = damage.kInfiniteDamage; damage.hDamager = m_hObject; damage.vDir = vDir; damage.DoDamage(this, hObj); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::CreateBreakFX() // // PURPOSE: Create break fx // // ----------------------------------------------------------------------- // void Breakable::CreateBreakFX() { STEAMCREATESTRUCT sc; sc.fRange = 40.0f; sc.fCreateDelta = 10.0f; sc.fEndAlpha = 0.0f; sc.fEndScale = 2.5f; sc.fParticleRadius = 13000.0f; sc.fStartAlpha = 0.5f; sc.fStartScale = 1.0f; sc.fVel = 20.0f; sc.hstrParticle = g_pLTServer->CreateString("SFX\\Impact\\Spr\\Smoke.spr"); sc.vMinDriftVel.Init(-15, -20, -15); sc.vMinDriftVel.Init(15, -5, 15); sc.vColor1.Init(255, 255, 255); sc.vColor2.Init(255, 255, 255); LTVector vDims; g_pLTServer->GetObjectDims(m_hObject, &vDims); sc.fVolumeRadius = Max(vDims.x, vDims.y); sc.fVolumeRadius = Max(sc.fVolumeRadius, vDims.z); sc.nNumParticles = int(sc.fVolumeRadius / 10.0f); sc.nNumParticles = sc.nNumParticles < 1 ? 1 : sc.nNumParticles; LTRotation rRot; g_pLTServer->GetObjectRotation(m_hObject, &rRot); LTVector vDown(0, -1, 0); g_pLTServer->AlignRotation(&rRot, &vDown, LTNULL); LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); Steam* pSteam = (Steam*)SpawnObject("Steam", vPos, rRot); if (pSteam) { pSteam->Setup(&sc, 3.0f, LTTRUE); } // Clear this so we don't try and delete it twice... sc.hstrParticle = LTNULL; } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::CreateImpactFX() // // PURPOSE: Create impact fx // // ----------------------------------------------------------------------- // void Breakable::CreateImpactFX() { STEAMCREATESTRUCT sc; sc.fRange = 75.0f; sc.fCreateDelta = 10.0f; sc.fEndAlpha = 0.0f; sc.fEndScale = 3.0f; sc.fParticleRadius = 20000.0f; sc.fStartAlpha = 0.5f; sc.fStartScale = 1.0f; sc.fVel = 25.0f; sc.hstrParticle = g_pLTServer->CreateString("SFX\\Impact\\Spr\\Smoke.spr"); sc.vMinDriftVel.Init(-35, 5, -35); sc.vMinDriftVel.Init(35, 50, 35); sc.vColor1.Init(255, 255, 255); sc.vColor2.Init(255, 255, 255); LTVector vDims; g_pLTServer->GetObjectDims(m_hObject, &vDims); sc.fVolumeRadius = Max(vDims.x, vDims.y); sc.fVolumeRadius = Max(sc.fVolumeRadius, vDims.z); sc.nNumParticles = int(sc.fVolumeRadius / 10.0f); sc.nNumParticles = sc.nNumParticles < 1 ? 1 : sc.nNumParticles; LTRotation rRot; g_pLTServer->GetObjectRotation(m_hObject, &rRot); LTVector vDown(0, 1, 0); g_pLTServer->AlignRotation(&rRot, &vDown, LTNULL); LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); Steam* pSteam = (Steam*)SpawnObject("Steam", vPos, rRot); if (pSteam) { pSteam->Setup(&sc, 3.0f, LTTRUE); } // Clear this so we don't try and delete it twice... sc.hstrParticle = LTNULL; } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::TouchNotify // // PURPOSE: Handle object touch notify // // ----------------------------------------------------------------------- // void Breakable::TouchNotify(HOBJECT hObj) { if (!hObj || (!m_bTouchActivate && !m_bCrushObjects)) return; // Determine if he can actually break us (i.e., is he standing on us, or // is he moving fast enough to break through)... LTBOOL bBreak = IsStandingOnMe(hObj); // Start the break... if (!m_bStarted && bBreak) { StartBreak(hObj); } else if (m_bFalling && m_bCrushObjects) { CrushObject(hObj); } } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::IsStandingOnMe // // PURPOSE: Determine if the object is standing on me... // // ----------------------------------------------------------------------- // LTBOOL Breakable::IsStandingOnMe(HOBJECT hObj) { LTVector vHisPos, vPos; g_pLTServer->GetObjectPos(hObj, &vHisPos); g_pLTServer->GetObjectPos(m_hObject, &vPos); // We're touching, he's above me, so...yes... return (vHisPos.y > vPos.y); } // --------------------------------------------------------------------------- // // // ROUTINE: Breakable::TriggerMsg() // // PURPOSE: Handler for trigger messages. // // --------------------------------------------------------------------------- // void Breakable::TriggerMsg(HOBJECT hSender, const char* szMsg) { if (_stricmp(szMsg, "Break") == 0) { StartBreak(hSender); return; } Door::TriggerMsg(hSender, szMsg); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::CacheFiles // // PURPOSE: Cache resources used by this object // // ----------------------------------------------------------------------- // void Breakable::CacheFiles() { char* pFile = LTNULL; if (m_hstrBreakSound) { pFile = g_pLTServer->GetStringData(m_hstrBreakSound); if (pFile) { g_pLTServer->CacheFile(FT_SOUND, pFile); } } if (m_hstrImpactSound) { pFile = g_pLTServer->GetStringData(m_hstrImpactSound); if (pFile) { g_pLTServer->CacheFile(FT_SOUND, pFile); } } } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void Breakable::Save(HMESSAGEWRITE hWrite) { if (!hWrite) return; SAVE_HOBJECT(m_hBreakObj); SAVE_BOOL(m_bStarted); SAVE_BOOL(m_bFalling); SAVE_BOOL(m_bDestroyOnImpact); SAVE_BOOL(m_bDestroyAfterBreak); SAVE_BOOL(m_bCrushObjects); SAVE_BOOL(m_bTouchActivate); SAVE_FLOAT(m_fBreakTime); SAVE_FLOAT(m_fBreakSoundRadius); SAVE_FLOAT(m_fImpactSoundRadius); SAVE_FLOAT(m_fRotVel); SAVE_HSTRING(m_hstrBreakSound); SAVE_HSTRING(m_hstrImpactSound); SAVE_VECTOR(m_vStartingPitchYawRoll); SAVE_VECTOR(m_vPitchYawRoll); SAVE_VECTOR(m_vTotalDelta); SAVE_VECTOR(m_vDelta); SAVE_VECTOR(m_vSign); SAVE_VECTOR(m_vFinalPos); SAVE_VECTOR(m_vShakeAmount); SAVE_VECTOR(m_vAdjust); SAVE_VECTOR(m_vVel); m_BreakTimer.Save(hWrite); } // ----------------------------------------------------------------------- // // // ROUTINE: Breakable::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void Breakable::Load(HMESSAGEREAD hRead) { if (!hRead) return; LOAD_HOBJECT(m_hBreakObj); LOAD_BOOL(m_bStarted); LOAD_BOOL(m_bFalling); LOAD_BOOL(m_bDestroyOnImpact); LOAD_BOOL(m_bDestroyAfterBreak); LOAD_BOOL(m_bCrushObjects); LOAD_BOOL(m_bTouchActivate); LOAD_FLOAT(m_fBreakTime); LOAD_FLOAT(m_fBreakSoundRadius); LOAD_FLOAT(m_fImpactSoundRadius); LOAD_FLOAT(m_fRotVel); LOAD_HSTRING(m_hstrBreakSound); LOAD_HSTRING(m_hstrImpactSound); LOAD_VECTOR(m_vStartingPitchYawRoll); LOAD_VECTOR(m_vPitchYawRoll); LOAD_VECTOR(m_vTotalDelta); LOAD_VECTOR(m_vDelta); LOAD_VECTOR(m_vSign); LOAD_VECTOR(m_vFinalPos); LOAD_VECTOR(m_vShakeAmount); LOAD_VECTOR(m_vAdjust); LOAD_VECTOR(m_vVel); m_BreakTimer.Load(hRead); }
25.328048
99
0.578025
rastrup
c10edfd550cef4b12a8d8a53362cde5ae8494fa5
384
cpp
C++
files/Codepit (Maratonando)/57085da6ba5675eb5c22a7a3/D.cpp
t0rr3sp3dr0/t0rr3sp3dr0.github.io
64d34a35059fa2efcae5310407730d306c0775a1
[ "CC-BY-4.0" ]
null
null
null
files/Codepit (Maratonando)/57085da6ba5675eb5c22a7a3/D.cpp
t0rr3sp3dr0/t0rr3sp3dr0.github.io
64d34a35059fa2efcae5310407730d306c0775a1
[ "CC-BY-4.0" ]
null
null
null
files/Codepit (Maratonando)/57085da6ba5675eb5c22a7a3/D.cpp
t0rr3sp3dr0/t0rr3sp3dr0.github.io
64d34a35059fa2efcae5310407730d306c0775a1
[ "CC-BY-4.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int count = 1; int in; while (true) { scanf("%d", &in); if (in == 0) break; int sJ = 0; int sZ = 0; printf("Teste %d\n", count); for (int i = 0; i < in; i++) { int J; int Z; scanf("%d %d", &J, &Z); sJ += J; sZ += Z; printf("%d\n", sJ - sZ); } printf("\n"); count++; } return 0; }
14.222222
32
0.460938
t0rr3sp3dr0
c110c53e216189561de3cf840da3e4e96736d9c8
2,218
hpp
C++
Library/Deps/MessagePack/Include/msgpack/preprocessor/list/for_each.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/preprocessor/list/for_each.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/preprocessor/list/for_each.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
# /* Copyright (C) 2001 # * Housemarque Oy # * http://www.housemarque.com # * # * 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) # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef MSGPACK_PREPROCESSOR_LIST_FOR_EACH_HPP # define MSGPACK_PREPROCESSOR_LIST_FOR_EACH_HPP # # include <msgpack/preprocessor/config/config.hpp> # include <msgpack/preprocessor/list/for_each_i.hpp> # include <msgpack/preprocessor/tuple/elem.hpp> # include <msgpack/preprocessor/tuple/rem.hpp> # # /* MSGPACK_PP_LIST_FOR_EACH */ # # if ~MSGPACK_PP_CONFIG_FLAGS() & MSGPACK_PP_CONFIG_EDG() # define MSGPACK_PP_LIST_FOR_EACH(macro, data, list) MSGPACK_PP_LIST_FOR_EACH_I(MSGPACK_PP_LIST_FOR_EACH_O, (macro, data), list) # else # define MSGPACK_PP_LIST_FOR_EACH(macro, data, list) MSGPACK_PP_LIST_FOR_EACH_X(macro, data, list) # define MSGPACK_PP_LIST_FOR_EACH_X(macro, data, list) MSGPACK_PP_LIST_FOR_EACH_I(MSGPACK_PP_LIST_FOR_EACH_O, (macro, data), list) # endif # # if ~MSGPACK_PP_CONFIG_FLAGS() & MSGPACK_PP_CONFIG_EDG() # define MSGPACK_PP_LIST_FOR_EACH_O(r, md, i, elem) MSGPACK_PP_LIST_FOR_EACH_O_D(r, MSGPACK_PP_TUPLE_ELEM(2, 0, md), MSGPACK_PP_TUPLE_ELEM(2, 1, md), elem) # else # define MSGPACK_PP_LIST_FOR_EACH_O(r, md, i, elem) MSGPACK_PP_LIST_FOR_EACH_O_I(r, MSGPACK_PP_TUPLE_REM_2 md, elem) # define MSGPACK_PP_LIST_FOR_EACH_O_I(r, im, elem) MSGPACK_PP_LIST_FOR_EACH_O_D(r, im, elem) # endif # # define MSGPACK_PP_LIST_FOR_EACH_O_D(r, m, d, elem) m(r, d, elem) # # /* MSGPACK_PP_LIST_FOR_EACH_R */ # # if ~MSGPACK_PP_CONFIG_FLAGS() & MSGPACK_PP_CONFIG_EDG() # define MSGPACK_PP_LIST_FOR_EACH_R(r, macro, data, list) MSGPACK_PP_LIST_FOR_EACH_I_R(r, MSGPACK_PP_LIST_FOR_EACH_O, (macro, data), list) # else # define MSGPACK_PP_LIST_FOR_EACH_R(r, macro, data, list) MSGPACK_PP_LIST_FOR_EACH_R_X(r, macro, data, list) # define MSGPACK_PP_LIST_FOR_EACH_R_X(r, macro, data, list) MSGPACK_PP_LIST_FOR_EACH_I_R(r, MSGPACK_PP_LIST_FOR_EACH_O, (macro, data), list) # endif # # endif
44.36
159
0.748422
rneogns
c11541f94a14ee19dca7b49ca7494eaf409ae7c9
1,860
hpp
C++
src/main/cpp/Balau/Logging/LoggerMacros.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
6
2018-12-30T15:09:26.000Z
2020-04-20T09:27:59.000Z
src/main/cpp/Balau/Logging/LoggerMacros.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
null
null
null
src/main/cpp/Balau/Logging/LoggerMacros.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
2
2019-11-12T08:07:16.000Z
2019-11-29T11:19:47.000Z
// @formatter:off // // CPPLF C++ library // Copyright (C) 2017 Bora Software (contact@borasoftware.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef COM_BORA_SOFTWARE__BALAU_LOGGING__LOGGER_MACROS #define COM_BORA_SOFTWARE__BALAU_LOGGING__LOGGER_MACROS #include <Balau/Logging/Logger.hpp> ///// Logger call macros that do not have the Balau prefix in ////// ///// their name. Do not use in libraries (use CPPLF instead). ////// /// /// Log a trace message with the source code location of the logging statement. /// #define LogTrace(...) BalauLogTrace(__VA_ARGS__) /// /// Log a debug message with the source code location of the logging statement. /// #define LogDebug(...) BalauLogDebug(__VA_ARGS__) /// /// Log an info message with the source code location of the logging statement. /// #define LogInfo(...) BalauLogInfo(__VA_ARGS__) /// /// Log a warn message with the source code location of the logging statement. /// #define LogWarn(...) BalauLogWarn(__VA_ARGS__) /// /// Log an error message with the source code location of the logging statement. /// #define LogError(...) BalauLogError(__VA_ARGS__) /// /// Log a message at the specified level and with the source code location of the logging statement. /// #define LogLog(...) BalauLogLog(__VA_ARGS__) #endif // COM_BORA_SOFTWARE__BALAU_LOGGING__LOGGER_MACROS
31.525424
100
0.737634
borasoftware
c1155c0f75e3c8514a7209226fe66c868fca1eb6
4,065
cpp
C++
soccer/planning/tests/BezierPathTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/tests/BezierPathTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/tests/BezierPathTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <fstream> #include "planning/primitives/PathSmoothing.hpp" using Geometry2d::Point; static void check_bezier_low_curvature(const Planning::BezierPath& path) { // Expected error is O(1/N) constexpr int N = 1000; double ds = 1.0 / static_cast<double>(N); for (int i = 0; i <= N; i++) { double s = i * ds; double curvature = 0; path.Evaluate(s, nullptr, nullptr, &curvature); EXPECT_LE(std::abs(curvature), 100); } } static void check_bezier_smooth(const Planning::BezierPath& path) { // Expected error decreases with high N constexpr int N = 10000; constexpr double epsilon = 1e-2; Point previous_position; Point previous_velocity; path.Evaluate(0, &previous_position, &previous_velocity, nullptr); double ds = 1.0 / static_cast<double>(N); for (int i = 1; i <= N; i++) { double s = i * ds; Point position; Point tangent; double curvature = 0; path.Evaluate(s, &position, &tangent, &curvature); EXPECT_LE((0.5 * (previous_velocity + tangent) * ds) .distTo(position - previous_position), epsilon); double curvature_expected = (tangent.normalized() - previous_velocity.normalized()).mag() / ds / tangent.mag(); // Make sure that the approximate curvature is consistent with the // calculated exact value. EXPECT_NEAR(curvature, std::abs(curvature_expected), epsilon); previous_position = position; previous_velocity = tangent; } } TEST(BezierPath, two_points_path_smooth_and_consistent) { MotionConstraints constraints; std::vector<Point> points{Point{0, 0}, Point{1, 1}}; Planning::BezierPath path(std::move(points), Point(1, 0), Point(1, 0), constraints); check_bezier_smooth(path); } TEST(BezierPath, multiple_points_path_smooth_and_consistent) { MotionConstraints constraints; std::vector<Point> points{Point{0, 0}, Point{1, 1}, Point{2, 0}}; Planning::BezierPath path(std::move(points), Point(1, 0), Point(1, 0), constraints); check_bezier_smooth(path); } // Smoothed paths should have reasonably low curvature everywhere on the // path. Sadly, this does not hold with our current system, which uses // Bezier curves and places keypoints in a fairly naive manner. // All examples with zero-velocity endpoints are broken because of numerical // issues (in this case, the second and third control points go on top of the // first and fourth, respectively). // TODO(#1539): Switch to a scheme that minimizes sum of squared // {acceleration/curvature/etc}. This should be fairly simple with Hermite // splines, as acceleration on a point in a curve is a linear function of // the endpoints' positions and velocities (so sub of squared acceleration // is a quadratic in the velocities (decision variables)) TEST(BezierPath, DISABLED_zero_velocity_endpoints_straight_smooth_and_consistent) { MotionConstraints constraints; std::vector<Point> points{Point{0, 0}, Point{2, 0}}; Planning::BezierPath path(std::move(points), Point(0, 0), Point(0, 0), constraints); check_bezier_smooth(path); } TEST(BezierPath, DISABLED_zero_endpoints_curved_smooth_and_consistent) { MotionConstraints constraints; std::vector<Point> points{Point{0, 0}, Point{1, 1}, Point{2, 0}}; Planning::BezierPath path(std::move(points), Point(0, 0), Point(0, 0), constraints); check_bezier_smooth(path); check_bezier_low_curvature(path); } TEST(BezierPath, DISABLED_nonzero_start_zero_end_curved_smooth_and_consistent) { MotionConstraints constraints; std::vector<Point> points{Point{0, 0}, Point{2, 2}}; Planning::BezierPath path(std::move(points), Point(1, 0), Point(0, 0), constraints); check_bezier_smooth(path); check_bezier_low_curvature(path); }
36.294643
80
0.665683
kasohrab
c11bb7d9b39da995885a66951251571389a467c2
5,502
cpp
C++
ace/SPIPE_Connector.cpp
xiafuyang2004/ACEFileService
51a330cdf2515919abe102bac5fec995fbe89cca
[ "MIT" ]
1
2019-01-19T06:35:40.000Z
2019-01-19T06:35:40.000Z
dep/ACE_wrappers/ace/SPIPE_Connector.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
null
null
null
dep/ACE_wrappers/ace/SPIPE_Connector.cpp
Subv/diamondcore
e11891587736b6308e554f71cb56e8df1a1812ad
[ "OpenSSL" ]
1
2020-02-22T08:42:22.000Z
2020-02-22T08:42:22.000Z
// $Id: SPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $ #include "ace/SPIPE_Connector.h" #include "ace/Log_Msg.h" #include "ace/OS_NS_sys_time.h" #include "ace/OS_NS_fcntl.h" #include "ace/OS_NS_unistd.h" #if !defined (__ACE_INLINE__) #include "ace/SPIPE_Connector.inl" #endif /* __ACE_INLINE__ */ ACE_RCSID(ace, SPIPE_Connector, "$Id: SPIPE_Connector.cpp 80826 2008-03-04 14:51:23Z wotte $") ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_ALLOC_HOOK_DEFINE(ACE_SPIPE_Connector) // Creates a Local ACE_SPIPE. ACE_SPIPE_Connector::ACE_SPIPE_Connector (ACE_SPIPE_Stream &new_io, const ACE_SPIPE_Addr &remote_sap, ACE_Time_Value *timeout, const ACE_Addr & local_sap, int reuse_addr, int flags, int perms, LPSECURITY_ATTRIBUTES sa, int pipe_mode) { ACE_TRACE ("ACE_SPIPE_Connector::ACE_SPIPE_Connector"); if (this->connect (new_io, remote_sap, timeout, local_sap, reuse_addr, flags, perms, sa, pipe_mode) == -1 && timeout != 0 && !(errno == EWOULDBLOCK || errno == ETIME)) ACE_ERROR ((LM_ERROR, ACE_TEXT ("address %s, %p\n"), remote_sap.get_path_name (), ACE_TEXT ("ACE_SPIPE_Connector"))); } void ACE_SPIPE_Connector::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_SPIPE_Connector::dump"); #endif /* ACE_HAS_DUMP */ } ACE_SPIPE_Connector::ACE_SPIPE_Connector (void) { ACE_TRACE ("ACE_SPIPE_Connector::ACE_SPIPE_Connector"); } int ACE_SPIPE_Connector::connect (ACE_SPIPE_Stream &new_io, const ACE_SPIPE_Addr &remote_sap, ACE_Time_Value *timeout, const ACE_Addr & /* local_sap */, int /* reuse_addr */, int flags, int perms, LPSECURITY_ATTRIBUTES sa, int pipe_mode) { ACE_TRACE ("ACE_SPIPE_Connector::connect"); // Make darn sure that the O_CREAT flag is not set! ACE_CLR_BITS (flags, O_CREAT); ACE_HANDLE handle; ACE_UNUSED_ARG (pipe_mode); #if defined (ACE_WIN32) && \ !defined (ACE_HAS_PHARLAP) && !defined (ACE_HAS_WINCE) // We need to allow for more than one attempt to connect, // calculate the absolute time at which we give up. ACE_Time_Value absolute_time; if (timeout != 0) absolute_time = ACE_OS::gettimeofday () + *timeout; // Loop until success or failure. for (;;) { handle = ACE_OS::open (remote_sap.get_path_name(), flags, perms, sa); if (handle != ACE_INVALID_HANDLE) // Success! break; // Check if we have a busy pipe condition. if (::GetLastError() != ERROR_PIPE_BUSY) // Nope, this is a failure condition. break; // This will hold the time out value used in the ::WaitNamedPipe // call. DWORD time_out_value; // Check if we are to block until we connect. if (timeout == 0) // Wait for as long as it takes. time_out_value = NMPWAIT_WAIT_FOREVER; else { // Calculate the amount of time left to wait. ACE_Time_Value relative_time (absolute_time - ACE_OS::gettimeofday ()); // Check if we have run out of time. if (relative_time <= ACE_Time_Value::zero) { // Mimick the errno value returned by // ACE::handle_timed_open. if (*timeout == ACE_Time_Value::zero) errno = EWOULDBLOCK; else errno = ETIMEDOUT; // Exit the connect loop with the failure. break; } // Get the amount of time remaining for ::WaitNamedPipe. time_out_value = relative_time.msec (); } // Wait for the named pipe to become available. ACE_TEXT_WaitNamedPipe (remote_sap.get_path_name (), time_out_value); // Regardless of the return value, we'll do one more attempt to // connect to see if it is now available and to return // consistent error values. } // Set named pipe mode if we have a valid handle. if (handle != ACE_INVALID_HANDLE) { // Check if we are changing the pipe mode from the default. if (pipe_mode != (PIPE_READMODE_BYTE | PIPE_WAIT)) { DWORD dword_pipe_mode = pipe_mode; if (!::SetNamedPipeHandleState (handle, &dword_pipe_mode, 0, 0)) { // We were not able to put the pipe into the requested // mode. ACE_OS::close (handle); handle = ACE_INVALID_HANDLE; } } } #else /* ACE_WIN32 && !ACE_HAS_PHARLAP */ handle = ACE::handle_timed_open (timeout, remote_sap.get_path_name (), flags, perms, sa); #endif /* !ACE_WIN32 || ACE_HAS_PHARLAP || ACE_HAS_WINCE */ new_io.set_handle (handle); new_io.remote_addr_ = remote_sap; // class copy. return handle == ACE_INVALID_HANDLE ? -1 : 0; } ACE_END_VERSIONED_NAMESPACE_DECL
34.173913
94
0.563431
xiafuyang2004
c121e0458da7d2ad65c04ac995884aaec0b113c4
327
cpp
C++
src/common/util/random.cpp
caozhiyi/quicX
46b486fc7786faf479b60c24da8ebdec783b3d5b
[ "BSD-3-Clause" ]
1
2021-11-02T14:31:12.000Z
2021-11-02T14:31:12.000Z
src/common/util/random.cpp
caozhiyi/quicX
46b486fc7786faf479b60c24da8ebdec783b3d5b
[ "BSD-3-Clause" ]
null
null
null
src/common/util/random.cpp
caozhiyi/quicX
46b486fc7786faf479b60c24da8ebdec783b3d5b
[ "BSD-3-Clause" ]
1
2021-09-30T08:23:58.000Z
2021-09-30T08:23:58.000Z
#include <random> #include "random.h" namespace quicx { std::random_device RangeRandom::_random; std::mt19937 RangeRandom::_engine(_random()); RangeRandom::RangeRandom(int32_t min, int32_t max): _uniform(min, max) { } RangeRandom::~RangeRandom() { } int32_t RangeRandom::Random() { return _uniform(_engine); } }
14.863636
51
0.712538
caozhiyi
c1222cedf2b59c081f367cb83f7191496727fba3
3,688
cpp
C++
tests/concurrent_hash_map_pmreorder_break_insert/concurrent_hash_map_pmreorder_break_insert.cpp
skygyh/libpmemobj-cpp
fbe4025fd37beec6ba1374b4b32b0e83bc9e2204
[ "BSD-3-Clause" ]
null
null
null
tests/concurrent_hash_map_pmreorder_break_insert/concurrent_hash_map_pmreorder_break_insert.cpp
skygyh/libpmemobj-cpp
fbe4025fd37beec6ba1374b4b32b0e83bc9e2204
[ "BSD-3-Clause" ]
7
2018-12-11T22:16:42.000Z
2019-02-07T16:28:51.000Z
tests/concurrent_hash_map_pmreorder_break_insert/concurrent_hash_map_pmreorder_break_insert.cpp
szyrom/libpmemobj-cpp
78f10eb6ae76f33043b05cd5d15f1c1594dab421
[ "BSD-3-Clause" ]
2
2021-01-19T08:22:32.000Z
2021-01-19T08:23:32.000Z
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019-2020, Intel Corporation */ /* * concurrent_hash_map_pmreorder_break_insert.cpp -- * pmem::obj::concurrent_hash_map test * */ #include "unittest.hpp" #include <libpmemobj++/make_persistent.hpp> #include <libpmemobj++/p.hpp> #include <libpmemobj++/persistent_ptr.hpp> #include <libpmemobj++/pool.hpp> #include <future> #include <iostream> #include <libpmemobj++/container/concurrent_hash_map.hpp> #define LAYOUT "persistent_concurrent_hash_map" namespace nvobj = pmem::obj; namespace { typedef nvobj::concurrent_hash_map<nvobj::p<int>, nvobj::p<int>> persistent_map_type; typedef persistent_map_type::value_type value_type; struct root { nvobj::persistent_ptr<persistent_map_type> cons; }; static constexpr int elements[] = { 1, /* bucket #1 */ 2, /* bucket #2 */ 3, /* bucket #3 */ 2 + 255, /* bucket #1 */ 3 + 255, /* bucket #2 */ 4 + 255, /* bucket #3 */ }; static constexpr int len_elements = static_cast<int>(sizeof(elements) / sizeof(elements[0])); /* * check_exist -- (internal) check existence of an element */ void check_exist(nvobj::persistent_ptr<persistent_map_type> &map, int element, bool exists) { typename persistent_map_type::accessor accessor; UT_ASSERTeq(map->find(accessor, element), exists); if (exists) { UT_ASSERTeq(accessor->first, element); UT_ASSERTeq(accessor->second, element); } } /* * test_init -- (internal) init test * pmem::obj::concurrent_hash_map<nvobj::p<int>, nvobj::p<int> > */ void test_init(nvobj::pool<root> &pop) { auto persistent_map = pop.root()->cons; persistent_map->runtime_initialize(); for (int i = 0; i < len_elements / 2; i++) { persistent_map->insert(value_type(elements[i], elements[i])); check_exist(persistent_map, elements[i], true); } } /* * test_insert -- (internal) test * pmem::obj::concurrent_hash_map<nvobj::p<int>, nvobj::p<int> > */ void test_insert(nvobj::pool<root> &pop) { auto persistent_map = pop.root()->cons; persistent_map->runtime_initialize(); for (int i = len_elements / 2; i < len_elements - 1; i++) { persistent_map->insert(value_type(elements[i], elements[i])); check_exist(persistent_map, elements[i], true); } } void check_consistency(nvobj::pool<root> &pop) { auto persistent_map = pop.root()->cons; persistent_map->runtime_initialize(); auto size = static_cast<typename persistent_map_type::difference_type>( persistent_map->size()); UT_ASSERTeq( std::distance(persistent_map->begin(), persistent_map->end()), size); for (int i = 0; i < size; i++) { UT_ASSERTeq(persistent_map->count(elements[i]), 1); check_exist(persistent_map, elements[i], true); } for (int i = size; i < len_elements; i++) UT_ASSERTeq(persistent_map->count(elements[i]), 0); } } static void test(int argc, char *argv[]) { if (argc != 3 || strchr("coi", argv[1][0]) == nullptr) UT_FATAL("usage: %s <c|o|i> file-name", argv[0]); const char *path = argv[2]; nvobj::pool<root> pop; try { if (argv[1][0] == 'o') { pop = nvobj::pool<root>::open(path, LAYOUT); check_consistency(pop); } else if (argv[1][0] == 'c') { pop = nvobj::pool<root>::create(path, LAYOUT, PMEMOBJ_MIN_POOL * 20, S_IWUSR | S_IRUSR); pmem::obj::transaction::run(pop, [&] { pop.root()->cons = nvobj::make_persistent< persistent_map_type>(); }); test_init(pop); } else if (argv[1][0] == 'i') { pop = nvobj::pool<root>::open(path, LAYOUT); test_insert(pop); } } catch (pmem::pool_error &pe) { UT_FATAL("!pool::create: %s %s", pe.what(), path); } pop.close(); } int main(int argc, char *argv[]) { return run_test([&] { test(argc, argv); }); }
22.351515
73
0.669469
skygyh
c1241549d555cffcbec50333deee25f7be3d724c
8,119
cc
C++
ns-allinone-3.29/ns-3.29/scratch/myWiFi.cc
tayoon/My-NS-3
e39bd778fe31397e048f770533c5154761bbbcb5
[ "MIT" ]
null
null
null
ns-allinone-3.29/ns-3.29/scratch/myWiFi.cc
tayoon/My-NS-3
e39bd778fe31397e048f770533c5154761bbbcb5
[ "MIT" ]
null
null
null
ns-allinone-3.29/ns-3.29/scratch/myWiFi.cc
tayoon/My-NS-3
e39bd778fe31397e048f770533c5154761bbbcb5
[ "MIT" ]
null
null
null
/* * Network Topology * * p2p * AP AP * *-----------* * | | * | | * * * * n0 n1 * */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/point-to-point-module.h" #include "ns3/internet-module.h" #include "ns3/applications-module.h" #include "ns3/mobility-module.h" #include "ns3/config-store-module.h" #include "ns3/lte-module.h" #include "ns3/netanim-module.h" #include "ns3/flow-monitor-module.h" #include "ns3/wifi-module.h" #include "ns3/csma-module.h" #include "ns3/ofswitch13-module.h" #include "ns3/socket.h" #include <string> using namespace ns3; void SetPosition (Ptr<Node> node, Vector position) { Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> (); mobility->SetPosition (position); } Vector GetPosition (Ptr<Node> node) { Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> (); return mobility->GetPosition (); } void AdvancePosition (Ptr<Node> node) { Vector pos = GetPosition (node); pos.x += 10.0; SetPosition (node, pos); Simulator::Schedule (Seconds (1.0), AdvancePosition, node); } NS_LOG_COMPONENT_DEFINE ("Study"); int main (int argc, char *argv[]) { uint16_t numNodes = 7; uint16_t src_sink = 2; uint16_t sourceNode = 0; uint16_t sinkNode = numNodes - 1; Time simTime = Seconds (30.0); Time simStart = Seconds (1.0); Time simStop = Seconds (30.0); Time interPacketInterval = MilliSeconds (100); double distance = 200.0; // m uint32_t packetSize = 1024; // byte // Command line arguments CommandLine cmd; cmd.AddValue ("numNodes", "Number of nodes", numNodes); cmd.AddValue ("simTime", "Total duration of the simulation", simTime); cmd.AddValue ("interPacketInterval", "Inter packet interval", interPacketInterval); cmd.AddValue ("distance", "Distance between nodes", distance); cmd.AddValue ("packetSize", "Size of packet", packetSize); cmd.Parse (argc, argv); ConfigStore inputConfig; inputConfig.ConfigureDefaults (); // parse again so you can override default values from the command line cmd.Parse(argc, argv); LogComponentEnable ("UdpClient", LOG_LEVEL_INFO); LogComponentEnable ("UdpServer", LOG_LEVEL_INFO); NodeContainer ueNodes; // = 7 ueNodes.Create (numNodes); NodeContainer apNodes; // = 1 apNodes.Create (src_sink - 1); NetDeviceContainer wifiDev; NetDeviceContainer apDev; YansWifiChannelHelper channel = YansWifiChannelHelper::Default (); YansWifiPhyHelper phy = YansWifiPhyHelper::Default (); phy.SetChannel (channel.Create ()); WifiHelper wifi; wifi.SetStandard (WIFI_PHY_STANDARD_80211n_2_4GHZ); // wifi.SetRemoteStationManager ("ns3::AarfWifiManager"); wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",StringValue ("HtMcs0"), "ControlMode",StringValue ("HtMcs7")); WifiMacHelper mac; Ssid ssid = Ssid ("Wifi"); mac.SetType ("ns3::StaWifiMac", "Ssid", SsidValue (ssid), "ActiveProbing", BooleanValue (false)); wifiDev = wifi.Install(phy, mac, ueNodes.Get(sourceNode)); mac.SetType ("ns3::ApWifiMac", "Ssid", SsidValue (ssid)); apDev = wifi.Install(phy, mac, apNodes); NodeContainer p2pNodes; // = 2 p2pNodes.Add (apNodes); p2pNodes.Create (1); PointToPointHelper p2p; p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer p2pDev; p2pDev = p2p.Install (p2pNodes); NodeContainer csmaNodes; // = 2 csmaNodes.Add (p2pNodes.Get (1)); csmaNodes.Add (ueNodes.Get (sinkNode)); CsmaHelper csma; csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2))); NetDeviceContainer csmaDev; csmaDev = csma.Install (csmaNodes); //モビリティモデルの設定 MobilityHelper mobility; Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> (); for (uint16_t i = 0; i < numNodes; i++) { if (i % 3 == 0){ positionAlloc->Add(Vector(distance * (i / 3), 210, 0)); } else if (i % 3 == 1){ positionAlloc->Add(Vector(distance * ((i - 1) / 3) + distance / 2, 180, 0)); } else{ positionAlloc->Add(Vector(distance * ((i - 2) / 3) + distance / 2, 240, 0)); } } for (uint16_t i = 0; i < src_sink; i++) { positionAlloc->Add(Vector(distance * 2 * i + 50, 140, 0)); } mobility.SetPositionAllocator(positionAlloc); mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel"); mobility.Install (ueNodes); mobility.Install (p2pNodes); //プロトコルスタックの設定(IPv4かIPv6か決める) InternetStackHelper internet; internet.Install(ueNodes); internet.Install(p2pNodes); //IPアドレス割り当て //右側のノード、AP Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer p2pInterface; p2pInterface = address.Assign (p2pDev); address.SetBase ("10.1.2.0", "255.255.255.0"); Ipv4InterfaceContainer csmaInterface; csmaInterface = address.Assign (csmaDev); address.SetBase ("10.1.3.0", "255.255.255.0"); Ipv4InterfaceContainer wifiIpIface; wifiIpIface = address.Assign (wifiDev); Ipv4InterfaceContainer apIpIface; apIpIface = address.Assign (apDev); UdpServerHelper Server (9); ApplicationContainer serverApps = Server.Install(csmaNodes.Get(sinkNode-5)); serverApps.Start (simStart); serverApps.Stop (simStop); UdpClientHelper Client(csmaInterface.GetAddress(sinkNode-5),9); Client.SetAttribute ("MaxPackets", UintegerValue (10000)); Client.SetAttribute ("Interval", TimeValue (interPacketInterval)); Client.SetAttribute ("PacketSize", UintegerValue (packetSize)); ApplicationContainer clientApps = Client.Install (ueNodes.Get (sourceNode)); clientApps.Start (simStart); clientApps.Stop (simStop); AnimationInterface anim ("my-wifi-ver9.xml"); // Mandatory for (uint32_t i = 0; i < numNodes; i++) { anim.UpdateNodeDescription (ueNodes.Get (i), "UE"); // Optional anim.UpdateNodeColor (ueNodes.Get (i), 255, 0, 0); // Optional } for (uint32_t i = 0; i < src_sink; i++) { anim.UpdateNodeDescription (p2pNodes.Get (i), "AP"); // Optional anim.UpdateNodeColor (p2pNodes.Get (i), 0, 255, 0); // Optional } anim.EnablePacketMetadata (); // Optional FlowMonitorHelper flowmon; Ptr<FlowMonitor> monitor = flowmon.InstallAll (); for (int i = 0; i < src_sink; i++) { Simulator::Schedule (Seconds (1), AdvancePosition, ueNodes.Get (i*(numNodes-1))); } Ipv4GlobalRoutingHelper::PopulateRoutingTables (); Simulator::Stop (simTime); Simulator::Run (); monitor->CheckForLostPackets (); Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ()); FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats (); for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin (); i != stats.end (); ++i) { Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (i->first); std::cout << "Flow " << i->first << " (" << t.sourceAddress << " -> " << t.destinationAddress << ")\n"; std::cout << " Tx Packets: " << i->second.txPackets << "\n"; std::cout << " Tx Bytes: " << i->second.txBytes << "\n"; std::cout << " Tx Offered: " << i->second.txBytes * 8.0 / 10 / 1000 / 1000 << " Mbps\n"; std::cout << " Rx Packets: " << i->second.rxPackets << "\n"; std::cout << " Rx Bytes: " << i->second.rxBytes << "\n"; std::cout << " Throughput: " << i->second.rxBytes * 8.0 / 10 / 1000 / 1000 << " Mbps\n"; } Simulator::Destroy (); return 0; }
32.090909
111
0.633699
tayoon
c126b424302f19a43ba34c99061d694cb5bbd6cf
428
hpp
C++
engine/include/real/renderer/base_rendering_context.hpp
tarantulala/real
8e69411c2025c348b18e12e223cf4b085e0387dc
[ "MIT" ]
9
2020-10-06T16:00:55.000Z
2020-12-29T07:09:54.000Z
engine/include/real/renderer/base_rendering_context.hpp
Light-Lens/real
194de672d7af35457e42a4aa24bfd77523eb09ca
[ "MIT" ]
null
null
null
engine/include/real/renderer/base_rendering_context.hpp
Light-Lens/real
194de672d7af35457e42a4aa24bfd77523eb09ca
[ "MIT" ]
3
2020-11-20T09:04:20.000Z
2021-01-11T13:44:19.000Z
// Copyright (c) 2020 udv. All rights reserved. #ifndef REAL_RENDERING_CONTEXT_BASE #define REAL_RENDERING_CONTEXT_BASE #include "real/core.hpp" #include "real/renderer/renderer_api.hpp" namespace Real { class REAL_API RenderingContext { public: virtual ~RenderingContext(); virtual void Init() = 0; virtual void SwapBuffers() = 0; virtual void VSync(bool enabled) = 0; }; } #endif //REAL_RENDERING_CONTEXT_BASE
20.380952
47
0.752336
tarantulala
c1282e2383240871d0114f12ecfe2a23b3e8f3b6
5,654
cpp
C++
src/core/map_node.cpp
surround-io/ellis
cb861e8dce9047a893d28ebcb4213ff530b8396d
[ "MIT" ]
1
2017-03-31T17:08:04.000Z
2017-03-31T17:08:04.000Z
src/core/map_node.cpp
surround-io/ellis
cb861e8dce9047a893d28ebcb4213ff530b8396d
[ "MIT" ]
null
null
null
src/core/map_node.cpp
surround-io/ellis
cb861e8dce9047a893d28ebcb4213ff530b8396d
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 Surround.IO Corporation. All Rights Reserved. * Copyright (c) 2017 Xevo 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 <ellis/core/map_node.hpp> #include <ellis/core/err.hpp> #include <ellis/core/node.hpp> #include <ellis/core/system.hpp> #include <ellis_private/core/payload.hpp> #include <ellis_private/using.hpp> namespace ellis { #define GETMAP m_node.m_pay->m_map map_node::~map_node() { ELLIS_ASSERT_UNREACHABLE(); /* This function should never be called; map_node is a type safety wrapper * over node, and destruction is to be handled by node. The user should * only ever see map_node by reference, and only be able to destroy * a node, not a map_node. */ } node & map_node::operator[](const std::string &key) { return const_cast<node&>( (*(static_cast<const map_node*>(this)))[key]); } const node & map_node::operator[](const std::string &key) const { const auto it = GETMAP.find(key); if (it == GETMAP.end()) { auto added = GETMAP.emplace(key, node(type::NIL)); ELLIS_ASSERT(added.second); return added.first->second; } return it->second; } bool map_node::operator==(const map_node &o) const { return GETMAP == o.GETMAP; } void map_node::add( const std::string &key, const node &val, add_policy addpol, add_failure_fn *failfn) { auto it = GETMAP.find(key); bool exists = not (it == GETMAP.end()); bool will_replace = exists && addpol != add_policy::INSERT_ONLY; bool will_insert = (not exists) && addpol != add_policy::REPLACE_ONLY; /* will_replace and will_insert can not both be set. */ ELLIS_ASSERT(! (will_replace && will_insert)); if (will_insert) { GETMAP.emplace(key, val); } else if (will_replace) { GETMAP.erase(it->first); GETMAP.emplace(key, val); } else { if (failfn != nullptr) { (*failfn)(key, val); } } } void map_node::add( const char *key, const node &val, add_policy addpol, add_failure_fn *failfn) { add(string(key), val, addpol, failfn); } void map_node::insert(const std::string &key, const node &val) { add(key, val, add_policy::INSERT_ONLY, nullptr); } void map_node::insert(const char *key, const node &val) { add(key, val, add_policy::INSERT_ONLY, nullptr); } void map_node::replace(const std::string &key, const node &val) { add(key, val, add_policy::REPLACE_ONLY, nullptr); } void map_node::replace(const char *key, const node &val) { add(key, val, add_policy::REPLACE_ONLY, nullptr); } void map_node::set(const std::string &key, const node &val) { add(key, val, add_policy::INSERT_OR_REPLACE, nullptr); } void map_node::set(const char *key, const node &val) { add(key, val, add_policy::INSERT_OR_REPLACE, nullptr); } void map_node::merge( const map_node &other, add_policy addpol, add_failure_fn *failfn) { for (const auto &it : other.m_node.m_pay->m_map) { add(it.first, it.second, addpol, failfn); } } void map_node::erase(const std::string &key) { GETMAP.erase(key); } void map_node::erase(const char *key) { GETMAP.erase(key); } bool map_node::has_key(const char *key) const { return GETMAP.count(key) > 0; } bool map_node::has_key(const std::string &key) const { return GETMAP.count(key) > 0; } std::vector<std::string> map_node::keys() const { vector<string> rv; for (const auto &it : GETMAP) { rv.push_back(it.first); } return rv; } void map_node::foreach_mutable(std::function< void(const std::string &, node &)> fn) { for (auto &it : GETMAP) { fn(it.first, it.second); } } void map_node::foreach(std::function< void(const std::string &, const node &)> fn) const { for (const auto &it : GETMAP) { fn(it.first, it.second); } } node map_node::filter(std::function< bool(const std::string &, const node &)> fn) const { node res_node(type::MAP); auto &res_map = res_node._as_mutable_map(); for (const auto &it : GETMAP) { if (fn(it.first, it.second)) { res_map.insert(it.first, it.second); } } return res_node; } size_t map_node::length() const { return GETMAP.size(); } bool map_node::is_empty() const { return GETMAP.empty(); } void map_node::clear() { GETMAP.clear(); } std::ostream & operator<<(std::ostream & os, const map_node &v) { size_t count = 0; size_t length = v.length(); os << "{"; v.foreach([&os, &count, &length](const string &k, const node &n) { os << k << ": " << n; count++; if (count < length) { os << ", "; } }); os << "}"; return os; } } /* namespace ellis */
21.416667
80
0.671206
surround-io
c12b555e6f0aa9d0d7a28fb75ab727ca9deab553
1,974
cpp
C++
test/verify/aoj-2450.test.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
null
null
null
test/verify/aoj-2450.test.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
null
null
null
test/verify/aoj-2450.test.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
1
2020-10-14T20:51:44.000Z
2020-10-14T20:51:44.000Z
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2450" #include "../../template/template.cpp" #include "../../graph/template.cpp" #include "../../structure/segment-tree/lazy-segment-tree.cpp" #include "../../graph/tree/heavy-light-decomposition.cpp" int main() { int N, Q, S[200000]; cin >> N >> Q; for(int i = 0; i < N; i++) { cin >> S[i]; } UnWeightedGraph g(N); HeavyLightDecomposition< UnWeightedGraph > tree(g); for(int i = 0; i < N - 1; i++) { int u, v; cin >> u >> v; --u, --v; g[u].emplace_back(v); g[v].emplace_back(u); } tree.build(); struct Node { int64 ans, all, left, right, length; Node() : ans(-infll), all(0), left(-infll), right(-infll), length(0) {} Node(int64 val, int64 len) { length = len; all = val * length; ans = left = right = (val > 0 ? all : val); } Node operator+(const Node &s) const { Node ret; ret.length = length + s.length; ret.ans = max({ans, s.ans, right + s.left}); ret.all = all + s.all; ret.left = max(left, all + s.left); ret.right = max(s.right, right + s.all); return ret; } }; auto F = [](const Node &a, const Node &b) { return a + b; }; auto G = [](const Node &a, int64 x) { return Node(x, a.length); }; auto H = [](int64 x, int64 y) { return y; }; LazySegmentTree< Node, int64 > seg(N, F, G, H, Node(), infll); for(int i = 0; i < N; i++) seg.set(i, Node(S[tree.rev[i]], 1)); seg.build(); auto QF = [&](int a, int b) { return seg.query(a, b); }; auto QG = [](const Node &a, const Node &b) { return a + b; }; auto QS = [](Node l, const Node &r) { swap(l.left, l.right); return l + r; }; while(Q--) { int T, A, B, C; cin >> T >> A >> B >> C; --A, --B; if(T == 1) { tree.add(A, B, [&](int a, int b) { seg.update(a, b, C); }); } else { cout << tree.query(A, B, Node(), QF, QG, QS).ans << "\n"; } } }
26.32
79
0.519757
beet-aizu
c12b8810cc60c07556c48fcf080c169cade738c8
305
hpp
C++
include/server/world.hpp
Foomf/Thimble
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
null
null
null
include/server/world.hpp
Foomf/Thimble
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
11
2019-09-14T11:02:24.000Z
2019-09-19T04:54:25.000Z
include/server/world.hpp
Foomf/Blyss
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
null
null
null
#pragma once #include <map> #include <string> #include <memory> #include "map.hpp" namespace blyss::server { class world { std::map<std::string, std::unique_ptr<map>> maps_; public: world(); void add_map(const std::string& name, std::unique_ptr<map> map); }; }
15.25
72
0.603279
Foomf
c12d4893df4bb8e1865c3f79a2f942024d60086a
1,490
cpp
C++
Menus/PauseMenu.cpp
colinmcgovern/panel-pop
7ac63a5fe5c7d5048a5d6dd97a8eb02e06861104
[ "MIT" ]
43
2016-03-22T11:08:13.000Z
2022-03-12T04:33:51.000Z
Menus/PauseMenu.cpp
colinmcgovern/panel-pop
7ac63a5fe5c7d5048a5d6dd97a8eb02e06861104
[ "MIT" ]
11
2016-09-26T18:16:46.000Z
2020-12-12T21:46:43.000Z
Menus/PauseMenu.cpp
colinmcgovern/panel-pop
7ac63a5fe5c7d5048a5d6dd97a8eb02e06861104
[ "MIT" ]
23
2016-08-08T07:56:03.000Z
2021-12-29T01:30:29.000Z
/* * PauseMenu.cpp * * Created on: 6.2.2016 * Author: axelw */ #include "PauseMenu.h" #include <SDL2/SDL_pixels.h> #include <SDL2/SDL_rect.h> #include <SDL2/SDL_render.h> #include <SDL2/SDL_timer.h> #include <string> #include <vector> #include "../Game/Game.h" #include "../SDLContext.h" #include "../States/StateManager.h" #include "MenuItem.h" PauseMenu::PauseMenu(Game &game) : _game(game) { addItem(MenuItem("RESUME", [this]() { _game.inputTogglePause(); })); addItem( MenuItem("QUIT", []() { StateManager::getInstance().returnToTitle(); })); } PauseMenu::~PauseMenu() { } void PauseMenu::render() const { //background SDL_Rect sprite = {0, 410, 150, 70}; SDL_Rect pos = {245, 205, 150, 70}; SDL_RenderCopy(_SDLRenderer, _spriteSheet, &sprite, &pos); int x = pos.x + 20; int y = pos.y + 8; _SDLContext.renderText("-PAUSE-", {255, 255, 255}, _SDLContext._fontPs, x, y); x = pos.x + 16; y += 2; for (unsigned i = 0; i < _items.size(); ++i) { y += 18; std::string text = _items.at(i).getName(); if (_selection == i && (SDL_GetTicks() - _time) % 1000 < 500) { text = "\u25b6" + text; } else { text = " " + text; } _SDLContext.renderText(text, {255, 255, 255}, _SDLContext._fontPs, x, y); } } void PauseMenu::inputCancel() { _game.inputTogglePause(); }
22.923077
78
0.552349
colinmcgovern
c12dd864b2cbd054d802bac54c4fda5ffd2bb654
3,680
cc
C++
src/MSM/estimate_strains.cc
ecr05/MSM_HOCR
c56f832436b18e612e95d3802b1961453910b283
[ "Unlicense" ]
21
2018-06-19T17:12:37.000Z
2022-02-12T11:47:17.000Z
src/MSM/estimate_strains.cc
ecr05/MSM_HOCR
c56f832436b18e612e95d3802b1961453910b283
[ "Unlicense" ]
16
2019-03-25T23:32:20.000Z
2021-12-13T13:07:12.000Z
src/MSM/estimate_strains.cc
ecr05/MSM_HOCR
c56f832436b18e612e95d3802b1961453910b283
[ "Unlicense" ]
8
2018-07-18T22:19:37.000Z
2021-10-05T13:54:20.000Z
/* estimate_strains.cc Emma Robinson, FMRIB Image Analysis Group Copyright (C) 2012 University of Oxford */ /* CCOPYRIGHT */ /* this program is designed to downsample freesurfer label files to be used in combination with the SPH6.vtk or other downsampled meshes*/ #include <iostream> #include <string> #include <fstream> #include <stdio.h> #include <cmath> #include <sstream> #include "newmat.h" #include "newmatio.h" #include "utils/options.h" #include "newimage/newimageall.h" #include "MeshReg/meshreg.h" using namespace std; using namespace NEWMAT; using namespace MISCMATHS; using namespace NEWMESH; using namespace MESHREG; void Usage() { cout << "estimate_strains <original anatomical mesh> <transformed mesh > <outdir> <-option> " << endl; cout << " estimates principal strains tangent to surface" << endl; cout << " options: " << endl; cout << " -fit-radius default 2 " << endl; cout << " -sphere X.surf.gii supply input sphere for approximate neighbourhood searching (will speed up calculation) " << endl; cout <<"-bulk bulk modulus (default 10) " << endl; cout << "-shear shear modulus (default 10) " << endl; cout << " " << endl; } int main(int argc, char **argv){ clock_t start = clock(); newmesh ORIG, TRANSFORMED, STRAINS,SPHERE; boost::shared_ptr<Matrix> VECS; VECS= boost::shared_ptr<Matrix> (new Matrix); string outdir; double fit_radius=0; double MU=0.1,KAPPA=10; boost::shared_ptr<RELATIONS> REL; boost::shared_ptr<newmesh > SPHERETMP; int ok; bool _targ=false,_calcrel=false; if(argc < 4){ Usage(); exit(0); } ORIG.load(argv[1]); argc--; argv++; TRANSFORMED.load(argv[1]); argc--; argv++; outdir=argv[1]; argc--; argv++; while (argc > 1) { ok = 0; if((ok == 0) && (strcmp(argv[1], "-fit-radius") == 0)){ argc--; argv++; fit_radius=atof(argv[1]); argc--; argv++; ok=1; } else if((ok == 0) && (strcmp(argv[1], "-sphere") == 0)){ argc--; argv++; SPHERE.load(argv[1]); _calcrel=true; argc--; argv++; ok=1; } else if((ok == 0) && (strcmp(argv[1], "-bulk") == 0)){ argc--; argv++; KAPPA=atof(argv[1]); argc--; argv++; ok=1; } else if((ok == 0) && (strcmp(argv[1], "-shear") == 0)){ argc--; argv++; MU=atof(argv[1]); argc--; argv++; ok=1; } else{cout << " option doesn't exist " << endl; exit(1);} } /* if(_calcrel){ REL=boost::shared_ptr<RELATIONS >(new RELATIONS (SPHERE,SPHERE,3*asin(fit_radius/RAD))); REL->update_RELATIONS(SPHERE); } */ cout << " calculate strains " << MU << " " << KAPPA << endl; ORIG.estimate_normals(); TRANSFORMED.estimate_normals(); if(SPHERE.nvertices()==ORIG.nvertices()) { SPHERETMP=boost::shared_ptr<newmesh >(new newmesh (SPHERE)); } if(fit_radius>0) STRAINS=calculate_strains(fit_radius,ORIG,TRANSFORMED,VECS,REL); else STRAINS=calculate_triangular_strains(ORIG,TRANSFORMED,MU,KAPPA); STRAINS.save(outdir+"strains.func"); /* ofstream strain1,strain2; strain1.open(outdir+"U1"); strain2.open(outdir+"U2"); cout << " output U1 and U2 " << endl; if(VECS->Nrows()==ORIG.nvertices()){ for(int i=1;i<=ORIG.nvertices();i++){ for(int j=1;j<=3;j++) strain1 << (*VECS)(i,j) << " " ; strain1 << endl; for(int j=4;j<=6;j++) strain2 << (*VECS)(i,j) << " " ; strain2 << endl; } } strain1.close(); strain2.close(); cout<<"Time elapsed: " << ((double)clock() - start) / CLOCKS_PER_SEC << endl; */ }
23.896104
138
0.589946
ecr05
c1359307f271abeb597ba059751cad217a3eb202
137
cpp
C++
Practical 8/prac 8 task2.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-23T16:06:39.000Z
2021-09-23T16:06:39.000Z
Practical 8/prac 8 task2.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
null
null
null
Practical 8/prac 8 task2.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-24T15:10:07.000Z
2021-09-24T15:10:07.000Z
#include<iostream> using namespace std; int main() { int a=10; int*ptr= &a; int **ptr2=&(ptr); cout<<**ptr2<<endl; return 0; }
12.454545
21
0.591241
sahilnegi30
c13bc2a7030525a489a99f1f82b5a6f5810a679a
3,032
cpp
C++
Source/System/Math/Primitive/ConvexHull3D/Tetrahedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Math/Primitive/ConvexHull3D/Tetrahedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Math/Primitive/ConvexHull3D/Tetrahedron.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "Tetrahedron.hpp" #include "../../Utility/Utility.hpp" #include "../../../Core/Utility/CoreDef.hpp" #include "../../../Graphics/Utility/PrimitiveRenderer.hpp" namespace Engine5 { Tetrahedron::Tetrahedron() { type = ePrimitiveType::Tetrahedron; } Tetrahedron::~Tetrahedron() { } void Tetrahedron::Initialize() { SetUnit(); } void Tetrahedron::Shutdown() { } void Tetrahedron::SetUnit() { vertices[0] = Math::Vector3::ORIGIN; vertices[1] = Math::Vector3::X_AXIS; vertices[2] = Math::Vector3::Y_AXIS; vertices[3] = Math::Vector3::Z_AXIS; } Vector3 Tetrahedron::Support(const Vector3& direction) { Real p = Math::REAL_NEGATIVE_MAX; Vector3 result; for (size_t i = 0; i < 4; ++i) { Real projection = vertices[i].DotProduct(direction); if (projection > p) { result = vertices[i]; p = projection; } } return result; } bool Tetrahedron::TestRayIntersection(const Ray& local_ray, Real& minimum_t, Real& maximum_t) const { minimum_t = local_ray.direction.DotProduct(local_ray.position); maximum_t = -1.0f; return false; } Vector3 Tetrahedron::GetNormal(const Vector3& local_point_on_primitive) { return local_point_on_primitive; } void Tetrahedron::DrawPrimitive(PrimitiveRenderer* renderer, eRenderingMode mode, const Color& color) const { I32 index = static_cast<I32>(renderer->VerticesSize(mode)); renderer->ReserveVertices(4, mode); Vector3 world_vertices[4]; std::memcpy(world_vertices, vertices, sizeof(vertices)); for (auto& vertex : world_vertices) { //local space to world space vertex = orientation.Rotate(vertex); vertex += position; //push to renderer renderer->PushVertex(vertex, mode, color); } //add indices if (mode == eRenderingMode::Dot) { for (I32 i = 0; i < 4; ++i) { renderer->PushIndex(index + i, mode); } } else if (mode == eRenderingMode::Line) { renderer->PushLineIndices(index, index + 1); renderer->PushLineIndices(index, index + 2); renderer->PushLineIndices(index, index + 3); renderer->PushLineIndices(index + 1, index + 2); renderer->PushLineIndices(index + 2, index + 3); renderer->PushLineIndices(index + 3, index + 1); } else if (mode == eRenderingMode::Face) { renderer->PushFaceIndices(index, index + 1, index + 2); renderer->PushFaceIndices(index, index + 2, index + 3); renderer->PushFaceIndices(index, index + 3, index + 1); renderer->PushFaceIndices(index + 1, index + 2, index + 3); } } }
29.153846
111
0.559037
arian153
c14593bd6127ef6caddfd6e89e0ce834c0b82dd5
20,164
cxx
C++
EVE/EveBase/AliEveInit.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
EVE/EveBase/AliEveInit.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
EVE/EveBase/AliEveInit.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// // AliEveInit.cpp // xAliRoot // // Created by Jeremi Niedziela on 01/06/15. // // #include <AliEveInit.h> #include <AliEveTrackCounter.h> #include <AliEveEventManagerEditor.h> #include <AliEveMultiView.h> #include <AliEveMacroExecutor.h> #include <AliEveMacro.h> #include <AliEveGeomGentle.h> #include <AliEveDataSourceOffline.h> #include <AliEveEventManager.h> #include <AliCDBManager.h> #include <TGrid.h> #include <TROOT.h> #include <TInterpreter.h> #include <TEveWindowManager.h> #include <TGTab.h> #include <TPRegexp.h> #include <TFolder.h> #include <TSystemDirectory.h> #include <TGFileBrowser.h> #include <TEveMacro.h> #include <TEveBrowser.h> #include <TRegexp.h> #include <cstring> #include <iostream> #include <string> #include <vector> using namespace std; AliEveInit::AliEveInit(const TString& path ,AliEveEventManager::EDataSource defaultDataSource,bool storageManager) : fPath(path) { //============================================================================== // Reading preferences from config file //============================================================================== TEnv settings; GetConfig(&settings); bool autoloadEvents = settings.GetValue("events.autoload.set",false); // set autoload by default bool fullscreen = settings.GetValue("fullscreen.mode",false); // hide left and bottom tabs TString ocdbStorage = settings.GetValue("OCDB.default.path","local://$ALICE_ROOT/../src/OCDB");// default path to OCDB Info("AliEveInit","\n\nOCDB path:%s\n\n",ocdbStorage.Data()); //============================================================================== // Event Manager and different data sources //============================================================================== AliEveEventManager *man = new AliEveEventManager(defaultDataSource); AliEveEventManager::SetCdbUri(ocdbStorage); if (gSystem->Getenv("ALICE_ROOT") != 0) { gInterpreter->AddIncludePath(Form("%s/MUON", gSystem->Getenv("ALICE_ROOT"))); gInterpreter->AddIncludePath(Form("%s/MUON/mapping", gSystem->Getenv("ALICE_ROOT"))); } AliEveDataSourceOffline *dataSourceOffline = (AliEveDataSourceOffline*)man->GetDataSourceOffline(); ImportMacros(); Init(); TEveUtil::AssertMacro("VizDB_scan.C"); TEveBrowser *browser = gEve->GetBrowser(); browser->ShowCloseTab(kFALSE); //============================================================================== // Geometry, scenes, projections and viewers //============================================================================== AliEveMultiView *mv = new AliEveMultiView(); AliEveGeomGentle *geomGentle = new AliEveGeomGentle(); // read all files with names matching "geom_list_XYZ.txt" vector<string> detectorsList; string geomPath = settings.GetValue("simple.geom.path","${ALICE_ROOT}/EVE/resources/geometry/run2/"); string alirootBasePath = gSystem->Getenv("ALICE_ROOT"); size_t alirootPos = geomPath.find("${ALICE_ROOT}"); if(alirootPos != string::npos){ geomPath.replace(alirootPos,alirootPos+13,alirootBasePath); } TSystemDirectory dir(geomPath.c_str(),geomPath.c_str()); TList *files = dir.GetListOfFiles(); if (files) { TRegexp e("simple_geom_[A-Z,0-9][A-Z,0-9][A-Z,0-9].root"); TRegexp e2("[A-Z,0-9][A-Z,0-9][A-Z,0-9]"); TSystemFile *file; TString fname; TIter next(files); while ((file=(TSystemFile*)next())) { fname = file->GetName(); if(fname.Contains(e)) { TString detName = fname(e2); detName.Resize(3); detectorsList.push_back(detName.Data()); } } } else{ cout<<"\n\nAliEveInit -- geometry files not found!!!"<<endl; cout<<"Searched directory was:"<<endl; dir.Print(); } for(int i=0;i<detectorsList.size();i++) { if(settings.GetValue(Form("%s.draw",detectorsList[i].c_str()), true)) { if(detectorsList[i]=="TPC" || detectorsList[i]=="MCH") { // don't load MUON and standard TPC to R-Phi view mv->InitSimpleGeom(geomGentle->GetSimpleGeom((char*)detectorsList[i].c_str()),true,false); } else if(detectorsList[i]=="RPH") { // special TPC geom from R-Phi view mv->InitSimpleGeom(geomGentle->GetSimpleGeom("RPH"),false,true,false); } else { mv->InitSimpleGeom(geomGentle->GetSimpleGeom((char*)detectorsList[i].c_str())); } } } AddMacros(); //============================================================================== // Additional GUI components //============================================================================== TEveWindowSlot *slot = TEveWindow::CreateWindowInTab(browser->GetTabRight()); // QA viewer /* slot = TEveWindow::CreateWindowInTab(browser->GetTabRight()); slot->StartEmbedding(); new AliQAHistViewer(gClient->GetRoot(), 600, 400, kTRUE); slot->StopEmbedding("QA histograms"); */ // browser->GetTabRight()->SetTab(1); browser->StartEmbedding(TRootBrowser::kBottom); new AliEveEventManagerWindow(man,storageManager,defaultDataSource); browser->StopEmbedding("EventCtrl"); slot = TEveWindow::CreateWindowInTab(browser->GetTabRight()); TEveWindowTab *store_tab = slot->MakeTab(); store_tab->SetElementNameTitle("WindowStore", "Undocked windows whose previous container is not known\n" "are placed here when the main-frame is closed."); gEve->GetWindowManager()->SetDefaultContainer(store_tab); //============================================================================== // AliEve objects - global tools //============================================================================== AliEveTrackCounter* g_trkcnt = new AliEveTrackCounter("Primary Counter"); gEve->AddToListTree(g_trkcnt, kFALSE); //============================================================================== // Final stuff //============================================================================== // A refresh to show proper window. // gEve->GetViewers()->SwitchColorSet(); browser->MoveResize(0, 0, gClient->GetDisplayWidth(),gClient->GetDisplayHeight() - 32); gEve->Redraw3D(true); gSystem->ProcessEvents(); // man->GotoEvent(0); gEve->EditElement(g_trkcnt); gEve->Redraw3D(); // move and rotate sub-views browser->GetTabRight()->SetTab(1); TGLViewer *glv1 = mv->Get3DView()->GetGLViewer(); TGLViewer *glv2 = mv->GetRPhiView()->GetGLViewer(); TGLViewer *glv3 = mv->GetRhoZView()->GetGLViewer(); glv1->CurrentCamera().RotateRad(-0.4, 1.0); glv2->CurrentCamera().Dolly(1, kFALSE, kFALSE); glv3->CurrentCamera().Dolly(1, kFALSE, kFALSE); // Fullscreen if(fullscreen){ ((TGWindow*)gEve->GetBrowser()->GetTabLeft()->GetParent())->Resize(1,0); ((TGWindow*)gEve->GetBrowser()->GetTabBottom()->GetParent())->Resize(0,1); gEve->GetBrowser()->Layout(); } gEve->FullRedraw3D(); gSystem->ProcessEvents(); gEve->Redraw3D(true); man->SetAutoLoad(autoloadEvents);// set autoload by default if(defaultDataSource == AliEveEventManager::kSourceOffline){ if(settings.GetValue("momentum.histograms.all.events.show",false)) { ((AliEveDataSourceOffline*)man->GetDataSourceOffline())->GotoEvent(0); man->GetMomentumHistogramsDrawer()->DrawAllEvents(); } } } void AliEveInit::Init() { Info("AliEveInit","Adding standard macros"); AliEveDataSourceOffline *dataSource = (AliEveDataSourceOffline*)AliEveEventManager::Instance()->GetDataSourceOffline(); // Open event if (fPath.BeginsWith("alien:")) { if (gGrid != 0) { Info("AliEveInit::Init()", "TGrid already initializied. Skiping checks and initialization."); } else { Info("AliEveInit::Init()", "AliEn requested - connecting."); if (gSystem->Getenv("GSHELL_ROOT") == 0) { Error("AliEveInit::Init()", "AliEn environment not initialized. Aborting."); gSystem->Exit(1); } if (TGrid::Connect("alien") == 0) { Error("AliEveInit::Init()", "TGrid::Connect() failed. Aborting."); gSystem->Exit(1); } } } cout<<"Opening event -1 from "<<fPath.Data()<<endl; gEve->AddEvent(AliEveEventManager::Instance()); } void AliEveInit::AddMacros() { //============================================================================== // Registration of per-event macros //============================================================================== // check which macros are available TEnv settings; GetConfig(&settings); vector<string> detectorsList; TSystemDirectory dir(Form("%s/../src/EVE/macros/data/",gSystem->Getenv("ALICE_ROOT")), Form("%s/../src/EVE/macros/data/",gSystem->Getenv("ALICE_ROOT"))); TList *files = dir.GetListOfFiles(); if (files) { TRegexp e("data_vis_[A-Z,0-9][A-Z,0-9][A-Z,0-9].C"); TRegexp e2("[A-Z,0-9][A-Z,0-9][A-Z,0-9]"); TSystemFile *file; TString fname; TIter next(files); while ((file=(TSystemFile*)next())) { fname = file->GetName(); if(fname.Contains(e)) { TString detName = fname(e2); detName.Resize(3); detectorsList.push_back(detName.Data()); } } } AliEveMacroExecutor *exec = AliEveEventManager::Instance()->GetExecutor(); exec->RemoveMacros(); // remove all old macros for(int i=0;i<detectorsList.size();i++) { const char *detector = detectorsList[i].c_str(); cout<<"Adding macros for "<<detector<<endl; // add macro for hits if(settings.GetValue(Form("%s.hits",detector),false)) { exec->AddMacro(new AliEveMacro( Form("Hits %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kHits" )); } // add macro for digits if(settings.GetValue(Form("%s.digits",detector),false)) { exec->AddMacro(new AliEveMacro( Form("Digits %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kDigits" )); } // add macro for raw data if(settings.GetValue(Form("%s.raw",detector),false)) { exec->AddMacro(new AliEveMacro( Form("Raw %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kRaw" )); } // add macro for raw data if(settings.GetValue(Form("%s.clusters",detector),false)) { exec->AddMacro(new AliEveMacro( Form("Clusters %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kClusters" )); } // add macro for ESD if(settings.GetValue(Form("%s.esd",detector),false)) { exec->AddMacro(new AliEveMacro( Form("ESD %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kESD" )); } // add macro for AOD if(settings.GetValue(Form("%s.aod",detector),false)) { exec->AddMacro(new AliEveMacro( Form("AOD %s",detector), Form("data_vis_%s.C",detector), Form("data_vis_%s",detector), "AliEveEventManager::kAOD" )); } } // what's below should be removed bool showMuon = settings.GetValue("MUON.show", true); // show MUON's geom bool showEMCal = settings.GetValue("EMCal.show", false); // show EMCal and PHOS histograms bool drawClusters = settings.GetValue("clusters.show",false); // show clusters bool drawRawData = settings.GetValue("rawData.show",false); // show raw data bool drawHits = settings.GetValue("hits.show",false); // show hits bool drawDigits = settings.GetValue("digits.show",false); // show digits bool drawAD = settings.GetValue("AD.show",false); // show AD hits if(drawHits) { exec->AddMacro(new AliEveMacro("SIM Hits ITS", "its_hits.C", "its_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits TPC", "tpc_hits.C", "tpc_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits T0", "t0_hits.C", "t0_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits FMD", "fmd_hits.C", "fmd_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits ACORDE", "acorde_hits.C", "acorde_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits EMCAL", "emcal_hits.C", "emcal_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits TOF", "tof_hits.C", "tof_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits TRD", "trd_hits.C", "trd_hits", "")); exec->AddMacro(new AliEveMacro("SIM Hits VZERO", "vzero_hits.C", "vzero_hits", "")); } if(drawDigits){ exec->AddMacro(new AliEveMacro("DIG ITS", "its_digits.C", "its_digits", "")); exec->AddMacro(new AliEveMacro("DIG TPC", "tpc_digits.C", "tpc_digits", "")); exec->AddMacro(new AliEveMacro("DIG TOF", "tof_digits.C", "tof_digits", "")); exec->AddMacro(new AliEveMacro("DIG HMPID", "hmpid_digits.C","hmpid_digits","")); exec->AddMacro(new AliEveMacro("DIG FMD", "fmd_digits.C", "fmd_digits", "")); } if(drawRawData) { exec->AddMacro(new AliEveMacro("RAW ITS", "its_raw.C", "its_raw", "")); exec->AddMacro(new AliEveMacro("RAW TPC", "tpc_raw.C", "tpc_raw", "")); exec->AddMacro(new AliEveMacro("RAW TOF", "tof_raw.C", "tof_raw", "")); exec->AddMacro(new AliEveMacro("RAW HMPID", "hmpid_raw.C", "hmpid_raw", "")); exec->AddMacro(new AliEveMacro("RAW T0", "t0_raw.C", "t0_raw", "")); exec->AddMacro(new AliEveMacro("RAW FMD", "fmd_raw.C", "fmd_raw", "")); exec->AddMacro(new AliEveMacro("RAW VZERO", "vzero_raw.C", "vzero_raw", "")); exec->AddMacro(new AliEveMacro("RAW ACORDE", "acorde_raw.C", "acorde_raw", "")); } if(drawClusters) { exec->AddMacro(new AliEveMacro("REC Clusters ITS", "its_clusters.C", "its_clusters","")); exec->AddMacro(new AliEveMacro("REC Clusters TPC", "tpc_clusters.C", "tpc_clusters","")); exec->AddMacro(new AliEveMacro("REC Clusters TRD", "trd_clusters.C", "trd_clusters","")); exec->AddMacro(new AliEveMacro("REC Clusters TOF", "tof_clusters.C", "tof_clusters","")); exec->AddMacro(new AliEveMacro("REC Clusters HMPID", "hmpid_clusters.C","hmpid_clusters","")); exec->AddMacro(new AliEveMacro("REC Clusters PHOS", "phos_clusters.C","phos_clusters","")); } if (showMuon) { if(drawRawData){ exec->AddMacro(new AliEveMacro("RAW MUON", "muon_raw.C", "muon_raw", "")); } if(drawDigits){ exec->AddMacro(new AliEveMacro("DIG MUON", "muon_digits.C", "muon_digits", "")); } if(drawClusters){ exec->AddMacro(new AliEveMacro("REC Clusters MUON", "muon_clusters.C", "muon_clusters", "")); } } // exec->AddMacro(new AliEveMacro("ESD AD", "ad_esd.C", "ad_esd", "", drawAD)); if(showEMCal){ exec->AddMacro(new AliEveMacro("ESD EMCal", "emcal_esdclustercells.C", "emcal_esdclustercells", "")); } } void AliEveInit::ImportMacros() { // Put macros in the list of browsables, add a macro browser to // top-level GUI. TString hack = gSystem->pwd(); // Problem with TGFileBrowser cding TString macdir("$(ALICE_ROOT)/EVE/macros/data"); gSystem->ExpandPathName(macdir); TFolder* f = gEve->GetMacroFolder(); void* dirhandle = gSystem->OpenDirectory(macdir.Data()); if (dirhandle != 0) { const char* filename; TPMERegexp re("\\.C$"); TObjArray names; while ((filename = gSystem->GetDirEntry(dirhandle)) != 0) { if (re.Match(filename)) names.AddLast(new TObjString(filename)); } names.Sort(); for (Int_t ii=0; ii<names.GetEntries(); ++ii) { TObjString * si = (TObjString*) names.At(ii); f->Add(new TEveMacro(Form("%s/%s", macdir.Data(), (si->GetString()).Data()))); } } gSystem->FreeDirectory(dirhandle); gROOT->GetListOfBrowsables()->Add(new TSystemDirectory(macdir.Data(), macdir.Data())); { TEveBrowser *br = gEve->GetBrowser(); TGFileBrowser *fb = 0; fb = br->GetFileBrowser(); fb->GotoDir(macdir); { br->StartEmbedding(0); fb = br->MakeFileBrowser(); fb->BrowseObj(f); fb->Show(); br->StopEmbedding(); br->SetTabTitle("Macros", 0); br->SetTab(0, 0); } } gSystem->cd(hack); } void AliEveInit::GetConfig(TEnv *settings) { TEveException kEH("AliEveInit::GetConfig"); if(settings->ReadFile(Form("%s/.eve_config",gSystem->Getenv("HOME")), kEnvUser) < 0) { Warning(kEH," could not find .eve_config in home directory! Trying ~/eve_config"); if(settings->ReadFile(Form("%s/eve_config",gSystem->Getenv("HOME")), kEnvUser) < 0) { Warning(kEH," could not find eve_config in home directory! Trying in $ALICE_ROOT/EVE/EveBase/"); if(settings->ReadFile(Form("%s/EVE/EveBase/eve_config",gSystem->Getenv("ALICE_ROOT")), kEnvUser) < 0) { Error(kEH,"could not find eve_config file!."); exit(0); } else{ Info(kEH,"Read config from standard location"); } } else{ Info(kEH,"Read config from home directory"); } } else{ Info(kEH,"Read config from home directory"); } }
38.480916
124
0.514531
shahor02
c147511b9f2510e2687fe545638b765482ff8e2d
2,531
cpp
C++
src/util/ScanAccumulator.cpp
jerlomy4ever/568_final_project
5f75d673d0236548345a10d8a2c54d8d8971ea92
[ "MIT" ]
644
2019-07-26T18:53:13.000Z
2022-03-31T14:37:17.000Z
src/util/ScanAccumulator.cpp
topcomma/SuMa
683f9bbb7298f8f2d1c6d8891362bba3ee8c6c54
[ "MIT" ]
54
2019-08-20T02:46:31.000Z
2022-03-30T13:34:37.000Z
src/util/ScanAccumulator.cpp
topcomma/SuMa
683f9bbb7298f8f2d1c6d8891362bba3ee8c6c54
[ "MIT" ]
176
2019-10-19T04:57:02.000Z
2022-03-30T05:52:00.000Z
#include "ScanAccumulator.h" using namespace rv; using namespace glow; ScanAccumulator::ScanAccumulator(uint32_t history_size, uint32_t max_points) : vbo_(BufferTarget::ARRAY_BUFFER, BufferUsage::DYNAMIC_DRAW), capacity_(history_size), max_size_(max_points) { vbo_.resize(history_size * max_points); // allocate memory & set size accordingly... offsets_.resize(history_size, 0); poses_.resize(history_size); sizes_.resize(history_size, 0); timestamps_.resize(history_size, -1); std::fill(timestamps_.begin(), timestamps_.end(), -1); offsets_[0] = 0; sizes_[0] = 0; for (uint32_t i = 1; i < capacity_; ++i) { offsets_[i] = offsets_[i - 1] + max_points; sizes_[i] = 0; } } void ScanAccumulator::clear() { currentIdx_ = -1; size_ = 0; std::fill(timestamps_.begin(), timestamps_.end(), -1); } uint32_t ScanAccumulator::size() const { return size_; } uint32_t ScanAccumulator::capacity() const { return capacity_; } uint32_t ScanAccumulator::offset(uint32_t idx) const { int32_t newIdx = currentIdx_ - idx; if (newIdx < 0) newIdx = capacity_ + newIdx; return offsets_[newIdx]; } const Eigen::Matrix4f& ScanAccumulator::pose(uint32_t idx) const { int32_t newIdx = currentIdx_ - idx; if (newIdx < 0) newIdx = capacity_ + newIdx; return poses_[newIdx]; } uint32_t ScanAccumulator::timestamp(uint32_t idx) const { int32_t newIdx = currentIdx_ - idx; if (newIdx < 0) newIdx = capacity_ + newIdx; return timestamps_[newIdx]; } uint32_t ScanAccumulator::size(uint32_t idx) const { int32_t newIdx = currentIdx_ - idx; if (newIdx < 0) newIdx = capacity_ + newIdx; return sizes_[newIdx]; } glow::GlBuffer<rv::Point3f>& ScanAccumulator::getVBO() { return vbo_; } void ScanAccumulator::insert(uint32_t timestamp, const Eigen::Matrix4f& pose, const std::vector<rv::Point3f>& points) { currentIdx_ += 1; if (uint32_t(currentIdx_) >= capacity_) currentIdx_ = 0; timestamps_[currentIdx_] = timestamp; poses_[currentIdx_] = pose; sizes_[currentIdx_] = std::min(max_size_, (uint32_t)points.size()); vbo_.replace(offsets_[currentIdx_], &points[0], sizes_[currentIdx_]); if (size_ < capacity_) size_ += 1; } std::vector<Eigen::Matrix4f>& ScanAccumulator::getPoses() { return poses_; } const std::vector<Eigen::Matrix4f>& ScanAccumulator::getPoses() const { return poses_; } std::vector<int32_t>& ScanAccumulator::getTimestamps() { return timestamps_; } const std::vector<int32_t>& ScanAccumulator::getTimestamps() const { return timestamps_; }
26.642105
119
0.713552
jerlomy4ever
c14b2008863371b7efe6e08d2d86f980e4a37485
2,072
hpp
C++
TabGraph/include/Property.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-08-28T09:35:18.000Z
2020-08-28T09:35:18.000Z
TabGraph/include/Property.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
null
null
null
TabGraph/include/Property.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-10-08T11:21:13.000Z
2020-10-08T11:21:13.000Z
#pragma once #include "Event/Signal.hpp" /** Use this to declare a new property */ #define PROPERTY(type, var, ...) \ public: \ Signal<type> var##Changed; \ type Get##var() const \ { \ return _##var; \ } \ void Set##var(type val) \ { \ if (val != _##var) { \ _##var = val; \ var##Changed(val); \ } \ } \ \ private: \ type _##var { __VA_ARGS__ }; #define READONLYPROPERTY(type, var, ...) \ public: \ Signal<type> var##Changed; \ type Get##var() const \ { \ return _##var; \ } \ \ protected: \ void _Set##var(type val) \ { \ if (val != _##var) { \ _##var = val; \ var##Changed(val); \ } \ } \ private: \ type _##var { __VA_ARGS__ }; #define PRIVATEPROPERTY(type, var, ...) \ private: \ Signal<type> var##Changed; \ type _Get##var() const \ { \ return _##var; \ } \ void _Set##var(type val) \ { \ bool changed = val != _##var; \ _##var = val; \ if (changed) \ var##Changed(val); \ } \ type _##var { __VA_ARGS__ };
36.350877
43
0.255792
Gpinchon
c14cc60b0db93196eed95d07fbfc868bc107d3bb
14,706
hpp
C++
source/lib/ls_common.hpp
LuisCM/lavascript
415b19fd95b0985241e1e5ebe68a925141ec17ea
[ "MIT" ]
null
null
null
source/lib/ls_common.hpp
LuisCM/lavascript
415b19fd95b0985241e1e5ebe68a925141ec17ea
[ "MIT" ]
null
null
null
source/lib/ls_common.hpp
LuisCM/lavascript
415b19fd95b0985241e1e5ebe68a925141ec17ea
[ "MIT" ]
null
null
null
// ================================================================================================ // -*- C++ -*- // File: ls_common.hpp // Author: LuisCM // Created on: 24/08/2001 // Brief: Bison Parser and Flex Lexer interface header and other common forward declarations. // ================================================================================================ #ifndef LAVASCRIPT_COMMON_HPP #define LAVASCRIPT_COMMON_HPP #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <utility> #include <string> #include <memory> #include <exception> #include <unordered_map> #include "ls_build_config.hpp" #include "ls_output.hpp" #ifndef INC_LEXER #ifdef LAVASCRIPT_USE_LOCAL_FLEX_LEXER_H // You can fall back to the local built-in copy of FlexLexer.h, // but this will not work if there's a version mismatch between // the generated code and the local copy. Only use this if you're // not generating the Lexer source yourself. #include "generated/FlexLexerLocal.h" #else // !LAVASCRIPT_USE_LOCAL_FLEX_LEXER_H // This header file is a built-in that comes bundled with the Flex install. #include <FlexLexer.h> #endif // LAVASCRIPT_USE_LOCAL_FLEX_LEXER_H #endif // INC_LEXER namespace lavascript { // ======================================================== // Some forward declarations for the Lexer & Parser: // ======================================================== struct Symbol; struct SyntaxTreeNode; class LSSymbolTable; class LSSyntaxTree; class LSVarInfoTable; class LSImportTable; class Parser; class Lexer; class LSCompiler; class LSVM; // ======================================================== // Shorthand type aliases: // ======================================================== using Int8 = std::int8_t; using Int16 = std::int16_t; using Int32 = std::int32_t; using Int64 = std::int64_t; using UInt8 = std::uint8_t; using UInt16 = std::uint16_t; using UInt32 = std::uint32_t; using UInt64 = std::uint64_t; using Float32 = float; using Float64 = double; static_assert(sizeof(Int8) == 1, "Expected 8-bits integer!"); static_assert(sizeof(Int16) == 2, "Expected 16-bits integer!"); static_assert(sizeof(Int32) == 4, "Expected 32-bits integer!"); static_assert(sizeof(Int64) == 8, "Expected 64-bits integer!"); static_assert(sizeof(UInt8) == 1, "Expected 8-bits integer!"); static_assert(sizeof(UInt16) == 2, "Expected 16-bits integer!"); static_assert(sizeof(UInt32) == 4, "Expected 32-bits integer!"); static_assert(sizeof(UInt64) == 8, "Expected 64-bits integer!"); static_assert(sizeof(Float32) == 4, "Expected 32-bits float!"); static_assert(sizeof(Float64) == 8, "Expected 64-bits float!"); // ======================================================== // Parser/Lexer aux types: // ======================================================== // The type used by Bison to pass data around. union SemanticVal { const Symbol * asSymbol; SyntaxTreeNode * asSTNode; }; // Bison needs this #define. #define YYSTYPE SemanticVal // Just a bunch of state the Parser and Lexer share. // Also a convenient way of adding our own user-supplied // data to the Bison-generated Parser class without // resorting to globals. struct ParseContext final { // Internal parse/compile states: SemanticVal * yylval = nullptr; Lexer * lexer = nullptr; Parser * parser = nullptr; LSSymbolTable * symTable = nullptr; LSSyntaxTree * syntTree = nullptr; LSVarInfoTable * varInfo = nullptr; LSVM * vm = nullptr; LSCompiler * compiler = nullptr; std::string * currText = nullptr; // [optional] const std::string * srcFile = nullptr; // [optional] SyntaxTreeNode * treeRoot = nullptr; LSImportTable * importTable = nullptr; int importDepth = 0; // Parser/compiler flags: bool debugMode = true; bool enableWarnings = true; }; // ======================================================== // The Flex Lexer front-end: // ======================================================== // We inherit from yyFlexLexer to be able to declare the // ParseContext member, which will be needed to pass some // information around that the Parser and Lexer must share. class Lexer final : public yyFlexLexer { public: // Not copyable. Lexer(const Lexer &) = delete; Lexer & operator = (const Lexer &) = delete; Lexer(ParseContext & parseCtx, std::istream * source) : yyFlexLexer { source } , ctx { parseCtx } { } ParseContext & ctx; // Methods defined in lexer.lxx: void lexOnInput(char * buf, int & result, int maxSize); void lexOnError(const char * message); void lexOnSingleLineComment(); void lexOnMultiLineComment(); void lexOnNewLine(); void lexOnIdentifier(); void lexOnStrLiteral(); void lexOnIntLiteral(); void lexOnFloatLiteral(); void lexOnBoolLiteral(); }; // This is the function called by the Bison Parser to get a token from the Lexer. // Bison requires it to be named yylex(), but we can control which parameters it takes. int yylex(SemanticVal * yylval, ParseContext & ctx); // ======================================================== // Exceptions thrown by the compiler and runtime: // ======================================================== class LSBaseException : public std::exception { public: explicit LSBaseException(const char * message); explicit LSBaseException(const std::string & message); virtual const char * what() const noexcept override; virtual ~LSBaseException(); private: // Sized buffer to avoid allocating extra memory with strings. static constexpr int MaxMessageLen = 1024; char messageBuffer[MaxMessageLen]; }; struct LexerException final : public LSBaseException { using LSBaseException::LSBaseException; }; struct ParserException final : public LSBaseException { using LSBaseException::LSBaseException; }; struct CompilerException final : public LSBaseException { using LSBaseException::LSBaseException; }; struct RuntimeException final : public LSBaseException { using LSBaseException::LSBaseException; }; struct ScriptException final : public LSBaseException { using LSBaseException::LSBaseException; }; // ======================================================== // Miscellaneous utilities: // ======================================================== struct Range final { Int32 begin; Int32 end; }; inline int rangeLength(const Range r) noexcept { return std::abs(r.end - r.begin); } template<typename T, UInt32 N> constexpr UInt32 arrayLength(const T (&)[N]) noexcept { return N; } // Fast 32-bits hash of a null-terminated C string: constexpr UInt32 NullHash = 0; UInt32 hashCString(const char * cstr); UInt32 hashCString(const char * cstr, UInt32 count); // Portable string compare ignoring character case. int compareCStringsNoCase(const char * s1, const char * s2, UInt32 count = ~0u); // Remove insignificant trailing zeros from a float, possibly also removing the '.' std::string trimTrailingFloatZeros(std::string trimmed); // Replaces non-printable escape chars with the printable equivalent (i.e.: an actual "\n", for '\n' char). std::string unescapeString(const char * escaped); // Replaces escape sequences by the equivalent character code (i.e. a "\n" by the '\n' character). // Also strips the first and last double-quotes, if any. The Lexer needs that for string literals. std::string escapeString(const char * unescaped); // Temporary formatting buffer used internally is fixed to 2048 chars, so longer strings will get truncated! #if defined(__GNUC__) || defined(__clang__) std::string strPrintF(const char * format, ...) __attribute__((format(printf, 1, 2))); #else // !__GNUC__ and !__clang__ std::string strPrintF(const char * format, ...); #endif // __GNUC__ or __clang__ // ------------------------------------ struct CStrHasher final { std::size_t operator()(const char * cstr) const { return hashCString(cstr); } }; struct CStrCmpEqual final { bool operator()(const char * a, const char * b) const { LAVASCRIPT_ASSERT(a != nullptr && b != nullptr); if (a == b) // Optimize for same memory. { return true; } return std::strcmp(a, b) == 0; } }; template<typename T> using HashTableCStr = std::unordered_map<const char *, T, CStrHasher, CStrCmpEqual>; template<typename Key, typename Val> using HashTable = std::unordered_map<Key, Val>; // ======================================================== // toString() helpers: // ======================================================== inline std::string toString(const bool value) { return value ? "true" : "false"; } inline std::string toString(const char * value) { return (value != nullptr) ? value : "null"; } inline std::string toString(const Int8 value) { return std::to_string(value); } inline std::string toString(const Int16 value) { return std::to_string(value); } inline std::string toString(const Int32 value) { return std::to_string(value); } inline std::string toString(const Int64 value) { return std::to_string(value); } inline std::string toString(const UInt8 value) { return std::to_string(value); } inline std::string toString(const UInt16 value) { return std::to_string(value); } inline std::string toString(const UInt32 value) { return std::to_string(value); } inline std::string toString(const UInt64 value) { return std::to_string(value); } inline std::string toString(const Float32 value) { return trimTrailingFloatZeros(std::to_string(value)); } inline std::string toString(const Float64 value) { return trimTrailingFloatZeros(std::to_string(value)); } // ======================================================== // Compile-time utilities: // ======================================================== namespace ct { // // Compile-time implementation of the one-at-a-time hash for strings: // https://en.wikipedia.org/wiki/Jenkins_hash_function // // Inspired by this CR question: // https://codereview.stackexchange.com/questions/93775/compile-time-sieve-of-eratosthenes // And: // http://stackoverflow.com/questions/28675727/using-crc32-algorithm-to-hash-string-at-compile-time // constexpr UInt32 addSHL(UInt32 h, UInt32 shift) { return h + (h << shift); } constexpr UInt32 addSHR(UInt32 h, UInt32 shift) { return h + (h >> shift); } constexpr UInt32 xorSHR(UInt32 h, UInt32 shift) { return h ^ (h >> shift); } constexpr UInt32 hashOATFinish(UInt32 h) { // h += (h << 3) // h ^= (h >> 11) // h += (h << 15) return addSHL(xorSHR(addSHL(h, 3), 11), 15); } constexpr UInt32 hashOATStep(UInt32 h, UInt32 c) { // h += c // h += (h << 10) // h ^= (h >> 6) return xorSHR(addSHL(h + c, 10), 6); } constexpr UInt32 hashOneAtATime(const char * cstr, UInt32 length, UInt32 h) { // hashOneAtATime is equivalent to the main hash loop unrolled recursively. return (length != 0) ? hashOneAtATime(cstr + 1, length - 1, hashOATStep(h, *cstr)) : hashOATFinish(h); } constexpr UInt32 lengthOfCString(const char * cstr) { return (*cstr != '\0') ? (lengthOfCString(cstr + 1) + 1) : 0; } constexpr UInt32 hashCString(const char * cstr) { return hashOneAtATime(cstr, lengthOfCString(cstr), 0); } // // Compile-time maximum of an arbitrary number of values: // template<typename T> constexpr T maxOf2(T a, T b) { return (a > b) ? a : b; } template<typename T> constexpr T maxOfN(T x) { return x; } template<typename T, typename... Args> constexpr T maxOfN(T x, Args... args) { return maxOf2(x, maxOfN(args...)); } } // namespace ct {} // ======================================================== // ConstRcString => Simple reference counted string type: // ======================================================== struct ConstRcString final { const char * chars; // Immutable null-terminated C-string. UInt32 length; // Length in characters, not including the null terminator. UInt32 hashVal; // Precomputed hashCString() since the string is immutable. UInt32 refCount; // Current reference count. Deleted when it drops to zero. }; // The const Ref Counted String has a precomputed hash of the string, so equal comparison // is constant-time. The string gets deallocated when the last reference is released. ConstRcString * newConstRcString(const char * cstr, UInt32 maxCharsToCopy); ConstRcString * newConstRcString(const char * cstr); ConstRcString * addRcStringRef(ConstRcString * rstr); void releaseRcString(ConstRcString * rstr); // ------------------------------------ inline int cmpRcStrings(const ConstRcString * a, const ConstRcString * b) { LAVASCRIPT_ASSERT(a != nullptr && b != nullptr); if (a->chars == b->chars) // Optimize for same memory { return 0; } if (a->length != b->length) // Optimize for strings of different length { return (a->length < b->length) ? -1 : +1; } return std::strncmp(a->chars, b->chars, a->length); } inline bool cmpRcStringsEqual(const ConstRcString * a, const ConstRcString * b) { LAVASCRIPT_ASSERT(a != nullptr && b != nullptr); return a->hashVal == b->hashVal; } inline bool isRcStringEmpty(const ConstRcString * rstr) noexcept { return rstr->length == 0; } inline bool isRcStringValid(const ConstRcString * rstr) noexcept { return rstr != nullptr && rstr->chars != nullptr && rstr->refCount != 0; } inline std::string toString(const ConstRcString * rstr) { return isRcStringValid(rstr) ? rstr->chars : "null"; } // ------------------------------------ struct CRcStrDeleter final { void operator()(ConstRcString * rstr) const { releaseRcString(rstr); } }; using ConstRcStrUPtr = std::unique_ptr<ConstRcString, CRcStrDeleter>; struct CRcStrHasher final { std::size_t operator()(const ConstRcString * rstr) const { return rstr->hashVal; } }; struct CRcStrCmpEqual final { bool operator()(const ConstRcString * a, const ConstRcString * b) const { return cmpRcStringsEqual(a, b); } }; template<typename T> using HashTableConstRcStr = std::unordered_map<ConstRcString *, T, CRcStrHasher, CRcStrCmpEqual>; // ------------------------------------ } // namespace lavascript {} // Parser has to be included here because it // will reference the Lexer and ParseContext. #ifndef INC_PARSER #include "generated/parser.hpp" #endif // INC_PARSER #endif // LAVASCRIPT_COMMON_HPP
33.422727
108
0.625731
LuisCM
c15086cf745c57f5f9a45945653b6ada5f00f241
1,594
hpp
C++
include/exemodel/wsserveree.hpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
2
2015-03-13T14:49:13.000Z
2017-09-18T12:38:59.000Z
include/exemodel/wsserveree.hpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
include/exemodel/wsserveree.hpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
#pragma once /** * \file exemodel/wswsserveree.hpp * \author Yi Qingliang <niqingliang2003@tom.com> */ #include <map> #include <functional> #include <libwebsockets.h> #include "exemodel/poller.hpp" namespace exemodel { class wsee; class wsserveree : public poller { public: typedef struct lws * cid; typedef std::function<int (cid, void *, size_t)> msg_cb_t; typedef std::function<int (cid, bool)> state_cb_t; public: explicit wsserveree() = default; virtual ~wsserveree(); public: int init(uint16_t port); public: int sendTextMessage(cid wsi, void * buffer, size_t length); int sendBinaryMessage(cid wsi, void * buffer, size_t length); void bind4TextMessage(msg_cb_t cb); void bind4BinaryMessage(msg_cb_t cb); void bind4StateChange(state_cb_t cb); void unbind(); private: wsserveree(const wsserveree & rhs) = delete; wsserveree & operator = (const wsserveree & rhs) = delete; private: void __addSp(cid wsi, struct lws_context *context, int fd, uint32_t events); void __delSp(cid wsi, int fd); void __modSp(cid wsi, int fd, uint32_t events); int __receiveTextMessage(cid wsi, void * data, size_t len); int __receiveBinaryMessage(cid wsi, void * data, size_t len); int __receiveConnectState(cid wsi, bool connectState); private: static struct lws_protocols protocols[]; static int callback_http( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); private: struct lws_context * m_pcontext; std::map<cid, wsee*> m_sps; msg_cb_t m_rxTextCallback; msg_cb_t m_rxBinaryCallback; state_cb_t m_stateChangeCallback; }; }
25.301587
77
0.747177
walkthetalk
c151572ec66449375e856f71275153abb88fb0be
2,340
cpp
C++
TG/bookcodes/ch3/ranktree.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
TG/bookcodes/ch3/ranktree.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
TG/bookcodes/ch3/ranktree.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// Rank Tree // Rujia Liu // 输入格式: // m 操作有m个 // 1 x 插入元素x // 2 x 删除元素x。如果成功,输入1,否则输出0 // 3 k 输出第k小元素。k=1为最小元素 // 4 x 输出值x的“名次”,即比x小的结点个数加1 #include<cstdlib> struct Node { Node *ch[2]; // 左右子树 int r; // 随机优先级 int v; // 值 int s; // 结点总数 Node(int v = 0):v(v) { ch[0] = ch[1] = NULL; r = rand(); s = 1; } int cmp(int x) const { if (x == v) return -1; return x < v ? 0 : 1; } void maintain() { s = 1; if(ch[0] != NULL) s += ch[0]->s; if(ch[1] != NULL) s += ch[1]->s; } }; void rotate(Node* &o, int d) { Node* k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o; o->maintain(); k->maintain(); o = k; } void insert(Node* &o, int x) { if(o == NULL) o = new Node(x); else { int d = (x < o->v ? 0 : 1); // 不要用cmp函数,因为可能会有相同结点 insert(o->ch[d], x); if(o->ch[d]->r > o->r) rotate(o, d^1); } o->maintain(); } Node* find(Node* o, int x) { if(o == NULL) return NULL; if(x == o->v) return o; return x < o->v ? find(o->ch[0], x) : find(o->ch[1], x); } // 要确保结点存在 void remove(Node* &o, int x) { int d = o->cmp(x); if(d == -1) { Node* u = o; if(o->ch[0] != NULL && o->ch[1] != NULL) { int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0); rotate(o, d2); remove(o->ch[d2], x); } else { if(o->ch[0] == NULL) o = o->ch[1]; else o = o->ch[0]; delete u; } } else remove(o->ch[d], x); if(o != NULL) o->maintain(); } int kth(Node* o, int k) { if(o == NULL || k <= 0 || k > o->s) return 0; int s = (o->ch[0] == NULL ? 0 : o->ch[0]->s); if(k == s+1) return o->v; else if(k <= s) return kth(o->ch[0], k); else return kth(o->ch[1], k-s-1); } // 在以o为根的子树中,值比x小的结点总数加1 int rank(Node* o, int x) { if(o == NULL) return 1; if(x <= o->v) return rank(o->ch[0], x); return rank(o->ch[1], x) + (o->ch[0] == NULL ? 0 : o->ch[0]->s) + 1; } #include<cstdio> const int INF = 1000000000; int main() { int m, c, v; Node* root = new Node(INF); while(scanf("%d", &m) == 1) { while(m--) { scanf("%d%d", &c, &v); if(c == 1) insert(root, v); else if(c == 2) { Node* o = find(root, v); printf("%d\n", o == NULL ? 0 : 1); if(o != NULL) remove(root, v); } else if(c == 3) printf("%d\n", kth(root, v)); else if(c == 4) printf("%d\n", rank(root, v)); } } return 0; }
22.941176
70
0.463248
Anyrainel
c151a69a36332420eafc9a19f4e2f68c9c7c3d7e
1,048
cpp
C++
algo/generate1.cpp
ppngiap/cppstdlib
1175c954cd5220c10146b1c80b5619e809cbad23
[ "MIT" ]
24
2016-09-22T08:27:04.000Z
2021-11-23T07:54:43.000Z
algo/generate1.cpp
ppngiap/cppstdlib
1175c954cd5220c10146b1c80b5619e809cbad23
[ "MIT" ]
null
null
null
algo/generate1.cpp
ppngiap/cppstdlib
1175c954cd5220c10146b1c80b5619e809cbad23
[ "MIT" ]
14
2016-11-23T05:31:48.000Z
2021-03-01T03:26:21.000Z
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <cstdlib> #include "algostuff.hpp" using namespace std; int main() { list<int> coll; // insert five random numbers generate_n (back_inserter(coll), // beginning of destination range 5, // count rand); // new value generator PRINT_ELEMENTS(coll); // overwrite with five new random numbers generate (coll.begin(), coll.end(), // destination range rand); // new value generator PRINT_ELEMENTS(coll); }
34.933333
75
0.637405
ppngiap
c1533c1eb5ff43fd932fac334f5c5a35806c60e2
1,967
cpp
C++
MyBlinkySketch/Shimmer.cpp
oddacon/BlinkyTape
f8cdee79ad599ac83d6371e5b5b999d15488009e
[ "MIT" ]
3
2018-04-16T09:13:38.000Z
2020-02-19T16:12:59.000Z
MyBlinkySketch/Shimmer.cpp
oddacon/BlinkyTape
f8cdee79ad599ac83d6371e5b5b999d15488009e
[ "MIT" ]
null
null
null
MyBlinkySketch/Shimmer.cpp
oddacon/BlinkyTape
f8cdee79ad599ac83d6371e5b5b999d15488009e
[ "MIT" ]
1
2020-02-19T16:13:05.000Z
2020-02-19T16:13:05.000Z
#include "Shimmer.h" #include "BlinkyTape.h" #include <Arduino.h> // Suggested colors // Shimmer(1, 1, 1) // White // Shimmer(1, 0.9352, 0.8340) // Light champagne // Shimmer(1, 0.9412, 0.8340) // Medium champagne const uint8_t ledMax = 255; const uint8_t stepSize = 5; const uint8_t valueDivisor = 4; void ShimmerDot::reset() { value = 0; maxValue = random(ledMax); resetDelay = random(ledMax/4); direction = 1; } void ShimmerDot::update() { if (direction == 1) { if (value/valueDivisor < maxValue) { int accelerated_step = 0; float unit = 0; unit = maxValue / (float)ledMax; accelerated_step = (float)stepSize + ((float)ledMax * (0.015 * (float)stepSize * unit * unit * unit * unit)); value += accelerated_step * valueDivisor; //error checking if (value/valueDivisor > ledMax) { value -= ledMax*valueDivisor; } } else { direction =0; } } else { if (value/valueDivisor > 0) { value = value - stepSize * valueDivisor; //error checking if (value < 0) { value = 0; } } else { if(resetDelay == 0) { reset(); } resetDelay--; } } } uint8_t ShimmerDot::getValue() { return ((value/valueDivisor) &0xFF); } void Shimmer::reset() { for (uint16_t i = 0; i < LED_COUNT; i++) { shimmerDots[i].reset(); } } Shimmer::Shimmer(float r, float g, float b) : color_temp_factor_r(r), color_temp_factor_g(g), color_temp_factor_b(b) { } void Shimmer::draw(CRGB* leds) { for (uint16_t i = 0; i < LED_COUNT; i++) { shimmerDots[i].update(); leds[i].r = (uint8_t)(shimmerDots[i].getValue() * color_temp_factor_r); leds[i].g = (uint8_t)(shimmerDots[i].getValue() * color_temp_factor_g); leds[i].b = (uint8_t)(shimmerDots[i].getValue() * color_temp_factor_b); } delay(30); // TODO: Don't place me here } // end shimmer_update_loop
20.925532
115
0.591764
oddacon
c154e6e644649bddd24a65d632592c95d304828d
7,966
cc
C++
table/merger.cc
tetcoin/rocksdb
2c1ef0692b393014613bdf4af623c9dc487f613c
[ "BSD-3-Clause" ]
null
null
null
table/merger.cc
tetcoin/rocksdb
2c1ef0692b393014613bdf4af623c9dc487f613c
[ "BSD-3-Clause" ]
null
null
null
table/merger.cc
tetcoin/rocksdb
2c1ef0692b393014613bdf4af623c9dc487f613c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "table/merger.h" #include "rocksdb/comparator.h" #include "rocksdb/iterator.h" #include "rocksdb/options.h" #include "table/iter_heap.h" #include "table/iterator_wrapper.h" #include "util/stop_watch.h" #include "util/perf_context_imp.h" #include <vector> namespace rocksdb { namespace { class MergingIterator : public Iterator { public: MergingIterator(Env* const env, const Comparator* comparator, Iterator** children, int n) : comparator_(comparator), children_(n), current_(nullptr), use_heap_(true), env_(env), direction_(kForward), maxHeap_(NewMaxIterHeap(comparator_)), minHeap_ (NewMinIterHeap(comparator_)) { for (int i = 0; i < n; i++) { children_[i].Set(children[i]); } for (auto& child : children_) { if (child.Valid()) { minHeap_.push(&child); } } } virtual ~MergingIterator() { } virtual bool Valid() const { return (current_ != nullptr); } virtual void SeekToFirst() { ClearHeaps(); for (auto& child : children_) { child.SeekToFirst(); if (child.Valid()) { minHeap_.push(&child); } } FindSmallest(); direction_ = kForward; } virtual void SeekToLast() { ClearHeaps(); for (auto& child : children_) { child.SeekToLast(); if (child.Valid()) { maxHeap_.push(&child); } } FindLargest(); direction_ = kReverse; } virtual void Seek(const Slice& target) { // Invalidate the heap. use_heap_ = false; IteratorWrapper* first_child = nullptr; StopWatchNano child_seek_timer(env_, false); StopWatchNano min_heap_timer(env_, false); for (auto& child : children_) { StartPerfTimer(&child_seek_timer); child.Seek(target); BumpPerfTime(&perf_context.seek_child_seek_time, &child_seek_timer); BumpPerfCount(&perf_context.seek_child_seek_count); if (child.Valid()) { // This child has valid key if (!use_heap_) { if (first_child == nullptr) { // It's the first child has valid key. Only put it int // current_. Now the values in the heap should be invalid. first_child = &child; } else { // We have more than one children with valid keys. Initialize // the heap and put the first child into the heap. StartPerfTimer(&min_heap_timer); ClearHeaps(); BumpPerfTime(&perf_context.seek_min_heap_time, &child_seek_timer); StartPerfTimer(&min_heap_timer); minHeap_.push(first_child); BumpPerfTime(&perf_context.seek_min_heap_time, &child_seek_timer); } } if (use_heap_) { StartPerfTimer(&min_heap_timer); minHeap_.push(&child); BumpPerfTime(&perf_context.seek_min_heap_time, &child_seek_timer); } } } if (use_heap_) { // If heap is valid, need to put the smallest key to curent_. StartPerfTimer(&min_heap_timer); FindSmallest(); BumpPerfTime(&perf_context.seek_min_heap_time, &child_seek_timer); } else { // The heap is not valid, then the current_ iterator is the first // one, or null if there is no first child. current_ = first_child; } direction_ = kForward; } virtual void Next() { assert(Valid()); // Ensure that all children are positioned after key(). // If we are moving in the forward direction, it is already // true for all of the non-current_ children since current_ is // the smallest child and key() == current_->key(). Otherwise, // we explicitly position the non-current_ children. if (direction_ != kForward) { ClearHeaps(); for (auto& child : children_) { if (&child != current_) { child.Seek(key()); if (child.Valid() && comparator_->Compare(key(), child.key()) == 0) { child.Next(); } if (child.Valid()) { minHeap_.push(&child); } } } direction_ = kForward; } // as the current points to the current record. move the iterator forward. // and if it is valid add it to the heap. current_->Next(); if (use_heap_) { if (current_->Valid()) { minHeap_.push(current_); } FindSmallest(); } else if (!current_->Valid()) { current_ = nullptr; } } virtual void Prev() { assert(Valid()); // Ensure that all children are positioned before key(). // If we are moving in the reverse direction, it is already // true for all of the non-current_ children since current_ is // the largest child and key() == current_->key(). Otherwise, // we explicitly position the non-current_ children. if (direction_ != kReverse) { ClearHeaps(); for (auto& child : children_) { if (&child != current_) { child.Seek(key()); if (child.Valid()) { // Child is at first entry >= key(). Step back one to be < key() child.Prev(); } else { // Child has no entries >= key(). Position at last entry. child.SeekToLast(); } if (child.Valid()) { maxHeap_.push(&child); } } } direction_ = kReverse; } current_->Prev(); if (current_->Valid()) { maxHeap_.push(current_); } FindLargest(); } virtual Slice key() const { assert(Valid()); return current_->key(); } virtual Slice value() const { assert(Valid()); return current_->value(); } virtual Status status() const { Status status; for (auto& child : children_) { status = child.status(); if (!status.ok()) { break; } } return status; } private: void FindSmallest(); void FindLargest(); void ClearHeaps(); const Comparator* comparator_; std::vector<IteratorWrapper> children_; IteratorWrapper* current_; // If the value is true, both of iterators in the heap and current_ // contain valid rows. If it is false, only current_ can possibly contain // valid rows. // This flag is always true for reverse direction, as we always use heap for // the reverse iterating case. bool use_heap_; Env* const env_; // Which direction is the iterator moving? enum Direction { kForward, kReverse }; Direction direction_; MaxIterHeap maxHeap_; MinIterHeap minHeap_; }; void MergingIterator::FindSmallest() { assert(use_heap_); if (minHeap_.empty()) { current_ = nullptr; } else { current_ = minHeap_.top(); assert(current_->Valid()); minHeap_.pop(); } } void MergingIterator::FindLargest() { assert(use_heap_); if (maxHeap_.empty()) { current_ = nullptr; } else { current_ = maxHeap_.top(); assert(current_->Valid()); maxHeap_.pop(); } } void MergingIterator::ClearHeaps() { use_heap_ = true; maxHeap_ = NewMaxIterHeap(comparator_); minHeap_ = NewMinIterHeap(comparator_); } } // namespace Iterator* NewMergingIterator(Env* const env, const Comparator* cmp, Iterator** list, int n) { assert(n >= 0); if (n == 0) { return NewEmptyIterator(); } else if (n == 1) { return list[0]; } else { return new MergingIterator(env, cmp, list, n); } } } // namespace rocksdb
27.659722
79
0.608712
tetcoin
c16090a9a57eb7301898c33c00bc3a437f100267
6,613
cpp
C++
opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/lag_wind_tab.cpp
337240552/opencore-amr-iOS
52fdd31e00c75ac5b07af09e7d9fd19e2210ec1c
[ "Apache-2.0" ]
192
2015-01-07T09:09:39.000Z
2022-02-22T07:11:48.000Z
opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/lag_wind_tab.cpp
337240552/opencore-amr-iOS
52fdd31e00c75ac5b07af09e7d9fd19e2210ec1c
[ "Apache-2.0" ]
19
2016-03-22T10:14:14.000Z
2021-09-04T02:40:20.000Z
opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/lag_wind_tab.cpp
337240552/opencore-amr-iOS
52fdd31e00c75ac5b07af09e7d9fd19e2210ec1c
[ "Apache-2.0" ]
71
2015-08-31T02:31:29.000Z
2022-03-08T10:18:07.000Z
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Filename: lag_wind_tab.cpp ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: None Local Stores/Buffers/Pointers Needed: None Global Stores/Buffers/Pointers Needed: None Outputs: None Pointers and Buffers Modified: None Local Stores Modified: None Global Stores Modified: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION File : lag_wind.tab Purpose : Table of lag_window for autocorrelation. *-----------------------------------------------------* | Table of lag_window for autocorrelation. | | | | noise floor = 1.0001 = (0.9999 on r[1] ..r[10]) | | Bandwitdh expansion = 60 Hz | | | | | | lag_wind[0] = 1.00000000 (not stored) | | lag_wind[1] = 0.99879038 | | lag_wind[2] = 0.99546897 | | lag_wind[3] = 0.98995781 | | lag_wind[4] = 0.98229337 | | lag_wind[5] = 0.97252619 | | lag_wind[6] = 0.96072036 | | lag_wind[7] = 0.94695264 | | lag_wind[8] = 0.93131179 | | lag_wind[9] = 0.91389757 | | lag_wind[10]= 0.89481968 | ------------------------------------------------------- ------------------------------------------------------------------------------ REQUIREMENTS None ------------------------------------------------------------------------------ REFERENCES None ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "lag_wind_tab.h" /*--------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ const Word16 lag_h[10] = { 32728, 32619, 32438, 32187, 31867, 31480, 31029, 30517, 29946, 29321 }; const Word16 lag_l[10] = { 11904, 17280, 30720, 25856, 24192, 28992, 24384, 7360, 19520, 14784 }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Define all local variables ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Function body here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/
33.39899
89
0.31922
337240552
c1630b9deae1a3ec4e60e766dd694092e1f345b9
1,725
hpp
C++
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/umask.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
10
2021-03-29T13:52:06.000Z
2022-03-10T02:24:25.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/umask.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
null
null
null
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/umask.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
6
2021-07-03T07:56:56.000Z
2022-02-14T15:28:23.000Z
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. #ifndef OPENVPN_COMMON_UMASK_H #define OPENVPN_COMMON_UMASK_H #include <sys/types.h> #include <sys/stat.h> namespace openvpn { // Note: not thread safe, since umask() is // documented to modify the process-wide file // mode creation mask. class UMask { public: UMask(mode_t new_umask) { umask_save = ::umask(new_umask); } ~UMask() { ::umask(umask_save); } private: UMask(const UMask&) = delete; UMask& operator=(const UMask&) = delete; mode_t umask_save; }; struct UMaskPrivate : public UMask { UMaskPrivate() : UMask(077) { } }; struct UMaskDaemon : public UMask { UMaskDaemon() : UMask(S_IWOTH) { } }; } #endif
25
78
0.649275
TiagoPedroByterev
c166fad59f97ac53844b7921bc9d91b910882a7c
2,066
hpp
C++
include/NasNas/core/data/Introspection.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
148
2020-04-08T13:45:34.000Z
2022-01-29T13:52:10.000Z
include/NasNas/core/data/Introspection.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
5
2020-09-15T12:34:31.000Z
2022-02-14T20:59:12.000Z
include/NasNas/core/data/Introspection.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
3
2020-10-03T22:35:20.000Z
2020-10-05T04:55:45.000Z
// Created by Modar Nasser on 30/07/2021. #pragma once #include "NasNas/core/data/Rect.hpp" namespace introspect { using namespace std; #define NS_DEFINE_HAS_METHOD(name, signature) \ template<typename, typename T=signature> \ struct has_##name {}; \ template<typename C, typename Ret, typename... Args> \ struct has_##name<C, Ret(Args...)> { \ private: \ template <typename Rt> \ using remove_const_ref = remove_const_t<remove_reference_t<Rt>>; \ template<typename T> \ static constexpr auto check(T*) -> \ enable_if_t<is_base_of_v< \ remove_const_ref<decltype(declval<T>().name(declval<Args>()...))>,\ remove_const_ref<Ret> \ >, true_type>; \ template<typename> static constexpr false_type check(...); \ using type = decltype(check<C>(0)); \ public: \ static constexpr bool value = type::value; \ }; \ template <typename C, typename T=signature> \ inline constexpr bool has_##name##_v = has_##name<C, T>::value NS_DEFINE_HAS_METHOD(getPosition, sf::Vector2f()); NS_DEFINE_HAS_METHOD(getGlobalBounds, ns::FloatRect()); NS_DEFINE_HAS_METHOD(getBounds, ns::FloatRect()); NS_DEFINE_HAS_METHOD(update, void()); }
57.388889
83
0.395934
Madour
c167d3f17bbf30ba43dc746d7feaef100154adda
33
hpp
C++
Snake/Canvas.hpp
sinkinGraphic/tiny
dece21d0d6ed5257e1d0fb8374a5f408939d8715
[ "Apache-2.0" ]
null
null
null
Snake/Canvas.hpp
sinkinGraphic/tiny
dece21d0d6ed5257e1d0fb8374a5f408939d8715
[ "Apache-2.0" ]
null
null
null
Snake/Canvas.hpp
sinkinGraphic/tiny
dece21d0d6ed5257e1d0fb8374a5f408939d8715
[ "Apache-2.0" ]
null
null
null
#pragma once class Canvas { };
4.714286
12
0.636364
sinkinGraphic
c1718a31fc78e8e673c53bc70520e6a057b7d6fc
204
hpp
C++
inc/macros.hpp
esaliya/lbl.pisa
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
4
2020-08-19T17:48:00.000Z
2021-06-17T14:39:48.000Z
inc/macros.hpp
esaliya/lbl.pisa
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
4
2020-08-14T16:43:20.000Z
2020-08-21T01:03:01.000Z
inc/macros.hpp
PASSIONLab/PASTIS
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
null
null
null
/** * @file * macros.hpp * * @author * Oguz Selvitopi * * @date * * @brief * Macro definitions * * @todo * * @note * */ #pragma once #define PASTIS_BOUND_CHECK #define PASTIS_DBG_LVL 3
8.869565
26
0.588235
esaliya
c17370b1023e7715aeaab7cdf95513bcc5af1e3f
1,129
cpp
C++
bin/lib/random/main.cpp
johnsonyl/cpps
ed91be2c1107e3cfa8e91d159be81931eacfec19
[ "MIT" ]
18
2017-09-01T04:59:23.000Z
2021-09-23T06:42:50.000Z
bin/lib/random/main.cpp
johnsonyl/cpps
ed91be2c1107e3cfa8e91d159be81931eacfec19
[ "MIT" ]
null
null
null
bin/lib/random/main.cpp
johnsonyl/cpps
ed91be2c1107e3cfa8e91d159be81931eacfec19
[ "MIT" ]
4
2017-06-15T08:46:07.000Z
2021-06-09T15:03:55.000Z
module random { var randint(var start,var end){ return math.random(start,end); } var randrange(var start,var end){ return math.random(start,end-1); } var choice(var v){ if(isstring(v)){ var p = randrange(0,len(v)); return string.at(v,p); } else if(isvector(v)){ var p = randrange(0,len(v)); return v[p]; } } var simple(var v,var count = 1){ if(!isstring(v) && !isvector(v)) return null; var hased = []; var ret = []; while(hased.size() < len(v) && hased.size() < count){ if(isstring(v)){ var p = randrange(0,len(v)); if(hased.has(p)) continue; hased.push_back(p); ret.push_back(string.at(v,p)); } else if(isvector(v)){ var p = randrange(0,len(v)); if(hased.has(p)) continue; hased.push_back(p); ret.push_back(v[p]); } } return ret; } }
27.536585
62
0.427812
johnsonyl
c173b7a6b3897debcbfbc5029668e4fec81edffe
2,019
cpp
C++
source/core/Integrator.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
3
2020-04-05T13:09:17.000Z
2021-03-16T10:56:17.000Z
source/core/Integrator.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
null
null
null
source/core/Integrator.cpp
zhanghao00925/CG-Path_Tracing-Algorithm
12bd6d7334051aa2bb0544dd26bfe4ad13ec5560
[ "MIT" ]
1
2020-02-19T02:59:44.000Z
2020-02-19T02:59:44.000Z
// // Created by hao on 3/27/19. // #include "Integrator.h" #include "core.h" #define JITTERED void Integrator::Render(shared_ptr<Sampler> sampler, shared_ptr<Camera> camera, shared_ptr<Scene> scene, shared_ptr<Film> film) { int nx = film->nx, ny = film->ny; for (int y = ny - 1; y >= 0; y--) { for (int x = 0; x < nx; x++) { printf("\rProgressing : %.2lf%%.", float((ny - 1 - y) * nx + x) / float(nx * ny) * 100); float r(0), g(0), b(0); #ifndef JITTERED int real_ns = ns; #else int spx = int(sqrt(ns)); int spy = ns / spx; int real_ns = spx * spy; float dx = 1.0 / float(spx); float dy = 1.0 / float(spy); #endif #ifdef USE_OPENMP #pragma omp parallel for reduction(+:r, g, b) #endif for (int s = 0; s < real_ns; s++) { vec2 sample = sampler->Get2D(); #ifndef JITTERED float u = (x + sample.x) / float(nx); float v = (y + sample.y) / float(ny); #else int delta_y = s / spx; int delta_x = s % spx; float u = float(x + delta_x * dx + sample.x * dx) / float(nx); float v = float(y + delta_y * dy + sample.y * dy) / float(ny); #endif Ray ray = camera->GenerateRay(u, v); vec3 result_color = deNan(color(ray, scene, 0)); r += result_color.r; g += result_color.g; b += result_color.b; } vec3 col(r, g, b); col /= float(ns); col = clamp(sqrt(col), 0.0f, 1.0f); // GAMMA // col = clamp(ACESToneMapping(col, 1.0f), 0.0f, 1.0f); // ACES Tone Mapping int ir = int(255.99 * col.r); int ig = int(255.99 * col.g); int ib = int(255.99 * col.b); film->Set((ny - 1 - y) * nx + nx - 1 - x, ir, ig, ib); } // film->WriteImage(); } film->WriteImage(); return; }
33.098361
100
0.466568
zhanghao00925
c1765d902eeeccfa73beb6a1326b12cd69ff5cc0
3,220
cpp
C++
test/accounting/UserConversionRatesTest.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
2
2016-07-17T02:12:44.000Z
2016-11-22T14:04:55.000Z
test/accounting/UserConversionRatesTest.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
null
null
null
test/accounting/UserConversionRatesTest.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Kyle Treubig * * 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. */ // UnderBudget include(s) #include "accounting/UserConversionRates.hpp" #include "UserConversionRatesTest.hpp" //------------------------------------------------------------------------------ QTEST_MAIN(ub::UserConversionRatesTest) namespace ub { //------------------------------------------------------------------------------ void UserConversionRatesTest::init() { UserConversionRates::open(":memory:"); rates = new UserConversionRates; // these values were correct as of 3/21/2013 (from google.com) rates->add("USD", "UAH", 8.14); rates->add("UAH", "USD", 0.12); rates->add("USD", "EUR", 0.77); rates->add("EUR", "USD", 1.29); rates->add("UAH", "EUR", 0.10); rates->add("EUR", "UAH", 10.51); } //------------------------------------------------------------------------------ void UserConversionRatesTest::cleanup() { delete rates; } //------------------------------------------------------------------------------ void UserConversionRatesTest::lookup_data() { QTest::addColumn<QString>("source"); QTest::addColumn<QString>("target"); QTest::addColumn<double>("rate"); QTest::newRow("eur-to-usd") << "EUR" << "USD" << 1.29; QTest::newRow("usd-to-uah") << "USD" << "UAH" << 8.14; QTest::newRow("usd-to-eur") << "USD" << "EUR" << 0.77; QTest::newRow("eur-to-uah") << "EUR" << "UAH" << 10.51; QTest::newRow("uah-to-eur") << "UAH" << "EUR" << 0.10; QTest::newRow("usd-to-gbp") << "USD" << "GBP" << 1.0; // no entry, default QTest::newRow("uah-to-usd") << "UAH" << "USD" << 0.12; } //------------------------------------------------------------------------------ void UserConversionRatesTest::lookup() { QFETCH(QString, source); QFETCH(QString, target); QFETCH(double, rate); QCOMPARE(rates->get(source, target), rate); } //------------------------------------------------------------------------------ void UserConversionRatesTest::addRates() { QCOMPARE(rates->get("USD", "GBP"), 1.0); rates->add("USD", "GBP", 0.66); QCOMPARE(rates->get("USD", "GBP"), 0.66); rates->add("USD", "GBP", 1.52); QCOMPARE(rates->get("USD", "GBP"), 1.52); } //------------------------------------------------------------------------------ void UserConversionRatesTest::removeRates() { QCOMPARE(rates->get("EUR", "USD"), 1.29); rates->remove("EUR", "USD"); QCOMPARE(rates->get("EUR", "USD"), 1.0); } //------------------------------------------------------------------------------ void UserConversionRatesTest::open() { QCOMPARE(rates->get("EUR", "USD"), 1.29); rates->open(":memory:"); // although this pair used to exist, new database doesn't have it QCOMPARE(rates->get("EUR", "USD"), 1.0); } }
31.568627
80
0.526398
vimofthevine
c17c3095919fa88b1d80bc8e2033c8cc8b257bc9
572
hpp
C++
HexGame/Engine/Input/Mouse.hpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
HexGame/Engine/Input/Mouse.hpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
HexGame/Engine/Input/Mouse.hpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
#pragma once #include <Engine/Core/OpenGL.hpp> class Mouse { public: static void posCallback(GLFWwindow* window, double _x, double _y); static void btnCallback(GLFWwindow* window, int button, int action, int mods); static float getX(); static float getY(); static const glm::vec2& getCoordinates(); static bool isButtonPressed(int button); static bool isButtonReleased(int button); static bool getButtonState(int button); private: static glm::vec2 coordinates; static bool buttonStates[]; static bool pressedButtons[]; static bool releasedButtons[]; };
21.185185
79
0.756993
kkorenev
c17c73f265a01e0b1a34c4954fed1201629be7e5
3,285
cpp
C++
ChainIDE/popwidget/AboutWidget.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
3
2019-05-09T13:56:10.000Z
2019-06-14T08:25:42.000Z
ChainIDE/popwidget/AboutWidget.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
null
null
null
ChainIDE/popwidget/AboutWidget.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
2
2019-04-27T20:39:24.000Z
2019-07-11T05:13:27.000Z
#include "AboutWidget.h" #include "ui_AboutWidget.h" #include <QPainter> #include "ChainIDE.h" #include "update/UpdateProcess.h" #include "update/UpdateProgressUtil.h" static const QString IDE_VERSION = "1.0.24"; //static const QString UPDATE_SERVER_URL = "http://192.168.1.161:7484/download/"; class AboutWidget::DataPrivate { public: DataPrivate() :updateProcess(new UpdateProcess(ChainIDE::getInstance()->getUpdateServer())) { } public: UpdateProcess *updateProcess; }; AboutWidget::AboutWidget(QWidget *parent) : MoveableDialog(parent), ui(new Ui::AboutWidget), _p(new DataPrivate()) { ui->setupUi(this); InitWidget(); } AboutWidget::~AboutWidget() { delete _p; delete ui; } void AboutWidget::CheckUpdateSlot() { emit UpdateNeeded(false); ui->label_updatetip->setText(tr("Checking updates...")); ui->label_updatetip->setVisible(true); showButtonState(-1); _p->updateProcess->checkUpdate(); } void AboutWidget::CheckResultSlot(const QString &version) { if(version.isEmpty() || UpdateProgressUtil::AFTER!=UpdateProgressUtil::CompareVersion(IDE_VERSION,version)) { //没有更新 ui->label_updatetip->setText(tr("No new version!")); showButtonState(0); } else { ui->label_updatetip->setText(tr("New version found! " )+ version); showButtonState(1); } } void AboutWidget::UpdateSlot() { ui->label_updatetip->setText(tr("Downloading... Please wait a moment! " )); showButtonState(-1); _p->updateProcess->startUpdate(); } void AboutWidget::UpdateFinishSlot() { ui->label_updatetip->setText(tr("Update finished. Restart and it will take effect! " )); showButtonState(2); emit UpdateNeeded(true); } void AboutWidget::UpdateWrongSlot() { ui->label_updatetip->setText(tr("Update error! " )); showButtonState(0); emit UpdateNeeded(false); } void AboutWidget::InitWidget() { setWindowFlags(windowFlags()| Qt::FramelessWindowHint); showButtonState(0); ui->label_updatetip->setVisible(false); #ifdef WIN64 ui->label_version->setText(QString("windows 64bit v") + IDE_VERSION); #elif defined(TARGET_OS_MAC) ui->label_version->setText(QString("mac v") + IDE_VERSION); #else ui->label_version->setText(QString("windows 32bit v") + IDE_VERSION); #endif connect(_p->updateProcess,&UpdateProcess::updateFinish,this,&AboutWidget::UpdateFinishSlot); connect(_p->updateProcess,&UpdateProcess::updateWrong,this,&AboutWidget::UpdateWrongSlot); connect(_p->updateProcess,&UpdateProcess::NewstVersionSignal,this,&AboutWidget::CheckResultSlot); connect(ui->toolButton_checkUpdate,&QToolButton::clicked,this,&AboutWidget::CheckUpdateSlot); connect(ui->toolButton_update,&QToolButton::clicked,this,&AboutWidget::UpdateSlot); connect(ui->toolButton_restart,&QToolButton::clicked,this,&AboutWidget::close); connect(ui->toolButton_restart,&QToolButton::clicked,this,&AboutWidget::RestartSignal); connect(ui->closeBtn,&QToolButton::clicked,this,&AboutWidget::close); } void AboutWidget::showButtonState(int type) { ui->toolButton_checkUpdate->setVisible(0 == type); ui->toolButton_update->setVisible(1 == type); ui->toolButton_restart->setVisible(2 == type); }
27.14876
111
0.711111
AnyChainIO
c17d32f4fc932555c2e43b41c51851409f6202f9
455
hpp
C++
im_str/tests/include_catch.hpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2021-07-16T14:19:50.000Z
2021-07-16T14:19:50.000Z
im_str/tests/include_catch.hpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2018-06-05T11:03:30.000Z
2018-06-05T11:03:30.000Z
im_str/tests/include_catch.hpp
tum-ei-rcs/mart-common
6f8f18ac23401eb294d96db490fbdf78bf9b316c
[ "MIT" ]
null
null
null
#pragma once /* * Purpose of this header is to have a central place * to include the catch library header, but with various * diagnostics disabled. * TODO: Find a way to achieve this from the tool invocation */ #ifdef _MSC_VER #include <codeanalysis\warnings.h> #pragma warning( push ) #pragma warning( disable : ALL_CODE_ANALYSIS_WARNINGS ) #include <catch2/catch.hpp> #pragma warning( pop ) #else #include <catch2/catch.hpp> #endif // _MSC_VER
21.666667
60
0.742857
Mike-Bal
c181cb523b9d25e7049248d308bc83f3a43a7ede
2,161
hpp
C++
src/planning/costmap_generator/include/costmap_generator/object_map_utils.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2022-02-24T07:36:59.000Z
2022-02-24T07:36:59.000Z
src/planning/costmap_generator/include/costmap_generator/object_map_utils.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
5
2022-01-04T20:19:51.000Z
2022-03-14T20:22:54.000Z
src/planning/costmap_generator/include/costmap_generator/object_map_utils.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2021 The Autoware Foundation // // 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. // // Co-developed by Tier IV, Inc. and Robotec.AI sp. z o.o. #ifndef COSTMAP_GENERATOR__OBJECT_MAP_UTILS_HPP_ #define COSTMAP_GENERATOR__OBJECT_MAP_UTILS_HPP_ #include <string> #include <vector> #include "grid_map_cv/grid_map_cv.hpp" #include "grid_map_msgs/msg/grid_map.hpp" #include "grid_map_ros/grid_map_ros.hpp" #include "rclcpp/rclcpp.hpp" #include "tf2_geometry_msgs/tf2_geometry_msgs.h" #include "tf2_ros/buffer.h" #include "tf2_ros/transform_listener.h" namespace object_map { /*! * Projects the in_area_points forming the road, stores the result in out_grid_map. * @param[out] out_grid_map GridMap object to add the road grid * @param[in] in_area_points Array of points containing the wayareas * @param[in] in_grid_layer_name Name to assign to the layer * @param[in] in_layer_background_value Empty state value * @param[in] in_fill_color Value to fill on wayareas * @param[in] in_layer_min_value Minimum value in the layer * @param[in] in_layer_max_value Maximum value in the later * @param[in] in_transform Most recent transform for wayarea points (from map to costmap frame) */ void fillPolygonAreas( grid_map::GridMap & out_grid_map, const std::vector<std::vector<geometry_msgs::msg::Point>> & in_area_points, const std::string & in_grid_layer_name, const int in_layer_background_value, const int in_fill_color, const int in_layer_min_value, const int in_layer_max_value, const geometry_msgs::msg::TransformStamped & in_transform); } // namespace object_map #endif // COSTMAP_GENERATOR__OBJECT_MAP_UTILS_HPP_
40.018519
96
0.775567
ruvus
c18ad5171a77486ba0735aa5ae992dc5b6bfa674
1,614
cpp
C++
main.cpp
mdklatt/clion-docker-user
fe32526ec3bbcb53c7a43c4cabf3b6b102abd892
[ "MIT" ]
null
null
null
main.cpp
mdklatt/clion-docker-user
fe32526ec3bbcb53c7a43c4cabf3b6b102abd892
[ "MIT" ]
null
null
null
main.cpp
mdklatt/clion-docker-user
fe32526ec3bbcb53c7a43c4cabf3b6b102abd892
[ "MIT" ]
null
null
null
#include <sys/stat.h> #include <unistd.h> #include <cstdlib> #include <cstdio> #include <cstring> #include <iostream> #include <stdexcept> #include <filesystem> using std::cout; using std::endl; using std::filesystem::exists; using std::exception; using std::getenv; using std::runtime_error; using std::string; /** * Display info for the Docker container user. * * @return process exit status */ int main() try { // The UID and GID should match the host user, typically 501:20 on macOS. // These should have been defined in the Docker `run` command. cout << "UID: " << geteuid() << endl; cout << "GID: " << getegid() << endl; // Determine if `fixuid` ran, either as the image ENTRYPOINT or as part of // the CLion toolchain environment script. const auto fixuid{exists("/var/run/fixuid.ran")}; cout << "fixuid: " << (fixuid ? "TRUE" : "FALSE") << endl; // This should be 'clion' as the result of running `fixuid'. const auto user{cuserid(nullptr)}; cout << "user: " << (user ? user : "") << endl; // This should be '/home/clion' as the result of running `fixuid'. const auto home{getenv("HOME")}; cout << "HOME: " << (home ? home : "") << endl; // HOME UID and GID should match the host user. struct stat statbuf{}; if (stat(home, &statbuf) != 0) { throw runtime_error(strerror(errno)); } cout << "HOME UID: " << statbuf.st_uid << endl; cout << "HOME GID: " << statbuf.st_gid << endl; return EXIT_SUCCESS; } catch (const exception& ex) { cout << "ERROR: " << ex.what() << endl; return EXIT_FAILURE; }
27.827586
78
0.623916
mdklatt
c18b4054c23dbc747d499d9fc9ff7ba550fb8304
910
cpp
C++
Problemset/maximum-number-of-achievable-transfer-requests/maximum-number-of-achievable-transfer-requests.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2020-10-06T01:06:45.000Z
2020-10-06T01:06:45.000Z
Problemset/maximum-number-of-achievable-transfer-requests/maximum-number-of-achievable-transfer-requests.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
null
null
null
Problemset/maximum-number-of-achievable-transfer-requests/maximum-number-of-achievable-transfer-requests.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2021-11-17T13:52:51.000Z
2021-11-17T13:52:51.000Z
// @Title: 最多可达成的换楼请求数目 (Maximum Number of Achievable Transfer Requests) // @Author: Singularity0909 // @Date: 2020-09-27 12:12:06 // @Runtime: 324 ms // @Memory: 8.8 MB class Solution { public: int maximumRequests(int n, vector<vector<int>>& requests) { int m = (int)requests.size(), ans = 0; for (int i = 0; i < (1 << m); i++) { int num[40] = { 0 }; for (int j = 0; j < m; j++) { if (i & (1 << j)) { num[requests[j][0]]--; num[requests[j][1]]++; } } bool flag = false; for (int i = 0; i < n; i++) { if (num[i]) { flag = true; break; } } if (!flag) { ans = max(ans, __builtin_popcount(i)); } } return ans; } };
26.764706
72
0.39011
Singularity0909
c18bc56666f8af063cd61143f6efb885b36687a9
1,280
cpp
C++
maketoeplitzCIJ.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
maketoeplitzCIJ.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
maketoeplitzCIJ.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
#include "bct.h" /* * Generates a random directed binary graph with a Toeplitz organization. */ MATRIX_T* BCT_NAMESPACE::maketoeplitzCIJ(int N, int K, FP_T s) { // profile = normpdf([1:N-1],0.5,s); VECTOR_T* indices = sequence(1, N - 1); VECTOR_T* profile = normpdf(indices, 0.5, s); VECTOR_ID(free)(indices); // template = toeplitz([0 profile],[0 profile]); VECTOR_T* temp = concatenate(0.0, profile); VECTOR_ID(free)(profile); profile = temp; MATRIX_T* _template = toeplitz(profile, profile); VECTOR_ID(free)(profile); // template = template.*(K./sum(sum(template))) VECTOR_T* sum__template = sum(_template); FP_T sum_sum__template = sum(sum__template); VECTOR_ID(free)(sum__template); MATRIX_ID(scale)(_template, (FP_T)K / sum_sum__template); // CIJ = zeros(N); MATRIX_T* CIJ = zeros(N); // while ((sum(sum(CIJ)) ~= K)) VECTOR_T* sum_CIJ = sum(CIJ); FP_T sum_sum_CIJ = sum(sum_CIJ); VECTOR_ID(free)(sum_CIJ); while ((int)sum_sum_CIJ != K) { // CIJ = (rand(N)<template); MATRIX_T* rand_N = rand(N); MATRIX_ID(free)(CIJ); CIJ = compare_elements(rand_N, fp_less, _template); MATRIX_ID(free)(rand_N); sum_CIJ = sum(CIJ); sum_sum_CIJ = sum(sum_CIJ); VECTOR_ID(free)(sum_CIJ); } MATRIX_ID(free)(_template); return CIJ; }
26.122449
73
0.677344
devuci
c18fb3a261e1163cb7b9de4c9083ce7dcd0f2d48
1,830
cpp
C++
sources/2019/2019_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
2
2021-02-01T13:19:37.000Z
2021-02-25T10:39:46.000Z
sources/2019/2019_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
sources/2019/2019_02.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
#include "2019_02.h" namespace Day02_2019 { t_Memory IntcodeVM::parse(const string& input) { int addr = 0; t_Memory m; string s; stringstream ss(input); while (getline(ss, s, ',')) m[addr++] = stoi(s); return m; } IntcodeVM::IntcodeVM(const t_Memory& program) : _ip(0) { _memory = program; } void IntcodeVM::patch(int address, int value) { _memory[address] = value; } void IntcodeVM::run() { while (1) { Operation op = (Operation)_memory[_ip++]; switch (op) { case Operation::addition: { store(fetch() + fetch()); break; } case Operation::multiplication: { store(fetch() * fetch()); break; } case Operation::halt: return; default: throw runtime_error("unsupported operation"); } } } int IntcodeVM::mem(int address) { return _memory[address]; } int IntcodeVM::fetch() { return _memory[_memory[_ip++]]; } void IntcodeVM::store(int v) { _memory[_memory[_ip++]] = v; } int part_one(const t_Memory& program) { IntcodeVM vm(program); vm.patch(1, 12); vm.patch(2, 2); vm.run(); return vm.mem(0); } int part_two(const t_Memory& program) { for (int noun = 0; noun <= 100; noun++) for (int verb = 0; verb <= 100; verb++) { IntcodeVM vm(program); vm.patch(1, noun); vm.patch(2, verb); vm.run(); if (19690720 == vm.mem(0)) return 100 * noun + verb; } return -1; } t_output main(const t_input& input) { auto program = IntcodeVM::parse(input[0]); auto t0 = chrono::steady_clock::now(); auto p1 = part_one(program); auto p2 = part_two(program); auto t1 = chrono::steady_clock::now(); vector<string> solutions; solutions.push_back(to_string(p1)); solutions.push_back(to_string(p2)); return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count()); } }
18.673469
82
0.621858
tbielak
c18ff524fb2a908f3063e00715cfc0bde1d83413
4,973
cc
C++
2014 Nordic Collegiate Programming Contest/A.cc
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
5
2019-04-07T05:39:11.000Z
2020-07-23T01:43:02.000Z
2014 Nordic Collegiate Programming Contest/A.cc
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
2014 Nordic Collegiate Programming Contest/A.cc
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<iostream> #include<algorithm> #include<string.h> #include<vector> #include<map> using namespace std; typedef long long ll; const int maxn = 2e5+10; #define pb push_back #define mp make_pair #define dbg(x) cout<<#x<<" = "<<x<<endl #define dbg2(x1,x2) cout<<#x1<<" = "<<x1<<" "<<#x2<<" = "<<x2<<endl int vis[maxn]; vector<pair<int,int> >ss[maxn]; int vis2[maxn]; bool dfs(int u,int flag) { vis2[u]=1; for(int i=0;i<ss[u].size();i++) { int ff=1; pair<int,int>vv=ss[u][i]; if(vis[vv.first]) { // cout<<u<<' '<<vv.first<<' '<<flag<<' '<<vis[vv.first]<<' '<<endl; if(vv.second==1) { //cout<<u<<' '<<vv.first<<' '<<flag<<' '<<vis[vv.first]<<' '<<endl; if(vis[vv.first]==flag)return false; else continue; } else { if(vv.second==0) { //cout<<u<<' '<<vv.first<<' '<<flag<<' '<<vis[vv.first]<<' '<<endl; if(vis[vv.first]==1&&flag==1)continue; else return false; } else { // cout<<u<<' '<<vv.first<<' '<<flag<<' '<<vis[vv.first]<<' '<<endl; if(vis[vv.first]==2&&flag==2)continue; else return false; } } } else { if(vv.second==1) { if(flag==1) { vis[vv.first]=2; ff= dfs(vv.first,2); } else { vis[vv.first]=1; ff= dfs(vv.first,1); } } else { if(vv.second==0) { if(flag!=1)return false; vis[vv.first]=1; ff= dfs(vv.first,1); } else { if(flag!=2)return false; vis[vv.first]=2; ff= dfs(vv.first,2); } } } if(ff==1)continue; else return false; } return true; // if(ff==1)return true; // else return false; } int vis1[maxn]; int cnt[maxn]; bool dfs1(int u,int flag,int &sum) { if(flag==2)sum+=1; for(int i=0;i<ss[u].size();i++) { int ff=1; pair<int,int>vv; vv=ss[u][i]; if(vis[vv.first]) { if(flag==vis[vv.first])return false; } else { if(flag==1) { vis[vv.first]=2; if(!dfs1(vv.first,2,sum))ff=0; } else { vis[vv.first]=1; if(!dfs1(vv.first,1,sum))ff=0; } } if(ff==0)return false; } return true; } void dfs2(int u,int flag) { //cout<<u<<' '<<(int)ss[u].size()<<endl; for(int i=0;i<ss[u].size();i++) { pair<int,int>vv; vv=ss[u][i]; //cout<<vv.first<<endl; if(vis1[vv.first])continue; else { vis1[vv.first]=flag; dfs2(vv.first,flag); } } } int main() { //freopen("A3.in","r",stdin); int n,m; scanf("%d%d",&n,&m); int flag=1; for(int i=1;i<=m;i++) { int u,v; int sign; scanf("%d%d%d",&u,&v,&sign); ss[u].pb(mp(v,sign)); ss[v].pb(mp(u,sign)); if(sign==2) { vis[u]=vis[v]=2; } else if(sign==0) { // if(vis[i]==2)flag=0; vis[u]=vis[v]=1;//1 none } } for(int i=1;i<=n;i++) { if(vis2[i]==0) if(vis[i]==1||vis[i]==2) { if(vis[i]==1) { if(!dfs(i,1))flag=0; } else if(!dfs(i,2))flag=0; } } if(flag) { int sum=0; for(int i=1;i<=n;i++)if(vis[i]==2)sum++; int cc=3; memcpy(vis1,vis,sizeof(vis)); for(int i=1;i<=n;i++) { if(vis1[i]==0) { vis1[i]=cc; dfs2(i,cc); cc++; } } cc--; for(int i=1;i<=n;i++) { if(vis1[i]>=3)cnt[vis1[i]]++; } // for(int i=1;i<=n;i++)cout<<vis1[i]<<' '; // puts(""); int ff=1; for(int i=1;i<=n;i++) { int sum1=0; if(vis[i]==0) { vis[i]=1; if(!dfs1(i,1,sum1))ff=0; //cout<<sum1<<endl; int ans=min(sum1,cnt[vis1[i]]-sum1); sum+=ans; } } if(ff) cout<<sum<<endl; else printf("impossible\n"); } else printf("impossible\n"); return 0; }
23.347418
87
0.35552
lajiyuan
c1931adcfe32a0a24c4813845fed92b25bffff25
28,343
cc
C++
src/utils/pdlfs_xxhash_impl.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
1
2021-01-11T14:19:51.000Z
2021-01-11T14:19:51.000Z
src/utils/pdlfs_xxhash_impl.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
src/utils/pdlfs_xxhash_impl.cc
pengdu/bubblefs
9b27e191a287b3a1d012adfd3bab6a30629a5f33
[ "BSD-3-Clause" ]
null
null
null
/* * xxHash - Fast Hash algorithm * Copyright (C) 2012-2016, Yann Collet * * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * You can contact the author at : * - xxHash homepage: http://www.xxhash.com * - xxHash source repository : https://github.com/Cyan4973/xxHash */ // pdlfs-common/src/xxhash_impl.cc /* ************************************* * Tuning parameters ***************************************/ /*!XXH_FORCE_MEMORY_ACCESS : * By default, access to unaligned memory is controlled by `memcpy()`, which is * safe and portable. * Unfortunately, on some target/compiler combinations, the generated assembly * is sub-optimal. * The below switch allow to select different access method for improved * performance. * Method 0 (default) : use `memcpy()`. Safe and portable. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not * portable). * This method is safe if your compiler supports it, and *generally* * as fast or faster than `memcpy`. * Method 2 : direct access. This method doesn't depend on compiler but violate * C standard. * It can generate buggy code on targets which do not support * unaligned memory accesses. * But in some circumstances, it's the only known way to get the most * performance (ie GCC + ARMv6) * See http://stackoverflow.com/a/32095106/646947 for details. * Prefer these methods in priority order (0 > 1 > 2) */ #ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line \ for example */ #if defined(__GNUC__) && \ (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \ defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__)) #define XXH_FORCE_MEMORY_ACCESS 2 #elif defined(__INTEL_COMPILER) || \ (defined(__GNUC__) && \ (defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \ defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || \ defined(__ARM_ARCH_7S__))) #define XXH_FORCE_MEMORY_ACCESS 1 #endif #endif /*!XXH_ACCEPT_NULL_INPUT_POINTER : * If the input pointer is a null pointer, xxHash default behavior is to trigger * a memory access error, since it is a bad pointer. * When this option is enabled, xxHash output for null input pointers will be * the same as a null-length input. * By default, this option is disabled. To enable it, uncomment below define : */ /* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */ /*!XXH_FORCE_NATIVE_FORMAT : * By default, xxHash library provides endian-independant Hash values, based on * little-endian convention. * Results are therefore identical for little-endian and big-endian CPU. * This comes at a performance cost for big-endian CPU, since some swapping is * required to emulate little-endian format. * Should endian-independance be of no importance for your application, you may * set the #define below to 1, * to improve speed for Big-endian CPU. * This option has no impact on Little_Endian CPU. */ #ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ #define XXH_FORCE_NATIVE_FORMAT 0 #endif /*!XXH_FORCE_ALIGN_CHECK : * This is a minor performance trick, only useful with lots of very small keys. * It means : check for aligned/unaligned input. * The check costs one initial branch per hash; set to 0 when the input data * is guaranteed to be aligned. */ #ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ #if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || \ defined(_M_X64) #define XXH_FORCE_ALIGN_CHECK 0 #else #define XXH_FORCE_ALIGN_CHECK 1 #endif #endif /* ************************************* * Includes & Memory related functions ***************************************/ /* Modify the local functions below should you wish to use some other memory * routines */ /* for malloc(), free() */ #include <stdlib.h> static void* XXH_malloc(size_t s) { return malloc(s); } static void XXH_free(void* p) { free(p); } /* for memcpy() */ #include <string.h> static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest, src, size); } #define XXH_STATIC_LINKING_ONLY #include "utils/pdlfs_xxhash_impl.h" /* ************************************* * Compiler Specific Options ***************************************/ #ifdef _MSC_VER /* Visual Studio */ #pragma warning( \ disable : 4127) /* disable: C4127: conditional expression is constant */ #define FORCE_INLINE static __forceinline #else #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ #ifdef __GNUC__ #define FORCE_INLINE static inline __attribute__((always_inline)) #else #define FORCE_INLINE static inline #endif #else #define FORCE_INLINE static #endif /* __STDC_VERSION__ */ #endif /* ************************************* * Basic Types ***************************************/ #ifndef MEM_MODULE #define MEM_MODULE #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ #include <stdint.h> typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; #else typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; #endif #endif #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 2)) /* Force direct memory access. Only works on CPU which support unaligned memory * access in hardware */ static U32 XXH_read32(const void* memPtr) { return *(const U32*)memPtr; } static U64 XXH_read64(const void* memPtr) { return *(const U64*)memPtr; } #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS == 1)) /* __pack instructions are safer, but compiler specific, hence potentially * problematic for some compilers */ /* currently only defined for gcc and icc */ typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign; static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } static U64 XXH_read64(const void* ptr) { return ((const unalign*)ptr)->u64; } #else /* portable and safe solution. Generally efficient. * see : http://stackoverflow.com/a/32095106/646947 */ static U32 XXH_read32(const void* memPtr) { U32 val; memcpy(&val, memPtr, sizeof(val)); return val; } static U64 XXH_read64(const void* memPtr) { U64 val; memcpy(&val, memPtr, sizeof(val)); return val; } #endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ /* **************************************** * Compiler-specific Functions and Macros ******************************************/ #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) /* Note : although _rotl exists for minGW (GCC under windows), performance seems * poor */ #if defined(_MSC_VER) #define XXH_rotl32(x, r) _rotl(x, r) #define XXH_rotl64(x, r) _rotl64(x, r) #else #define XXH_rotl32(x, r) ((x << r) | (x >> (32 - r))) #define XXH_rotl64(x, r) ((x << r) | (x >> (64 - r))) #endif #if defined(_MSC_VER) /* Visual Studio */ #define XXH_swap32 _byteswap_ulong #define XXH_swap64 _byteswap_uint64 #elif GCC_VERSION >= 403 #define XXH_swap32 __builtin_bswap32 #define XXH_swap64 __builtin_bswap64 #else static U32 XXH_swap32(U32 x) { return ((x << 24) & 0xff000000) | ((x << 8) & 0x00ff0000) | ((x >> 8) & 0x0000ff00) | ((x >> 24) & 0x000000ff); } static U64 XXH_swap64(U64 x) { return ((x << 56) & 0xff00000000000000ULL) | ((x << 40) & 0x00ff000000000000ULL) | ((x << 24) & 0x0000ff0000000000ULL) | ((x << 8) & 0x000000ff00000000ULL) | ((x >> 8) & 0x00000000ff000000ULL) | ((x >> 24) & 0x0000000000ff0000ULL) | ((x >> 40) & 0x000000000000ff00ULL) | ((x >> 56) & 0x00000000000000ffULL); } #endif /* ************************************* * Architecture Macros ***************************************/ typedef enum { XXH_bigEndian = 0, XXH_littleEndian = 1 } XXH_endianess; /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler * command line */ #ifndef XXH_CPU_LITTLE_ENDIAN static const int g_one = 1; #define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&g_one)) #endif /* *************************** * Memory reads *****************************/ typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) { if (align == XXH_unaligned) return endian == XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); else return endian == XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); } FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); } static U32 XXH_readBE32(const void* ptr) { return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); } FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) { if (align == XXH_unaligned) return endian == XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); else return endian == XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); } FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) { return XXH_readLE64_align(ptr, endian, XXH_unaligned); } static U64 XXH_readBE64(const void* ptr) { return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); } /* ************************************* * Macros ***************************************/ #define XXH_STATIC_ASSERT(c) \ { \ enum { XXH_static_assert = 1 / (int)(!!(c)) }; \ } /* use only *after* variable declarations */ /* ************************************* * Constants ***************************************/ static const U32 PRIME32_1 = 2654435761U; static const U32 PRIME32_2 = 2246822519U; static const U32 PRIME32_3 = 3266489917U; static const U32 PRIME32_4 = 668265263U; static const U32 PRIME32_5 = 374761393U; static const U64 PRIME64_1 = 11400714785074694791ULL; static const U64 PRIME64_2 = 14029467366897019727ULL; static const U64 PRIME64_3 = 1609587929392839161ULL; static const U64 PRIME64_4 = 9650029242287828579ULL; static const U64 PRIME64_5 = 2870177450012600261ULL; XXH_PUBLIC_API unsigned XXH_versionNumber(void) { return XXH_VERSION_NUMBER; } /* *************************** * Simple Hash Functions *****************************/ static U32 XXH32_round(U32 seed, U32 input) { seed += input * PRIME32_2; seed = XXH_rotl32(seed, 13); seed *= PRIME32_1; return seed; } FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)input; const BYTE* bEnd = p + len; U32 h32; #define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (p == NULL) { len = 0; bEnd = p = (const BYTE*)(size_t)16; } #endif if (len >= 16) { const BYTE* const limit = bEnd - 16; U32 v1 = seed + PRIME32_1 + PRIME32_2; U32 v2 = seed + PRIME32_2; U32 v3 = seed + 0; U32 v4 = seed - PRIME32_1; do { v1 = XXH32_round(v1, XXH_get32bits(p)); p += 4; v2 = XXH32_round(v2, XXH_get32bits(p)); p += 4; v3 = XXH32_round(v3, XXH_get32bits(p)); p += 4; v4 = XXH32_round(v4, XXH_get32bits(p)); p += 4; } while (p <= limit); h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (U32)len; while (p + 4 <= bEnd) { h32 += XXH_get32bits(p) * PRIME32_3; h32 = XXH_rotl32(h32, 17) * PRIME32_4; p += 4; } while (p < bEnd) { h32 += (*p) * PRIME32_5; h32 = XXH_rotl32(h32, 11) * PRIME32_1; p++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } XXH_PUBLIC_API unsigned int XXH32(const void* input, size_t len, unsigned int seed) { #if 0 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ XXH32_CREATESTATE_STATIC(state); XXH32_reset(state, seed); XXH32_update(state, input, len); return XXH32_digest(state); #else XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if (XXH_FORCE_ALIGN_CHECK) { if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); } } if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); #endif } static U64 XXH64_round(U64 acc, U64 input) { acc += input * PRIME64_2; acc = XXH_rotl64(acc, 31); acc *= PRIME64_1; return acc; } static U64 XXH64_mergeRound(U64 acc, U64 val) { val = XXH64_round(0, val); acc ^= val; acc = acc * PRIME64_1 + PRIME64_4; return acc; } FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; U64 h64; #define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (p == NULL) { len = 0; bEnd = p = (const BYTE*)(size_t)32; } #endif if (len >= 32) { const BYTE* const limit = bEnd - 32; U64 v1 = seed + PRIME64_1 + PRIME64_2; U64 v2 = seed + PRIME64_2; U64 v3 = seed + 0; U64 v4 = seed - PRIME64_1; do { v1 = XXH64_round(v1, XXH_get64bits(p)); p += 8; v2 = XXH64_round(v2, XXH_get64bits(p)); p += 8; v3 = XXH64_round(v3, XXH_get64bits(p)); p += 8; v4 = XXH64_round(v4, XXH_get64bits(p)); p += 8; } while (p <= limit); h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); h64 = XXH64_mergeRound(h64, v1); h64 = XXH64_mergeRound(h64, v2); h64 = XXH64_mergeRound(h64, v3); h64 = XXH64_mergeRound(h64, v4); } else { h64 = seed + PRIME64_5; } h64 += (U64)len; while (p + 8 <= bEnd) { U64 const k1 = XXH64_round(0, XXH_get64bits(p)); h64 ^= k1; h64 = XXH_rotl64(h64, 27) * PRIME64_1 + PRIME64_4; p += 8; } if (p + 4 <= bEnd) { h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; p += 4; } while (p < bEnd) { h64 ^= (*p) * PRIME64_5; h64 = XXH_rotl64(h64, 11) * PRIME64_1; p++; } h64 ^= h64 >> 33; h64 *= PRIME64_2; h64 ^= h64 >> 29; h64 *= PRIME64_3; h64 ^= h64 >> 32; return h64; } XXH_PUBLIC_API unsigned long long XXH64(const void* input, size_t len, unsigned long long seed) { #if 0 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ XXH64_CREATESTATE_STATIC(state); XXH64_reset(state, seed); XXH64_update(state, input, len); return XXH64_digest(state); #else XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if (XXH_FORCE_ALIGN_CHECK) { if ((((size_t)input) & 7) == 0) { /* Input is aligned, let's leverage the speed advantage */ if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); else return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); } } if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); else return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); #endif } /* ************************************************** * Advanced Hash Functions ****************************************************/ XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) { return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); } XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) { XXH_free(statePtr); return XXH_OK; } XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) { return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); } XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) { XXH_free(statePtr); return XXH_OK; } /*** Hash feed ***/ XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) { XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ memset(&state, 0, sizeof(state)); state.seed = seed; state.v1 = seed + PRIME32_1 + PRIME32_2; state.v2 = seed + PRIME32_2; state.v3 = seed + 0; state.v4 = seed - PRIME32_1; memcpy(statePtr, &state, sizeof(state)); return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) { XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ memset(&state, 0, sizeof(state)); state.seed = seed; state.v1 = seed + PRIME64_1 + PRIME64_2; state.v2 = seed + PRIME64_2; state.v3 = seed + 0; state.v4 = seed - PRIME64_1; memcpy(statePtr, &state, sizeof(state)); return XXH_OK; } FORCE_INLINE XXH_errorcode XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (input == NULL) return XXH_ERROR; #endif state->total_len += len; if (state->memsize + len < 16) { /* fill in tmp buffer */ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); state->memsize += (U32)len; return XXH_OK; } if (state->memsize) { /* some data left from previous update */ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16 - state->memsize); { const U32* p32 = state->mem32; state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++; } p += 16 - state->memsize; state->memsize = 0; } if (p <= bEnd - 16) { const BYTE* const limit = bEnd - 16; U32 v1 = state->v1; U32 v2 = state->v2; U32 v3 = state->v3; U32 v4 = state->v4; do { v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p += 4; v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p += 4; v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p += 4; v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p += 4; } while (p <= limit); state->v1 = v1; state->v2 = v2; state->v3 = v3; state->v4 = v4; } if (p < bEnd) { XXH_memcpy(state->mem32, p, bEnd - p); state->memsize = (int)(bEnd - p); } return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH32_update(XXH32_state_t* state_in, const void* input, size_t len) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_update_endian(state_in, input, len, XXH_littleEndian); else return XXH32_update_endian(state_in, input, len, XXH_bigEndian); } FORCE_INLINE U32 XXH32_digest_endian(const XXH32_state_t* state, XXH_endianess endian) { const BYTE* p = (const BYTE*)state->mem32; const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize; U32 h32; if (state->total_len >= 16) { h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); } else { h32 = state->seed + PRIME32_5; } h32 += (U32)state->total_len; while (p + 4 <= bEnd) { h32 += XXH_readLE32(p, endian) * PRIME32_3; h32 = XXH_rotl32(h32, 17) * PRIME32_4; p += 4; } while (p < bEnd) { h32 += (*p) * PRIME32_5; h32 = XXH_rotl32(h32, 11) * PRIME32_1; p++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } XXH_PUBLIC_API unsigned int XXH32_digest(const XXH32_state_t* state_in) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_digest_endian(state_in, XXH_littleEndian); else return XXH32_digest_endian(state_in, XXH_bigEndian); } /* **** XXH64 **** */ FORCE_INLINE XXH_errorcode XXH64_update_endian(XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (input == NULL) return XXH_ERROR; #endif state->total_len += len; if (state->memsize + len < 32) { /* fill in tmp buffer */ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); state->memsize += (U32)len; return XXH_OK; } if (state->memsize) { /* tmp buffer is full */ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32 - state->memsize); state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64 + 0, endian)); state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64 + 1, endian)); state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64 + 2, endian)); state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64 + 3, endian)); p += 32 - state->memsize; state->memsize = 0; } if (p + 32 <= bEnd) { const BYTE* const limit = bEnd - 32; U64 v1 = state->v1; U64 v2 = state->v2; U64 v3 = state->v3; U64 v4 = state->v4; do { v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p += 8; v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p += 8; v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p += 8; v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p += 8; } while (p <= limit); state->v1 = v1; state->v2 = v2; state->v3 = v3; state->v4 = v4; } if (p < bEnd) { XXH_memcpy(state->mem64, p, bEnd - p); state->memsize = (int)(bEnd - p); } return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH64_update(XXH64_state_t* state_in, const void* input, size_t len) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_update_endian(state_in, input, len, XXH_littleEndian); else return XXH64_update_endian(state_in, input, len, XXH_bigEndian); } FORCE_INLINE U64 XXH64_digest_endian(const XXH64_state_t* state, XXH_endianess endian) { const BYTE* p = (const BYTE*)state->mem64; const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize; U64 h64; if (state->total_len >= 32) { U64 const v1 = state->v1; U64 const v2 = state->v2; U64 const v3 = state->v3; U64 const v4 = state->v4; h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); h64 = XXH64_mergeRound(h64, v1); h64 = XXH64_mergeRound(h64, v2); h64 = XXH64_mergeRound(h64, v3); h64 = XXH64_mergeRound(h64, v4); } else { h64 = state->seed + PRIME64_5; } h64 += (U64)state->total_len; while (p + 8 <= bEnd) { U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian)); h64 ^= k1; h64 = XXH_rotl64(h64, 27) * PRIME64_1 + PRIME64_4; p += 8; } if (p + 4 <= bEnd) { h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1; h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; p += 4; } while (p < bEnd) { h64 ^= (*p) * PRIME64_5; h64 = XXH_rotl64(h64, 11) * PRIME64_1; p++; } h64 ^= h64 >> 33; h64 *= PRIME64_2; h64 ^= h64 >> 29; h64 *= PRIME64_3; h64 ^= h64 >> 32; return h64; } XXH_PUBLIC_API unsigned long long XXH64_digest(const XXH64_state_t* state_in) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected == XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_digest_endian(state_in, XXH_littleEndian); else return XXH64_digest_endian(state_in, XXH_bigEndian); } /* ************************** * Canonical representation ****************************/ /*! Default XXH result types are basic unsigned 32 and 64 bits. * The canonical representation follows human-readable write convention, aka * big-endian (large digits first). * These functions allow transformation of hash result into and from its * canonical format. * This way, hash values can be written into a file or buffer, and remain * comparable across different systems and programs. */ XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) { XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); memcpy(dst, &hash, sizeof(*dst)); } XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) { XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); memcpy(dst, &hash, sizeof(*dst)); } XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) { return XXH_readBE32(src); } XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) { return XXH_readBE64(src); }
31.810325
92
0.632784
pengdu