hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
70db1e5fb99009a442ee7a87d4919eb90b8efd5e
8,309
cpp
C++
cpp/yarn/detail/AttachmentStrategy.cpp
dstmath/profilo
85c4e4cbf954e8ea4d6227d863f2980ab2c53b55
[ "Apache-2.0" ]
1
2019-01-14T13:37:12.000Z
2019-01-14T13:37:12.000Z
cpp/yarn/detail/AttachmentStrategy.cpp
KazuCocoa/profilo
29831cd73e7933a72914d96a20814a285608c539
[ "Apache-2.0" ]
null
null
null
cpp/yarn/detail/AttachmentStrategy.cpp
KazuCocoa/profilo
29831cd73e7933a72914d96a20814a285608c539
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2004-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <yarn/detail/AttachmentStrategy.h> namespace facebook { namespace yarn { namespace detail { static bool tryRaiseFdLimit(); static int getCoreCount(); static int getCoreCount() { static const int kNumCores = sysconf(_SC_NPROCESSORS_CONF); return kNumCores; } PerCoreAttachmentStrategy::PerCoreAttachmentStrategy( const EventSpecList& specs, uint32_t fallbacks, uint16_t max_iterations, float open_fds_limit_ratio) : specs_(specs), // copy global_specs_(0), fallbacks_(fallbacks), used_fallbacks_(0), max_iterations_(max_iterations), open_fds_limit_ratio_(open_fds_limit_ratio) { size_t global_events = 0; // process-wide events for (auto& spec : specs) { if (spec.isProcessWide()) { ++global_events; } } global_specs_ = global_events; } EventList PerCoreAttachmentStrategy::attach() { // The list from the previous iteration of the attachment loop, // used to calculate the delta from attempt to attempt. auto prev_tids = ThreadList(); // The final list of event objects. auto perf_events = EventList(); bool success = false; // The first event on every core becomes the output for all // other events on this core. We store their indices into perf_events here. // (It's kinda silly but it saves us from using shared_ptr everywhere) auto cpu_output_idxs = std::vector<size_t>(getCoreCount()); auto has_cpu_output = std::vector<bool>(getCoreCount()); for (int32_t iter = 0; iter < max_iterations_; iter++) { auto tids = threadListFromProcFs(); if (!isWithinLimits(tids.size())) { if (tryFallbacks()) { iter--; // don't count fallbacks as an attachment iteration } continue; // try again } auto events = eventsForDelta(prev_tids, tids); for (auto& evt : events) { try { evt.open(); } catch (std::system_error& ex) { // check for missing thread auto current_tids = threadListFromProcFs(); auto no_result = current_tids.end(); if (current_tids.find(evt.tid()) == no_result) { // Thread is no longer alive, allow this failure. The dead thread // remains in `tids`, see comment at the end of the loop. continue; } else { // We don't know what's wrong, rethrow. throw; } } perf_events.push_back(std::move(evt)); size_t last_idx = perf_events.size() - 1; // evt is gone now, get a reference to the Event in the list auto& list_evt = perf_events.at(last_idx); int32_t cpu = list_evt.cpu(); if (!has_cpu_output[cpu]) { // First event on each cpu becomes the "cpu output" - all subsequent // events on this core will be redirected to it. cpu_output_idxs[cpu] = last_idx; has_cpu_output[cpu] = true; } } // If we have at least one process-wide event, we care about attaching to // all currently running threads. if (global_specs_ > 0) { // Get the thread list again and confirm it hasn't changed. auto end_tids = threadListFromProcFs(); if (tids == end_tids) { // Same list, reached a fixed point, we're done here. success = true; break; } else { // Things changed, record the last list we worked with and try again. // // It doesn't matter that prev_tids potentially contains threads which // are no longer alive (see try-catch above) - that's only a problem // if the dead thread's tid is reused and we get a false positive. // The chances of tid reusal within two iterations of this loop // are infinitesimal. prev_tids = std::move(tids); continue; } } else { // We are attaching to specific threads and that's all best effort. // We don't care if any of the threads suddenly disappeared. success = true; break; } } if (success) { // mmap the cpu leaders and redirect all other events to them. for (int cpu = 0; cpu < getCoreCount(); ++cpu) { if (!perf_events.empty() && !has_cpu_output[cpu]) { throw std::logic_error( "Succeeded but did not assign a CPU output event for all cores"); } // TODO: figure out buffer size perf_events.at(cpu_output_idxs[cpu]).mmap(4096 * 5); } for (auto& evt : perf_events) { // skip the cpu leaders if (evt.buffer() != nullptr) { continue; } auto& cpu_evt = perf_events.at(cpu_output_idxs[evt.cpu()]); evt.setOutput(cpu_evt); } return perf_events; } else { return EventList(); } } static ThreadList computeDelta( const ThreadList& prev_tids, const ThreadList& tids) { if (prev_tids.empty()) { return tids; } else { auto delta = ThreadList(); auto no_result = prev_tids.end(); for (auto& tid : tids) { if (prev_tids.find(tid) == no_result) { delta.emplace(tid); } } return delta; } } // // Build a list of Event objects for all threads in `tids` but not in // `prev_tids`. If `prev_tids` is nullptr or empty, this will build a list of // events for every thread in `tids`. // EventList PerCoreAttachmentStrategy::eventsForDelta( const ThreadList& prev_tids, const ThreadList& tids) const { auto delta = computeDelta(prev_tids, tids); auto events = EventList(); for (auto& spec : specs_) { for (int32_t cpu = 0; cpu < getCoreCount(); cpu++) { // one event per core if (spec.isProcessWide()) { for (auto& tid : delta) { // per thread we know about too events.emplace_back(spec.type, tid, cpu, true /*inherit*/); } } else { // We're targeting a specific thread but we still // need one event per core. events.emplace_back(spec.type, spec.tid, cpu, false /*inherit*/); } } } return events; } bool PerCoreAttachmentStrategy::isWithinLimits(size_t tids_count) { auto specific_specs = specs_.size() - global_specs_; auto fds = fdListFromProcFs(); auto fds_count = fds.size(); auto coreCount = getCoreCount(); // number of fds we'll add auto estimate_new_fds = tids_count * coreCount * global_specs_ + // process-global coreCount * specific_specs; // specific threads // estimated final count auto estimate_fds_count = fds_count + estimate_new_fds; auto max_fds = getrlimit(RLIMIT_NOFILE); auto internal_limit = open_fds_limit_ratio_ * max_fds.rlim_cur; return estimate_fds_count <= internal_limit; } bool PerCoreAttachmentStrategy::tryFallbacks() { if ((fallbacks_ & FALLBACK_RAISE_RLIMIT) && ((used_fallbacks_ & FALLBACK_RAISE_RLIMIT) == 0) && tryRaiseFdLimit()) { used_fallbacks_ |= FALLBACK_RAISE_RLIMIT; return true; } return false; } // Update the soft file descriptor limit up to the hard limit. // Returns true if the request succeeded, // false if they were already the same. static bool tryRaiseFdLimit() { try { auto limits = getrlimit(RLIMIT_NOFILE); if (limits.rlim_cur == limits.rlim_max) { // Soft limit is already up to the hard limit return false; } // Raise the soft limit up to the hard limit auto new_limits = rlimit{limits.rlim_max, limits.rlim_max}; setrlimit(RLIMIT_NOFILE, new_limits); // Check if we actually succeeded. If we didn't, we'd keep trying on every // attachment iteration but that's okay. new_limits = getrlimit(RLIMIT_NOFILE); return new_limits.rlim_cur == limits.rlim_max; } catch (std::system_error& ex) { return false; } } } // namespace detail } // namespace yarn } // namespace facebook
31.473485
78
0.654952
[ "vector" ]
70de4d828a3a8f702f0f3ed690318f3c36a85409
6,415
hpp
C++
include/mphf/recsplit/src/RiceBitVector.hpp
DominikHorn/exotic-hashing
77ae8a696a6b18f1b6e600143666a1e90eed6b85
[ "MIT" ]
null
null
null
include/mphf/recsplit/src/RiceBitVector.hpp
DominikHorn/exotic-hashing
77ae8a696a6b18f1b6e600143666a1e90eed6b85
[ "MIT" ]
null
null
null
include/mphf/recsplit/src/RiceBitVector.hpp
DominikHorn/exotic-hashing
77ae8a696a6b18f1b6e600143666a1e90eed6b85
[ "MIT" ]
null
null
null
/* * Sux: Succinct data structures * * Copyright (C) 2019-2020 Emmanuel Esposito and Sebastiano Vigna * * 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 3 of the License, or (at your option) * any later version. * * This library 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, 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 General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional permissions * described in the GCC Runtime Library Exception, version 3.1, as published by * the Free Software Foundation. * * You should have received a copy of the GNU General Public License and a copy of * the GCC Runtime Library Exception along with this program; see the files * COPYING3 and COPYING.RUNTIME respectively. If not, see * <http://www.gnu.org/licenses/>. */ #pragma once #include "support/common.hpp" #include "util/Vector.hpp" #include <cstdint> #include <cstdio> #include <iostream> namespace sux::function { using namespace std; using namespace sux; /** Storage for Golomb-Rice codes of a RecSplit bucket. * * This class exists solely to implement RecSplit. * @tparam AT a type of memory allocation out of util::AllocType. */ template<util::AllocType AT = util::AllocType::MALLOC> class RiceBitVector { public: class Builder { util::Vector<uint64_t, AT> data; size_t bit_count = 0; public: Builder() : Builder(16) {} Builder(const size_t alloc_words) : data(alloc_words) {} void appendFixed(const uint64_t v, const int log2golomb) { const uint64_t lower_bits = v & ((uint64_t(1) << log2golomb) - 1); int used_bits = bit_count & 63; data.resize((((bit_count + log2golomb + 7) / 8) + 7 + 7) / 8); uint64_t* append_ptr = &data + bit_count / 64; uint64_t cur_word = *append_ptr; cur_word |= lower_bits << used_bits; if (used_bits + log2golomb > 64) { *(append_ptr++) = cur_word; cur_word = lower_bits >> (64 - used_bits); used_bits += log2golomb - 64; } *append_ptr = cur_word; bit_count += log2golomb; } void appendUnaryAll(const std::vector<uint32_t> unary) { size_t bit_inc = 0; for (const auto& u : unary) { bit_inc += u + 1; } data.resize((((bit_count + bit_inc + 7) / 8) + 7 + 7) / 8); for (const auto& u : unary) { bit_count += u; uint64_t* append_ptr = &data + bit_count / 64; *append_ptr |= uint64_t(1) << (bit_count & 63); ++bit_count; } } uint64_t getBits() { return bit_count; } RiceBitVector<AT> build() { data.trimToFit(); return RiceBitVector(std::move(data)); } }; private: util::Vector<uint64_t, AT> data; friend std::ostream& operator<<(std::ostream& os, const RiceBitVector<AT>& rbv) { os << rbv.data; return os; } friend std::istream& operator>>(std::istream& is, RiceBitVector<AT>& rbv) { is >> rbv.data; return is; } public: RiceBitVector() {} RiceBitVector(util::Vector<uint64_t, AT> data) : data(std::move(data)) {} size_t getBits() const { return data.size() * sizeof(uint64_t); } class Reader { size_t curr_fixed_offset = 0; uint64_t curr_window_unary = 0; uint64_t* curr_ptr_unary; int valid_lower_bits_unary = 0; const util::Vector<uint64_t, AT>& data; public: explicit Reader(const util::Vector<uint64_t, AT>& data) : data(data) {} uint64_t readNext(const int log2golomb) { uint64_t result = 0; if (curr_window_unary == 0) { result += valid_lower_bits_unary; curr_window_unary = *(curr_ptr_unary++); valid_lower_bits_unary = 64; while (__builtin_expect(curr_window_unary == 0, 0)) { result += 64; curr_window_unary = *(curr_ptr_unary++); } } const size_t pos = rho(curr_window_unary); curr_window_unary >>= pos; curr_window_unary >>= 1; valid_lower_bits_unary -= pos + 1; result += pos; result <<= log2golomb; uint64_t fixed; memcpy(&fixed, (uint8_t*) &data + curr_fixed_offset / 8, 8); result |= (fixed >> curr_fixed_offset % 8) & ((uint64_t(1) << log2golomb) - 1); curr_fixed_offset += log2golomb; return result; } void skipSubtree(const size_t nodes, const size_t fixed_len) { assert(nodes > 0); size_t missing = nodes, cnt; while ((cnt = nu(curr_window_unary)) < missing) { curr_window_unary = *(curr_ptr_unary++); missing -= cnt; valid_lower_bits_unary = 64; } cnt = select64(curr_window_unary, missing - 1); curr_window_unary >>= cnt; curr_window_unary >>= 1; valid_lower_bits_unary -= cnt + 1; curr_fixed_offset += fixed_len; } void readReset(const size_t bit_pos, const size_t unary_offset) { // assert(bit_pos < bit_count); curr_fixed_offset = bit_pos; size_t unary_pos = bit_pos + unary_offset; curr_ptr_unary = &data + unary_pos / 64; curr_window_unary = *(curr_ptr_unary++) >> (unary_pos & 63); valid_lower_bits_unary = 64 - (unary_pos & 63); } }; Reader reader() const { return Reader(data); } }; } // namespace sux::function
32.563452
91
0.577864
[ "vector" ]
70e043d5e97c29ffbd9f41e362bd2ff37c6d5088
12,996
hh
C++
docs/tufte/tufte.hh
notsue/HaHa
c7969bb3b54121f117f96ffacb96661f7d11eecc
[ "MIT" ]
null
null
null
docs/tufte/tufte.hh
notsue/HaHa
c7969bb3b54121f117f96ffacb96661f7d11eecc
[ "MIT" ]
null
null
null
docs/tufte/tufte.hh
notsue/HaHa
c7969bb3b54121f117f96ffacb96661f7d11eecc
[ "MIT" ]
null
null
null
<NT:=span,class=newthought > <INPUT:=input,type=checkbox,class=margin-toggle > <SLABEL:=label,class=margin-toggle_sidenote-number > <SN:=span,class=sidenote > <MLABEL:=label,c=margin-toggle > <MN:=span,marginnote > <PY:=code,language-python > <article < <a,index.html Home > > <h1,dc.title,i=Tufte-CSS HaHa's Tufte CSS > <p,dc.creator,c=subtitle NotSue > <section <,dc.description <a,https://github.com/edwardtufte/tufte-css Tufte CSS > provides tools to style web articles using the ideas demonstrated by Edward Tufte’s books and handouts. Tufte’s style is known for its simplicity, extensive use of sidenotes, tight integration of graphics with text, and carefully chosen typography. > < Tufte CSS was created by <a,http://www.daveliepmann.com Dave Liepmann >. The original idea was cribbed from <a,https://tufte-latex.github.io/tufte-latex/ <span Tufte- ><span,latex <span L ><span,latex-sup a ><span T><span,latex-sub e ><span X > > > and <a,http://rmarkdown.rstudio.com/tufte\_handout\_format.html R Markdown’s Tufte Handout format >. > < The <a,https://github.com/notsue/HaHa HaHa project > used <em Tufte CSS > and it's corresponding HTML as a test. With this more demanding HTML-structure, it was shown that HaHa-reader version 0.4 could use some improvements. > section> <div,header Contents > <TOC > <section <h2,i=Tufte-CSS-howto Tufte CSS Howto > < Use <code tufte.css > and the <code et-book > directory of font files. With the HaHa-reader this is done with the <code --css tufte > option. > < HaHa created extra <code tufte-haha.css > with some style for numbering of headers (if option <code -n > in on) and for the table of contents if <code \<TOC \> > is inserted. > < Tufte CSS uses <code h1 > for the document title, <code p > with class <code subtitle > for the document subtitle, <code h2 > for section headings, and <code h3 > for low-level headings. More specific headings are not supported. > < Links in Tufte CSS match the body text in color and do not change on mouseover or when clicked. The underline effect is achieved using CSS trickery involving background gradients instead of standard <code text-decoration >. Credit goes to <a,https://adamschwartz.co/ Adam Schwartz > for that technique. > < <NT In his later books >, Tufte starts each section with a bit of vertical space, a non-indented paragraph, and the first few words of the sentence set in small caps. For this <i Tufte CSS > uses a span with the class <code newthought >, as demonstrated at the beginning of this paragraph. In HaHa we use predefined tag-name NT: <code \<NT:=span,class=newthought \> >. > <,sans If you prefer sans-serifs, use the <code sans > class. It relies on Gill Sans, Tufte’s sans-serif font of choice. > <h3,i=code Code > < Technical jargon, programming language terms, and code samples are denoted with the <code code > element. <em Tufte CSS > follows GitHub’s font selection, which shifts gracefully along the monospace spectrum from the elegant but rare Consolas all the way to good old reliable Courier. > < Extended code examples should live in a <code code > element within a <code pre > element. This adds control over indentation and overflow as well: > <pre <PY,title=tufte.py !------------ import sys sys.path.append('../../') import hh config = {'sourcefile':'demo.hh', 'outputfile':None, 'toc':2, 'h1':0, 'numbers': 1, 'includes': 3 , 'x3d': 1, 'css':'tufte', 'katex':1, 'highlight': 1, 'dir':'ltr', 'lang':'en', 'class': 'hh', 'view': 1} doc = hh.Document(config) print(doc.dublin_core['dc.title']) print('DONE... with Tufte CSS') !------------ >> < When <em Highlight.js > is activated with option <code -H > , the HaHa-reader uses by default <code github.min.css >, with the same font. > <h3,i=epigraphs Epigraphs > <div,epigraph <blockquote < The English language . . . becomes ugly and inaccurate because our thoughts are foolish, but the slovenliness of our language makes it easier for us to have foolish thoughts. > <footer George Orwell, "Politics and the English Language" footer> blockquote> <blockquote < For a successful technology, reality must take precedence over public relations, for Nature cannot be fooled. > <footer Richard P. Feynman, <cite "What Do You Care What Other People Think?" > > blockquote> <blockquote I do not paint things, I paint only the differences between things. <footer Henri Matisse, <cite Henri Matisse Dessins: thèmes et variations > (Paris, 1943), 37 > blockquote> div> < If you’d like to introduce your page or a section of your page with some quotes, use epigraphs. Modeled after chapter epigraphs in Tufte’s books (particularly <em Beautiful Evidence >), these are <code blockquote > elements, children of a block <code \<div class='epigraph' \> >. The source goes in a <code footer > element inside the <code blockquote >. We have reused three examples of <em Tufte CSS > in the epigraph of this section, demonstrating shorter and longer quotes, with and without a paragraph tag, and showing how multiple quotes within an epigraph fit together with the use of wrapper class <code epigraph >. > section> <section <h2,i=sidenotes Sidenotes > <h3 With numbers > < One of the most distinctive features of Tufte’s style is his extensive use of sidenotes <SLABEL,for=sn-example-sidenote > <INPUT,id=sn-example-sidenote > <SN This is a sidenote. Sidenotes are like footnotes, except they don’t force the reader to jump their eye to the bottom of the page. >. On sufficiently large viewports, Tufte CSS uses the margin for sidenotes, margin notes, and small figures. On smaller viewports, elements that would go in the margin are hidden until the user toggles them into view. > < Sidenotes consist of two elements: a superscript reference number that goes inline with the text, and a sidenote with content. To add the former, just put a label and dummy checkbox into the text where you want the reference to go, like so: > <pre <code,language-html !------------- &lt;label for="sn-sidenote-example" class="margin-toggle sidenote-number"&gt;&lt;/label&gt; &lt;input type="checkbox" id="sn-sidenote-example" class="margin-toggle"/&gt; &lt;span class="sidenote"&gt; ... sidenote text ... &lt;/span&gt; !------------- >> < In HaHa we can define some tags, with <code \<SLABEL:=label,class=margin-toggle_sidenote-number \> > and <code \<INPUT:=input,type=checkbox,class=margin-toggle \> > and <code \<SN:=span,class=sidenote \> >. As demostrated in the hh-markup of this article, this reduces the markup to: > <pre <code,nohighlight !------------- &lt;SLABEL,for=sn-sidenote-example &gt; &lt;INPUT,i=sn-sidenote-example &gt; &lt;SN ... sidenote text ... &gt; !------------- >> <h3 Without numbers > < If you want a sidenote without footnote-style numberings, then you want a margin note. <MLABEL,for=mn-demo &#8314; > <INPUT,id=mn-demo > <MN This is a margin note. Notice there isn't a number preceding the note. > On large screens, a margin note omits the reference number. On small screens, a margin note is like a sidenote except its viewability-toggle is a symbol rather than a reference number. This document currently uses the symbol &#8314; ( <code &amp;#8314; > ). Liepmann uses &#8853;. We've tried creating some similarity between numbered and anonymous notes. > < Again, in HaHa we can define the specific tags with <code \<MLABEL:=label,margin-toggle \> > and <code \<MN:=span,marginnote \> >, while <code \<INPUT > remains the same: > <pre <code,nohighlight !------------- &lt;MLABEL,for=mn-demo &#8314; &gt; &lt;INPUT,i=mn-demo &gt; &lt;MN ... marginnote text ... &gt; !------------- >> section> <section <h2,id=figures Figures > < We are still using content from Liepmann's <a,https://github.com/edwardtufte/tufte-css Tufte CSS > to demonstate figures. > < Figures should try to use the <code figure > element, which by default are constrained to the main column. Don’t wrap figures in a paragraph tag. Any label or margin note goes in a regular margin note inside the figure. For example, most of the time one should introduce a figure directly into the main flow of discussion, like so: > <figure <MLABEL,for=mn-exports-imports &#8314; > <INPUT,id=mn-exports-imports > <MN From Edward Tufte, <em Visual Display of Quantitative Information >, page 92. > <img,exports-imports.png,alt=Exports_and_Imports_to_and_from_Denmark_&amp;_Norway_from_1700_to_1780 > figure> < <MLABEL,for=mn-figure-1 &#8314; > <INPUT,id=mn-figure-1 > <MN <img,rhino.png,alt=Image_of_a_Rhinoceros > F.J. Cole, "The History of Albrecht Dürer’s Rhinoceros in Zooological Literature," <em Science, Medicine, and History: Essays on the Evolution of Scientific Thought and Medical Practice > (London, 1953), ed. E. Ashworth Underwood, 337-356. From page 71 of Edward Tufte’s <em Visual Explanations >. > But tight integration of graphics with text is central to Tufte’s work even when those graphics are ancillary to the main body of a text. In many of those cases, a margin figure may be most appropriate. To place figures in the margin, just wrap an image (or whatever) in a margin note inside a <code p > tag, as seen to the right of this paragraph. > < If you need a full-width figure, give it the <code fullwidth > class. Make sure that’s inside an <code article >, and it will take up (almost) the full width of the screen. This approach is demonstrated below using Edward Tufte’s English translation of the Napoleon’s March data visualization. From <em Beautiful Evidence >, page 122-124. > <figure,fullwidth <img,napoleons-march.png,alt=Figurative_map_of_the_successive_losses_of_the_French_Army_in_the_Russian_campaign_1812-1813 > figure> < One obstacle to creating elegant figures on the web is the difficulty of handling different screen sizes, especially on the fly. Embedded <code iframe > elements are particularly troublesome. For these instances we wrap the element <code \<iframe > in a <code \<figure,iframe-wrapper >. > < You can use <code div > instead of <code figure >, with slightly different results but the same general effect. > <figure,iframe-wrapper <iframe,width=853,height=480,src=https://www.youtube.com/embed/YslQ2625TR4,frameborder=0,allowfullscreen= > figure> < We could not wait with this expriment with a sphere, a cube and a cone: <MLABEL,for=mn-x3d &#8314; > <INPUT,id=mn-x3d > <MN !------------------- <x3d> <scene> <shape> <appearance> <Material ambientIntensity='0.4' diffuseColor='0.8,0,0' emissiveColor='0,0,0' metadata='X3DMetadataObject' shininess='0.2' specularColor='0,0,0' transparency='0.5' ></Material> </appearance> <box></box> </shape> <transform translation='-3 0 0'> <shape> <appearance> <material diffuseColor='0 1 0'></material> </appearance> <cone></cone> </shape> </transform> <transform translation='3 0 0'> <shape> <appearance> <material diffuseColor='0 0 1'></material> </appearance> <sphere></sphere> </shape> </transform> </scene> </x3d> !-------------------- Use left mouse-button to rotate and right mouse button to zoom in and out. > x3d in the margin. We've removed the usual width- and height-attributes from x3d-element. > < If that is not your cup of tea, Tufte CSS also provides support for Edward Tufte and Adam Schwartz’s <a,http://imagequilts.com/ ImageQuilts >. > section> <section <h2,epilogue Epilogue > < As usual we have extracted some metadata from the content (see meta-elements in <code HTML-head >). Try printing: the url's are added to the bottem of the article. > < One final margin note. <MLABEL,for=sn-euler &#8314; > <INPUT,i=sn-euler > <MN $ e^{i\pi} + 1 = 0 $ > Here we use <a,https://katex.org/ <span,latex <span K ><span,latex-sup a ><span T><span,latex-sub e ><span X > > a> with the <a,https://katex.org/docs/autorender.html <em auto-render extension > >. > section> article>
50.177606
182
0.663435
[ "render", "shape", "transform" ]
70e3da677d81ede97e01b9dd19328d1b8352e7ac
6,324
hpp
C++
hpx/util/ochunk_manager.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/util/ochunk_manager.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/util/ochunk_manager.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // // 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) #if !defined(HPX_UTIL_OCHUNK_MANAGER_JUL_31_2013_1158AM) #define HPX_UTIL_OCHUNK_MANAGER_JUL_31_2013_1158AM #include <hpx/util/binary_filter.hpp> #include <cstddef> // for size_t #include <cstring> // for memcpy #include <vector> namespace hpx { namespace util { namespace detail { /////////////////////////////////////////////////////////////////////// struct erase_ocontainer_type { virtual ~erase_ocontainer_type() {} virtual void set_filter(binary_filter* filter) = 0; virtual void save_binary(void const* address, std::size_t count) = 0; virtual void save_binary_chunk(void const* address, std::size_t count) = 0; }; template <typename Container> struct ocontainer_type : erase_ocontainer_type { private: std::size_t get_chunk_size(std::size_t chunk) const { return (*chunks_)[chunk].size_; } void set_chunk_size(std::size_t chunk, std::size_t size) { (*chunks_)[chunk].size_ = size; } boost::uint8_t get_chunk_type(std::size_t chunk) const { return (*chunks_)[chunk].type_; } chunk_data get_chunk_data(std::size_t chunk) const { return (*chunks_)[chunk].data_; } std::size_t get_num_chunks() const { return chunks_->size(); } public: ocontainer_type(Container& cont) : cont_(cont), current_(0), start_compressing_at_(0), filter_(0), chunks_(0), current_chunk_(std::size_t(-1)) {} ocontainer_type(Container& cont, std::vector<serialization_chunk>* chunks) : cont_(cont), current_(0), start_compressing_at_(0), filter_(0), chunks_(chunks), current_chunk_(std::size_t(-1)) { if (chunks_) { chunks_->clear(); chunks_->push_back(create_index_chunk(0, 0)); current_chunk_ = 0; } } ~ocontainer_type() { if (filter_) { std::size_t written = 0; if (cont_.size() < current_) cont_.resize(current_); current_ = start_compressing_at_; do { bool flushed = filter_->flush(&cont_[current_], cont_.size()-current_, written); current_ += written; if (flushed) break; // resize container cont_.resize(cont_.size()*2); } while (true); cont_.resize(current_); // truncate container } else if (chunks_) { HPX_ASSERT( get_chunk_type(current_chunk_) == chunk_type_index || get_chunk_size(current_chunk_) != 0); // complement current serialization_chunk by setting its length if (get_chunk_type(current_chunk_) == chunk_type_index) { HPX_ASSERT(get_chunk_size(current_chunk_) == 0); set_chunk_size(current_chunk_, current_ - get_chunk_data(current_chunk_).index_); } } } void set_filter(binary_filter* filter) { HPX_ASSERT(0 == filter_); filter_ = filter; start_compressing_at_ = current_; if (chunks_) { HPX_ASSERT(get_num_chunks() == 1 && get_chunk_size(0) == 0); chunks_->clear(); } } void save_binary(void const* address, std::size_t count) { HPX_ASSERT(count != 0); { if (filter_) { filter_->save(address, count); } else { // make sure there is a current serialization_chunk descriptor available if (chunks_ && (get_chunk_type(current_chunk_) == chunk_type_pointer || get_chunk_size(current_chunk_) != 0)) { // add a new serialization_chunk chunks_->push_back(create_index_chunk(current_, 0)); ++current_chunk_; } if (cont_.size() < current_ + count) cont_.resize(cont_.size() + count); if (count == 1) cont_[current_] = *static_cast<unsigned char const*>(address); else std::memcpy(&cont_[current_], address, count); } current_ += count; } } void save_binary_chunk(void const* address, std::size_t count) { if (filter_ || chunks_ == 0 || count < HPX_ZERO_COPY_SERIALIZATION_THRESHOLD) { // fall back to serialization_chunk-less archive this->ocontainer_type::save_binary(address, count); } else { HPX_ASSERT( get_chunk_type(current_chunk_) == chunk_type_index || get_chunk_size(current_chunk_) != 0); // complement current serialization_chunk by setting its length if (get_chunk_type(current_chunk_) == chunk_type_index) { HPX_ASSERT(get_chunk_size(current_chunk_) == 0); set_chunk_size(current_chunk_, current_ - get_chunk_data(current_chunk_).index_); } // add a new serialization_chunk referring to the external buffer chunks_->push_back(create_pointer_chunk(address, count)); ++current_chunk_; } } Container& cont_; std::size_t current_; std::size_t start_compressing_at_; binary_filter* filter_; std::vector<serialization_chunk>* chunks_; std::size_t current_chunk_; }; }}} #endif
32.9375
92
0.517236
[ "vector" ]
70e631cfeaae7d02e0ed92672008466a03520fee
14,980
cpp
C++
src/eepp/graphics/renderer/renderergl3cp.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/graphics/renderer/renderergl3cp.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
src/eepp/graphics/renderer/renderergl3cp.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#include <eepp/graphics/renderer/openglext.hpp> #include <eepp/graphics/renderer/renderergl3cp.hpp> #ifdef EE_GL3_ENABLED #include <eepp/graphics/renderer/rendererstackhelper.hpp> #include <eepp/system/filesystem.hpp> #include <eepp/system/log.hpp> namespace EE { namespace Graphics { const char* EEGL3CP_STATES_NAME[] = {"dgl_Vertex", "dgl_Normal", "dgl_FrontColor"}; const char* EEGL3CP_TEXTUREUNIT_NAMES[] = {"dgl_MultiTexCoord0", "dgl_MultiTexCoord1", "dgl_MultiTexCoord2", "dgl_MultiTexCoord3"}; const char* EEGL3CP_PLANES_ENABLED_NAME[] = {"dgl_ClipEnabled[0]", "dgl_ClipEnabled[1]", "dgl_ClipEnabled[2]", "dgl_ClipEnabled[3]", "dgl_ClipEnabled[4]", "dgl_ClipEnabled[5]"}; const char* EEGL3CP_PLANES_NAME[] = {"dgl_ClipPlane[0]", "dgl_ClipPlane[1]", "dgl_ClipPlane[2]", "dgl_ClipPlane[3]", "dgl_ClipPlane[4]", "dgl_ClipPlane[5]"}; #ifdef EE_GLES2 const GLchar* GL3CP_SHADER_HEAD = "precision mediump float;\nprecision lowp int;\n"; #else const GLchar* GL3CP_SHADER_HEAD = "#version 330\n"; #endif #if !defined( EE_GLES2 ) #include "shaders/basegl3cp.vert.h" #include "shaders/basegl3cp.frag.h" #else #include "shaders/basegl3cp.gles2.vert.h" #include "shaders/basegl3cp.gles2.frag.h" #endif RendererGL3CP::RendererGL3CP() : RendererGLShader(), mTexActive( 1 ), mTexActiveLoc( -1 ), mPointSpriteLoc( -1 ), mPointSize( 1.f ), mCurActiveTex( 0 ), mCurTexCoordArray( 0 ), mVBOSizeAlloc( 1024 * 1024 ), mBiggestAlloc( 0 ), mLoaded( false ) { mQuadsSupported = false; mQuadVertexs = 6; } RendererGL3CP::~RendererGL3CP() { for ( Uint32 i = 0; i < eeARRAY_SIZE( mVBO ); i++ ) { if ( 0 != mVBO[i] ) { glDeleteBuffersARB( 1, &mVBO[i] ); } } deleteVertexArrays( 1, &mVAO ); #ifdef EE_DEBUG Log::instance()->writel( "Biggest VBO allocation on GL3 Renderer: " + FileSystem::sizeToString( mBiggestAlloc ) ); #endif } GraphicsLibraryVersion RendererGL3CP::version() { return GLv_3CP; } std::string RendererGL3CP::versionStr() { return "OpenGL 3 Core Profile"; } void RendererGL3CP::init() { if ( !mLoaded ) { Uint32 i; Renderer::init(); std::string vs( GL3CP_SHADER_HEAD ); std::string fs( GL3CP_SHADER_HEAD ); vs += EEGL3CP_SHADER_BASE_VS; fs += EEGL3CP_SHADER_BASE_FS; mBaseVertexShader = vs; for ( i = 0; i < EEGL_ARRAY_STATES_COUNT; i++ ) { mAttribsLoc[i] = -1; mAttribsLocStates[i] = 0; } for ( i = 0; i < eeARRAY_SIZE( mVBO ); i++ ) mVBO[i] = 0; for ( i = 0; i < EE_MAX_PLANES; i++ ) { mPlanes[i] = -1; mPlanesStates[i] = 0; } for ( i = 0; i < EE_MAX_TEXTURE_UNITS; i++ ) { mTextureUnits[i] = -1; mTextureUnitsStates[i] = 0; } Shader::ensure( false ); mShaders[EEGL3CP_SHADER_BASE] = ShaderProgram::New( vs.c_str(), vs.size(), fs.c_str(), fs.size() ); mShaders[EEGL3CP_SHADER_BASE]->setReloadCb( cb::Make1( this, &RendererGL3CP::reloadShader ) ); Shader::ensure( true ); } else { mCurShader = NULL; mShaders[EEGL3CP_SHADER_BASE]->reload(); } genVertexArrays( 1, &mVAO ); bindVertexArray( mVAO ); glGenBuffersARB( EEGL_ARRAY_STATES_COUNT + 5, &mVBO[0] ); allocateBuffers( mVBOSizeAlloc ); clientActiveTexture( GL_TEXTURE0 ); setShader( mShaders[EEGL3CP_SHADER_BASE] ); mLoaded = true; } unsigned int RendererGL3CP::baseShaderId() { return mCurShader->getHandler(); } void RendererGL3CP::reloadCurrentShader() { reloadShader( mCurShader ); } void RendererGL3CP::reloadShader( ShaderProgram* Shader ) { mCurShader = NULL; setShader( Shader ); } void RendererGL3CP::setShader( const EEGL3CP_SHADERS& Shader ) { setShader( mShaders[Shader] ); } void RendererGL3CP::setShader( ShaderProgram* Shader ) { if ( NULL == Shader ) { Shader = mShaders[EEGL3CP_SHADER_BASE]; } if ( mCurShader == Shader ) { return; } disableClientState( GL_VERTEX_ARRAY ); disableClientState( GL_TEXTURE_COORD_ARRAY ); disableClientState( GL_COLOR_ARRAY ); mShaderPrev = mCurShader; mCurShader = Shader; mProjectionMatrix_id = mCurShader->getUniformLocation( "dgl_ProjectionMatrix" ); mModelViewMatrix_id = mCurShader->getUniformLocation( "dgl_ModelViewMatrix" ); mTextureMatrix_id = mCurShader->getUniformLocation( "dgl_TextureMatrix" ); mTexActiveLoc = mCurShader->getUniformLocation( "dgl_TexActive" ); mPointSpriteLoc = mCurShader->getUniformLocation( "dgl_PointSpriteActive" ); mClippingEnabledLoc = mCurShader->getUniformLocation( "dgl_ClippingEnabled" ); mCurActiveTex = 0; Uint32 i; for ( i = 0; i < EEGL_ARRAY_STATES_COUNT; i++ ) { mAttribsLoc[i] = mCurShader->getAttributeLocation( EEGL3CP_STATES_NAME[i] ); } for ( i = 0; i < EE_MAX_PLANES; i++ ) { mPlanes[i] = mCurShader->getUniformLocation( EEGL3CP_PLANES_NAME[i] ); } for ( i = 0; i < EE_MAX_TEXTURE_UNITS; i++ ) { mTextureUnits[i] = mCurShader->getAttributeLocation( EEGL3CP_TEXTUREUNIT_NAMES[i] ); } glUseProgram( mCurShader->getHandler() ); if ( -1 != mAttribsLoc[EEGL_VERTEX_ARRAY] ) enableClientState( GL_VERTEX_ARRAY ); if ( -1 != mAttribsLoc[EEGL_COLOR_ARRAY] ) enableClientState( GL_COLOR_ARRAY ); if ( -1 != mTextureUnits[mCurActiveTex] ) enableClientState( GL_TEXTURE_COORD_ARRAY ); unsigned int CM = mCurrentMode; matrixMode( GL_TEXTURE ); updateMatrix(); matrixMode( GL_PROJECTION ); updateMatrix(); matrixMode( GL_MODELVIEW ); updateMatrix(); matrixMode( CM ); if ( -1 != mTexActiveLoc ) { mCurShader->setUniform( mTexActiveLoc, 1 ); } mCurShader->setUniform( mClippingEnabledLoc, 0 ); for ( i = 0; i < EE_MAX_PLANES; i++ ) { if ( -1 != mPlanes[i] ) { mCurShader->setUniform( EEGL3CP_PLANES_ENABLED_NAME[i], 0 ); } } if ( -1 != mPointSpriteLoc ) { mCurShader->setUniform( mPointSpriteLoc, 0 ); } } void RendererGL3CP::enable( unsigned int cap ) { switch ( cap ) { case GL_TEXTURE_2D: { if ( 0 == mTexActive ) { mTexActive = 1; mCurShader->setUniform( mTexActiveLoc, mTexActive ); mCurShader->setUniform( mTextureUnits[mCurActiveTex], mCurActiveTex ); } return; } case GL_CLIP_PLANE0: case GL_CLIP_PLANE1: case GL_CLIP_PLANE2: case GL_CLIP_PLANE3: case GL_CLIP_PLANE4: case GL_CLIP_PLANE5: { int plane = cap - GL_CLIP_PLANE0; if ( 0 == mPlanesStates[plane] ) { mPlanesStates[plane] = 1; planeStateCheck( true ); mCurShader->setUniform( EEGL3CP_PLANES_ENABLED_NAME[plane], 1 ); } return; } case GL_POINT_SPRITE: { mCurShader->setUniform( mPointSpriteLoc, 1 ); return; } } Renderer::enable( cap ); } void RendererGL3CP::disable( unsigned int cap ) { switch ( cap ) { case GL_TEXTURE_2D: { if ( 1 == mTexActive ) { mTexActive = 0; mCurShader->setUniform( mTexActiveLoc, mTexActive ); } return; } case GL_CLIP_PLANE0: case GL_CLIP_PLANE1: case GL_CLIP_PLANE2: case GL_CLIP_PLANE3: case GL_CLIP_PLANE4: case GL_CLIP_PLANE5: { int plane = cap - GL_CLIP_PLANE0; if ( 1 == mPlanesStates[plane] ) { mPlanesStates[plane] = 0; planeStateCheck( false ); mCurShader->setUniform( EEGL3CP_PLANES_ENABLED_NAME[plane], 0 ); } return; } case GL_POINT_SPRITE: { mCurShader->setUniform( mPointSpriteLoc, 0 ); return; } } Renderer::disable( cap ); } void RendererGL3CP::enableClientState( unsigned int array ) { int state; if ( GL_TEXTURE_COORD_ARRAY == array ) { if ( -1 != ( state = mTextureUnits[mCurActiveTex] ) ) { mTextureUnitsStates[mCurActiveTex] = 1; glEnableVertexAttribArray( state ); } } else { Int32 Pos = array - GL_VERTEX_ARRAY; if ( -1 != ( state = mAttribsLoc[Pos] ) ) { mAttribsLocStates[Pos] = 1; glEnableVertexAttribArray( state ); } } } void RendererGL3CP::disableClientState( unsigned int array ) { int state; if ( GL_TEXTURE_COORD_ARRAY == array ) { if ( -1 != ( state = mTextureUnits[mCurActiveTex] ) ) { mTextureUnitsStates[mCurActiveTex] = 0; glDisableVertexAttribArray( state ); } } else { Int32 Pos = array - GL_VERTEX_ARRAY; if ( -1 != ( state = mAttribsLoc[Pos] ) ) { mAttribsLocStates[Pos] = 0; glDisableVertexAttribArray( state ); } } } void RendererGL3CP::vertexPointer( int size, unsigned int type, int stride, const void* pointer, unsigned int allocate ) { const int index = mAttribsLoc[EEGL_VERTEX_ARRAY]; #ifdef EE_DEBUG mBiggestAlloc = eemax( mBiggestAlloc, allocate ); #endif if ( -1 != index ) { bindVertexArray( mVAO ); if ( allocate > mVBOSizeAlloc ) { allocateBuffers( allocate ); } glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_VERTEX_ARRAY] ); glBufferSubDataARB( GL_ARRAY_BUFFER, 0, allocate, pointer ); if ( 0 == mAttribsLocStates[EEGL_VERTEX_ARRAY] ) { mAttribsLocStates[EEGL_VERTEX_ARRAY] = 1; glEnableVertexAttribArray( index ); } if ( type == GL_UNSIGNED_BYTE ) { glVertexAttribPointerARB( index, size, type, GL_TRUE, stride, 0 ); } else { glVertexAttribPointerARB( index, size, type, GL_FALSE, stride, 0 ); } } } void RendererGL3CP::colorPointer( int size, unsigned int type, int stride, const void* pointer, unsigned int allocate ) { const int index = mAttribsLoc[EEGL_COLOR_ARRAY]; #ifdef EE_DEBUG mBiggestAlloc = eemax( mBiggestAlloc, allocate ); #endif if ( -1 != index ) { bindVertexArray( mVAO ); if ( allocate > mVBOSizeAlloc ) { allocateBuffers( allocate ); } glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_COLOR_ARRAY] ); glBufferSubDataARB( GL_ARRAY_BUFFER, 0, allocate, pointer ); if ( 0 == mAttribsLocStates[EEGL_COLOR_ARRAY] ) { mAttribsLocStates[EEGL_COLOR_ARRAY] = 1; glEnableVertexAttribArray( index ); } if ( type == GL_UNSIGNED_BYTE ) { glVertexAttribPointerARB( index, size, type, GL_TRUE, stride, 0 ); } else { glVertexAttribPointerARB( index, size, type, GL_FALSE, stride, 0 ); } } } void RendererGL3CP::texCoordPointer( int size, unsigned int type, int stride, const void* pointer, unsigned int allocate ) { const int index = mTextureUnits[mCurActiveTex]; #ifdef EE_DEBUG mBiggestAlloc = eemax( mBiggestAlloc, allocate ); #endif if ( -1 != index ) { bindVertexArray( mVAO ); if ( allocate > mVBOSizeAlloc ) { allocateBuffers( allocate ); } glBindBufferARB( GL_ARRAY_BUFFER, mCurTexCoordArray ); glBufferSubDataARB( GL_ARRAY_BUFFER, 0, allocate, pointer ); if ( 0 == mTextureUnitsStates[mCurActiveTex] ) { mTextureUnitsStates[mCurActiveTex] = 1; glEnableVertexAttribArray( index ); } glVertexAttribPointerARB( index, size, type, GL_FALSE, stride, 0 ); } } int RendererGL3CP::getStateIndex( const Uint32& State ) { eeASSERT( State < EEGL_ARRAY_STATES_COUNT ); if ( EEGL_TEXTURE_COORD_ARRAY == State ) return mTextureUnits[mCurActiveTex]; return mAttribsLoc[State]; } void RendererGL3CP::planeStateCheck( bool tryEnable ) { int i; if ( tryEnable ) { for ( i = 0; i < EE_MAX_PLANES; i++ ) { if ( 0 != mPlanesStates[i] ) { mCurShader->setUniform( mClippingEnabledLoc, 1 ); return; } } } else { for ( i = 0; i < EE_MAX_PLANES; i++ ) { if ( 0 != mPlanesStates[i] ) { return; } } mCurShader->setUniform( mClippingEnabledLoc, 0 ); } } void RendererGL3CP::clip2DPlaneEnable( const Int32& x, const Int32& y, const Int32& Width, const Int32& Height ) { Rectf r( x, y, x + Width, y + Height ); glm::vec4 vclip_left( 1.0, 0.0, 0.0, -r.Left ); glm::vec4 vclip_right( -1.0, 0.0, 0.0, r.Right ); glm::vec4 vclip_top( 0.0, 1.0, 0.0, -r.Top ); glm::vec4 vclip_bottom( 0.0, -1.0, 0.0, r.Bottom ); glm::mat4 invMV = glm::inverse( mStack->mModelViewMatrix.top() ); vclip_left = vclip_left * invMV; vclip_right = vclip_right * invMV; vclip_top = vclip_top * invMV; vclip_bottom = vclip_bottom * invMV; GLi->enable( GL_CLIP_PLANE0 ); GLi->enable( GL_CLIP_PLANE1 ); GLi->enable( GL_CLIP_PLANE2 ); GLi->enable( GL_CLIP_PLANE3 ); glUniform4fv( mPlanes[0], 1, static_cast<const float*>( &vclip_left[0] ) ); glUniform4fv( mPlanes[1], 1, static_cast<const float*>( &vclip_right[0] ) ); glUniform4fv( mPlanes[2], 1, static_cast<const float*>( &vclip_top[0] ) ); glUniform4fv( mPlanes[3], 1, static_cast<const float*>( &vclip_bottom[0] ) ); } void RendererGL3CP::clip2DPlaneDisable() { GLi->disable( GL_CLIP_PLANE0 ); GLi->disable( GL_CLIP_PLANE1 ); GLi->disable( GL_CLIP_PLANE2 ); GLi->disable( GL_CLIP_PLANE3 ); } void RendererGL3CP::pointSize( float size ) { mCurShader->setUniform( "dgl_PointSize", size ); mPointSize = size; } void RendererGL3CP::clipPlane( unsigned int plane, const double* equation ) { Int32 nplane = plane - GL_CLIP_PLANE0; Int32 location; if ( nplane < EE_MAX_PLANES ) { location = mPlanes[nplane]; } else { std::string planeNum( "dgl_ClipPlane[" + String::toString( nplane ) + "]" ); location = glGetUniformLocation( mCurShader->getHandler(), (GLchar*)&planeNum[0] ); } glm::vec4 teq( equation[0], equation[1], equation[2], equation[3] ); teq = teq * glm::inverse( mStack->mModelViewMatrix .top() ); /// Apply the inverse of the model view matrix to the equation glUniform4f( location, (float)teq[0], (float)teq[1], (float)teq[2], (float)teq[3] ); } float RendererGL3CP::pointSize() { return mPointSize; } void RendererGL3CP::clientActiveTexture( unsigned int texture ) { mCurActiveTex = texture - GL_TEXTURE0; if ( mCurActiveTex >= EE_MAX_TEXTURE_UNITS ) mCurActiveTex = 0; switch ( mCurActiveTex ) { case 0: mCurTexCoordArray = mVBO[EEGL_TEXTURE_COORD_ARRAY]; break; case 1: mCurTexCoordArray = mVBO[EEGL_TEXTURE_COORD_ARRAY + 1]; break; case 2: mCurTexCoordArray = mVBO[EEGL_TEXTURE_COORD_ARRAY + 2]; break; case 3: mCurTexCoordArray = mVBO[EEGL_TEXTURE_COORD_ARRAY + 3]; break; } } std::string RendererGL3CP::getBaseVertexShader() { return mBaseVertexShader; } void RendererGL3CP::bindGlobalVAO() { bindVertexArray( mVAO ); } void RendererGL3CP::allocateBuffers( const Uint32& size ) { if ( mVBOSizeAlloc != size ) Log::instance()->writel( "Allocating new VBO buffers size: " + String::toString( size ) ); mVBOSizeAlloc = size; glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_VERTEX_ARRAY] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_COLOR_ARRAY] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_TEXTURE_COORD_ARRAY] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_TEXTURE_COORD_ARRAY + 1] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_TEXTURE_COORD_ARRAY + 2] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); glBindBufferARB( GL_ARRAY_BUFFER, mVBO[EEGL_TEXTURE_COORD_ARRAY + 3] ); glBufferDataARB( GL_ARRAY_BUFFER, mVBOSizeAlloc, NULL, GL_STREAM_DRAW ); } }} // namespace EE::Graphics #endif
25.050167
98
0.697063
[ "model" ]
70e84a400327772a513380fa2a309c3e94ec88b2
12,770
cpp
C++
src/core_apps.cpp
matadini/TechDemo-SFML-Box2D
fff2d0850c7cfb68926114857abfaf2a8b00e257
[ "Zlib" ]
null
null
null
src/core_apps.cpp
matadini/TechDemo-SFML-Box2D
fff2d0850c7cfb68926114857abfaf2a8b00e257
[ "Zlib" ]
null
null
null
src/core_apps.cpp
matadini/TechDemo-SFML-Box2D
fff2d0850c7cfb68926114857abfaf2a8b00e257
[ "Zlib" ]
null
null
null
/* TechDemo SFML/Box2D Copyright (C) 2016 Matadini (matadini@hotmail.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. External libraries used by TechDemo SFML/Box2D ------------------------------- * Qt5 is licensed under the LGPL license * PhysicsFS is licensed under the zlib license. * SFML is licensed under the zlib license. * Box2D is licensed under the zlib license. */ #include "core_apps.h" #include <iostream> #include <memory> #include <vector> #include "assets.h" #include "contact_detector.h" #include "movable_body.h" #include "identified_body.h" #include "control_keys.h" #include "fps_stabilizer.h" #include "body_mover.h" #include "globals.h" #include "editor.h" #include "box_creators.h" #include "game_world.h" void CoreApps::startExample() { sf::RenderWindow* windowItem = new sf::RenderWindow( sf::VideoMode(800, 600, 32), std::string("SFML/Box2D - tech demo"), sf::Style::Default); std::shared_ptr<sf::RenderWindow> window(windowItem); std::shared_ptr<ControlKeys>playerControl(new ControlKeys()); FpsStabilizer stabilizer(60); Assets::Resources resources("data.zip"); GameWorld world(resources); MovableBody* playerPtr = world.getPlayer(); ContactDetector* contactDetector = world.getContactDetector(); while(window->isOpen()) { /* OTHER */ stabilizer.work(); for(auto& item : world.listMovableBodies){ item->getRenderBody()->setColor(sf::Color::White); } /* EVENTS */ sf::Event myEvent; while(window->pollEvent(myEvent)) { if(myEvent.type == sf::Event::Closed){ window->close(); } } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_JUMP)) { playerPtr->getMover()->move( BodyMover::Direction::Jump); } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_RIGHT)) { playerPtr->getMover()->move( BodyMover::Direction::Right); DrawableBodyAnimated* ptr = (DrawableBodyAnimated*)playerPtr->getRenderBody(); ptr->getAnimator()->setAnimation(0); } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_LEFT)) { playerPtr->getMover()->move( BodyMover::Direction::Left); DrawableBodyAnimated* ptr = (DrawableBodyAnimated*)playerPtr->getRenderBody(); ptr->getAnimator()->setAnimation(1); } /* BOX2D */ world.prepareWorld(); for(auto& enemyItem : world.listMovableBodies) { break; } const bool contactCondition = (!contactDetector->isContactListIsEmpty()) && contactDetector->isContactListContains( ContactDetector::Contact::Type::PlayerTouchEnemy); if(contactCondition) { std::vector<ContactDetector::Contact::Info> enemyContacts = contactDetector->getContactList( ContactDetector::Contact::Type::PlayerTouchEnemy); if(!enemyContacts.empty()){ for(auto& contact : enemyContacts) { break; } } } /* RENDER */ window->clear(sf::Color::Black); for(auto& item : world.listMovableBodies){ item->getRenderBody()->update(); item->getRenderBody()->render(*window); } for(auto& item : world.listIdentifiedBodies){ item->getRenderBody()->render(*window); } window->display(); } } void beforeGameLoop(b2World& world) { const float32 timeStep = 1.0f / 60.0f; const int32 velocityIterations = 6; const int32 positionIterations = 2; world.Step( timeStep, velocityIterations, positionIterations); } void createArea( b2World* world, std::vector<IdentifiedBody>& list, Assets::Resources& resources) { IdentifiedBody mapPlatformTop( new DrawableBodyGenerated( BoxCreators::createStaticBody(world, 800, 40)), BodyUserData::Type::Map); mapPlatformTop.getRenderBody()->setPosition(400.f, 0.f); mapPlatformTop.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Map)); IdentifiedBody mapPlatformBottom( new DrawableBodyGenerated( BoxCreators::createStaticBody(world, 800, 40)), BodyUserData::Type::Map); mapPlatformBottom.getRenderBody()->setPosition(400.f, 600.f); mapPlatformBottom.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Map)); IdentifiedBody mapWallLeft( new DrawableBodyGenerated( BoxCreators::createStaticBody(world, 40, 800)), BodyUserData::Type::Wall); mapWallLeft.getRenderBody()->setPosition(0.f, 400.f); mapWallLeft.getRenderBody()->setVisable(false); mapWallLeft.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Wall)); IdentifiedBody mapWallRight( new DrawableBodyGenerated( BoxCreators::createStaticBody(world, 40, 800)), BodyUserData::Type::Wall); mapWallRight.getRenderBody()->setPosition(800.f, 400.f); mapWallRight.getRenderBody()->setVisable(false); mapWallRight.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Wall)); list.push_back(mapPlatformTop); list.push_back(mapPlatformBottom); list.push_back(mapWallLeft); list.push_back(mapWallRight); } void CoreApps::startSecondExample() { sf::RenderWindow* windowItem = new sf::RenderWindow( sf::VideoMode(800, 600, 32), std::string("SFML/Box2D - tech demo"), sf::Style::Default); std::shared_ptr<sf::RenderWindow> window(windowItem); std::shared_ptr<ControlKeys>playerControl(new ControlKeys()); FpsStabilizer stabilizer(60); /* Map section. */ ContactDetector myContactLister; std::unique_ptr<b2World> myWorld(BoxCreators::createWorld()); myWorld.get()->SetContactListener(&myContactLister); Assets::Resources resources("data.zip"); std::vector<IdentifiedBody> listWorldBodies; createArea(myWorld.get(), listWorldBodies, resources); /* Player item. */ sf::Texture playerTexture; if(!playerTexture.loadFromFile("walk.png")){ std::cout << __func__ << " -walki.png problem\n"; } sf::Vector2f oneFrameSize(104.f, 150.f); sf::Vector2f playerBodySize(75.f, 100.f); sf::RectangleShape shapeForAnimation; shapeForAnimation.setSize(playerBodySize); shapeForAnimation.setOrigin( shapeForAnimation.getSize().x/2, shapeForAnimation.getSize().y/2); shapeForAnimation.setPosition(sf::Vector2f(250, 250.f)); shapeForAnimation.setTexture(&playerTexture); MovableBody playerItem( new DrawableBodyAnimated( BoxCreators::createDynamicBody( myWorld.get(), playerBodySize.x, playerBodySize.y), new Animator( &shapeForAnimation, oneFrameSize)), BodyUserData::Type::Player); playerItem.getRenderBody()->setPosition(400.f, 10.f); playerItem.getMover()->setJumpForce(4.5f); /* Enemy A. */ MovableBody enemyItem( new DrawableBodyGenerated( BoxCreators::createDynamicBody(myWorld.get(), 90, 60)), BodyUserData::Type::Enemy); enemyItem.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Enemy)); enemyItem.getRenderBody()->setPosition(600.f, 50.f); enemyItem.getMover()->setJumpForce(3.f); enemyItem.getMover()->setMaxSpeed(2.5f); /* Enemy B. */ MovableBody enemyItemB( new DrawableBodyGenerated( BoxCreators::createDynamicBody(myWorld.get(), 90, 60)), BodyUserData::Type::Enemy); enemyItemB.getRenderBody()->setTexture( *resources.getTexture(Assets::Textures::Enemy)); enemyItemB.getRenderBody()->setPosition(150.f, 50.f); enemyItemB.getMover()->setJumpForce(3.f); enemyItemB.getMover()->setMaxSpeed(2.5f); /* Ewidencja wrogow. */ std::vector<MovableBody> listEnemies; listEnemies.push_back(enemyItem); listEnemies.push_back(enemyItemB); sf::Color backgroundColor; while(window->isOpen()) { /* OTHER */ stabilizer.work(); backgroundColor = sf::Color::Black; for(MovableBody& item : listEnemies){ item.getRenderBody()->setColor(sf::Color::White); } /* EVENTS */ sf::Event myEvent; while(window->pollEvent(myEvent)) { if(myEvent.type == sf::Event::Closed){ window->close(); } } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_JUMP)) { playerItem.getMover()->move( BodyMover::Direction::Jump); } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_RIGHT)) { playerItem.getMover()->move( BodyMover::Direction::Right); DrawableBodyAnimated* ptr = (DrawableBodyAnimated*)playerItem.getRenderBody(); ptr->getAnimator()->setAnimation(0); } if(sf::Keyboard::isKeyPressed(playerControl->MOVE_LEFT)) { playerItem.getMover()->move( BodyMover::Direction::Left); DrawableBodyAnimated* ptr = (DrawableBodyAnimated*)playerItem.getRenderBody(); ptr->getAnimator()->setAnimation(1); } /* BOX2D */ beforeGameLoop(*myWorld.get()); for(auto& enemyItem : listEnemies) { break; } const bool contactCondition = (!myContactLister.isContactListIsEmpty()) && myContactLister.isContactListContains( ContactDetector::Contact::Type::PlayerTouchEnemy); if(contactCondition) { std::vector<ContactDetector::Contact::Info> enemyContacts = myContactLister.getContactList( ContactDetector::Contact::Type::PlayerTouchEnemy); if(!enemyContacts.empty()){ for(auto& contact : enemyContacts) { break; } } } /* RENDER */ window->clear(backgroundColor); playerItem.getRenderBody()->update(); playerItem.getRenderBody()->render(*window); for(auto& item : listEnemies){ item.getRenderBody()->update(); item.getRenderBody()->render(*window); } for(auto& item : listWorldBodies){ item.getRenderBody()->render(*window); } window->display(); } }
29.906323
80
0.566014
[ "render", "vector" ]
70e8c913caa19955681f02a30eeafe7b123440c1
11,837
cpp
C++
src/raster04_rasterization.cpp
ysh86/raster
565568fd95e68a5e0886fc8d6754c8720aebe3bb
[ "MIT" ]
null
null
null
src/raster04_rasterization.cpp
ysh86/raster
565568fd95e68a5e0886fc8d6754c8720aebe3bb
[ "MIT" ]
null
null
null
src/raster04_rasterization.cpp
ysh86/raster
565568fd95e68a5e0886fc8d6754c8720aebe3bb
[ "MIT" ]
null
null
null
#include "vis.hpp" #define UNREACHABLE() assert(0) constexpr float Inf = 1e+8f; constexpr float Eps = 1e-4f; struct Framebuffer { int w = 0; int h = 0; unsigned char *buf; // Color buffer float *zbuf; // Depth buffer void clear(int w_, int h_) { if (w != w_ || h != h_) { w = w_; h = h_; ::free(buf); ::free(zbuf); buf = (unsigned char *)::malloc(w * h * 4); zbuf = (float *)::malloc(w * h * 4); } ::memset(buf, 0, w * h * 4); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { zbuf[w * y + x] = Inf; } } } void setPixel(int x, int y, const glm::vec3& c) { if (x < 0 || w <= x || y < 0 || h <= y) { return; } const size_t i = (w * y + x) * 4; buf[i + 0] = glm::clamp(int(c.r * 255), 0, 255); buf[i + 1] = glm::clamp(int(c.g * 255), 0, 255); buf[i + 2] = glm::clamp(int(c.b * 255), 0, 255); buf[i + 3] = 255; }; }; struct VaryingVert { glm::vec4 p; glm::vec3 n; }; using VertexShaderFunc = std::function<VaryingVert(const Scene::Vert& v)>; using FragmentShaderFunc = std::function<glm::vec3(const glm::vec3& n, const glm::vec3& p_ndc)>; void rasterize( const Scene& scene, Framebuffer& fb, bool wireframe, bool cullbackface, const VertexShaderFunc& vertexShader, const FragmentShaderFunc& fragmentShader ) { // Viewport transform const auto viewportTrans = [&](const glm::vec3& p) -> glm::vec2 { return glm::vec2( (p.x + 1.f) * .5f * fb.w, (p.y + 1.f) * .5f * fb.h ); }; // Rasterize a line segment const auto rasterLine = [&](const glm::vec2& p1, const glm::vec2& p2) { int x1 = int(p1.x); int y1 = int(p1.y); int x2 = int(p2.x); int y2 = int(p2.y); bool trans = false; if (abs(x2 - x1) < abs(y2 - y1)) { std::swap(x1, y1); std::swap(x2, y2); trans = true; } if (x1 > x2) { std::swap(x1, x2); std::swap(y1, y2); } const int dx = x2 - x1; const int dy = y2 - y1; const int delta = abs(dy) * 2; const int yd = dy > 0 ? 1 : -1; int error = 0; int y = y1; for (int x = x1; x <= x2; x++) { fb.setPixel(trans ? y : x, trans ? x : y, glm::vec3(1)); error += delta; if (error > dx) { y += yd; error -= dx * 2; } } }; // Rasterize a triangle const auto rasterTriangle = [&](const VaryingVert& v1, const VaryingVert& v2, const VaryingVert& v3) { // Clip space -> NDC -> Screen space const auto p1_ndc = glm::vec3(v1.p) / v1.p.w; const auto p2_ndc = glm::vec3(v2.p) / v2.p.w; const auto p3_ndc = glm::vec3(v3.p) / v3.p.w; const auto p1 = viewportTrans(p1_ndc); const auto p2 = viewportTrans(p2_ndc); const auto p3 = viewportTrans(p3_ndc); // Wireframe? if (wireframe) { rasterLine(p1, p2); rasterLine(p2, p3); rasterLine(p3, p1); return; } // Bounding box in screen coordinates glm::vec2 min( Inf); glm::vec2 max(-Inf); const auto merge = [&](const glm::vec2& p) { min = glm::min(min, p); max = glm::max(max, p); }; merge(p1); merge(p2); merge(p3); min = glm::max(min, glm::vec2(0)); max = glm::min(max, glm::vec2(fb.w-1, fb.h-1)); // Edge function (CCW) const auto edgeFunc = [](const glm::vec2& a, const glm::vec2& b, const glm::vec2& c) { const auto d1 = b - a; const auto d2 = c - a; return d1.x*d2.y - d1.y*d2.x; }; // Check inside/outside tests for each pixel const auto denom = edgeFunc(p1, p2, p3); const bool back = denom < 0; if (back && cullbackface) { return; } for (int y = int(min.y); y <= int(max.y); y++) { for (int x = int(min.x); x <= int(max.x); x++) { const auto p = glm::vec2(x, y) + 0.5f; auto b1 = edgeFunc(p2, p3, p); auto b2 = edgeFunc(p3, p1, p); auto b3 = edgeFunc(p1, p2, p); const bool inside = (b1>0 && b2>0 && b3>0) || (b1<0 && b2<0 && b3<0); if (!inside) { continue; } b1 /= denom; b2 /= denom; b3 /= denom; const auto p_ndc = b1 * p1_ndc + b2 * p2_ndc + b3 * p3_ndc; if (fb.zbuf[y*fb.w+x] < p_ndc.z) { continue; } fb.zbuf[y*fb.w + x] = p_ndc.z; const auto n = glm::normalize(b1/v1.p.w*v1.n + b2/v2.p.w*v2.n + b3/v3.p.w*v3.n); fb.setPixel(x, y, fragmentShader(back ? -n : n, p_ndc)); } } }; // Clip triangle const auto clipTriangle = [&]( const VaryingVert& v1, const VaryingVert& v2, const VaryingVert& v3, const std::function<void ( const VaryingVert& v1_clipped, const VaryingVert& v2_clipped, const VaryingVert& v3_clipped)>& processClippedTriangle ) { // Polygon as a vector of vertices in CCW order static std::vector<VaryingVert> poly; poly.clear(); poly.insert(poly.end(), { v1, v2, v3 }); // Perform clipping const glm::vec4 clip_plane_ns[] = { glm::vec4( 1, 0, 0, 1), // w=x glm::vec4(-1, 0, 0, 1), // w=-x glm::vec4( 0, 1, 0, 1), // w=y glm::vec4( 0,-1, 0, 1), // w=-y glm::vec4( 0, 0, 1, 1), // w=z glm::vec4( 0, 0,-1, 1), // w=-z }; for (const auto& clip_plane_n : clip_plane_ns) { static std::vector<VaryingVert> outpoly; outpoly.clear(); for (int i = 0; i < int(poly.size()); i++) { // Current edge const auto& v1 = poly[i]; const auto& v2 = poly[(i+1)%poly.size()]; // Signed distance const auto d1 = glm::dot(v1.p, clip_plane_n); const auto d2 = glm::dot(v2.p, clip_plane_n); // Calculate intersection between a segment and a clip plane const auto intersect = [&]() -> VaryingVert { const auto a = d1 / (d1 - d2); return { (1.f-a)*v1.p + a*v2.p, glm::normalize((1.f-a)*v1.n + a*v2.n) }; }; if (d1 > 0) { if (d2 > 0) { // Both inside outpoly.push_back(v2); } else { // p1: indide, p2: outside outpoly.push_back(intersect()); } } else if (d2 > 0) { // p1: outside, p2: inside outpoly.push_back(intersect()); outpoly.push_back(v2); } } poly = outpoly; } // Triangulate the polygon if (poly.empty()) { return; } const auto& vt1 = poly[0]; for (int i = 1; i < int(poly.size()) - 1; i++) { const auto& vt2 = poly[i]; const auto& vt3 = poly[(i+1)%poly.size()]; processClippedTriangle(vt1, vt2, vt3); } }; // For each triangles in the scene scene.foreachTriangles([&](const Scene::Tri& tri) { // Transform vertices const auto v1 = vertexShader(tri.v1); const auto v2 = vertexShader(tri.v2); const auto v3 = vertexShader(tri.v3); // Clip triangle and raster clipTriangle(v1, v2, v3, [&](const VaryingVert& v1_c, const VaryingVert& v2_c, const VaryingVert& v3_c) { rasterTriangle(v1_c, v2_c, v3_c); }); }); } int main(int argc, char* argv[]) { // Parse arguments if (argc != 2) { std::cerr << "Invalid number of argument(s)" << std::endl; return EXIT_FAILURE; } // Load scene Scene scene; if (!scene.load(argv[1])) { return EXIT_FAILURE; } // Execute application App app; if (!app.setup("raster04_rasterization")) { return EXIT_FAILURE; } app.run([&](int w, int h, const glm::mat4& viewM) -> App::Buf { // Raster mode enum class RasterMode { Shaded, Normal, Wireframe, }; #if 1 const static auto mode = RasterMode::Normal; const static bool animate = true; const static bool cullbackface = true; const static float fov = 30.f; const static float znear = 0.1f; const static float zfar = 10.f; const static auto view = glm::lookAt( glm::vec3(0, 0.8, 1.5), // eye glm::vec3(0, 0, 0), // center glm::vec3(0, 1, 0)); // up auto *pview = const_cast<glm::mat4 *>(&viewM); *pview = view; #else const auto mode = [&]() { static int mode = 0; ImGui::RadioButton("Shaded", &mode, 0); ImGui::SameLine(); ImGui::RadioButton("Normal", &mode, 1); ImGui::SameLine(); ImGui::RadioButton("Wireframe", &mode, 2); ImGui::Separator(); return RasterMode(mode); }(); // Animation static bool animate = true; ImGui::Checkbox("Enable animation", &animate); ImGui::Separator(); // Backface culling static bool cullbackface = true; ImGui::Checkbox("Enable backface culling", &cullbackface); ImGui::Separator(); // Camera parameters static float fov = 30.f; static float znear = 0.1f; static float zfar = 10.f; ImGui::DragFloat("fov", &fov, 0.1f, 0.01f, 180.f); ImGui::DragFloat("near", &znear, 0.01f, 0.01f, 10.f); ImGui::DragFloat("far", &zfar, 0.01f, 1.f, 1000.f); ImGui::Separator(); #endif // Framebuffer static Framebuffer fb; fb.clear(w, h); // Transformation matrix const auto modelM = animate ? glm::rotate(float(ImGui::GetTime()), glm::vec3(0.f,1.f,0.f)) : glm::mat4(1.f); const auto projM = glm::perspective(glm::radians(fov), float(fb.w) / fb.h, znear, zfar); const auto transMVP = projM * viewM * modelM; const auto transN = glm::mat3(glm::transpose(glm::inverse(modelM))); // Direction of light const auto lightdir = glm::normalize(glm::vec3(0.5, 0.8, 1)); // Rasterize rasterize(scene, fb, mode == RasterMode::Wireframe, cullbackface, // Vertex shader [&](const Scene::Vert& v) -> VaryingVert { return { transMVP * glm::vec4(v.p, 1), transN * v.n }; }, // Fragment shader [&](const glm::vec3& n, const glm::vec3& p_ndc) -> glm::vec3 { if (mode == RasterMode::Normal) { return glm::abs(n); } else if (mode == RasterMode::Shaded) { return glm::vec3(0.2f + 0.8f*glm::max(0.f, glm::dot(n, lightdir))); } UNREACHABLE(); return {}; }); return { fb.w, fb.h, fb.buf }; }); app.shutdown(); return EXIT_SUCCESS; }
32.972145
116
0.464814
[ "vector", "transform" ]
70f39c0ef815c1639c48ae6f946dff0dbfc78cc4
1,108
cpp
C++
src/Buffer.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
71
2016-11-17T19:22:21.000Z
2022-01-10T10:03:58.000Z
src/Buffer.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
30
2017-02-02T21:03:33.000Z
2018-06-27T20:49:31.000Z
src/Buffer.cpp
akifoezkan/Halide-HLS
1eee3f38f32722f3e725c29a5b7a084275062a7f
[ "MIT" ]
22
2017-04-16T11:44:34.000Z
2022-03-26T13:27:10.000Z
#include "Buffer.h" #include "Var.h" #include "IREquality.h" #include "IROperator.h" namespace Halide { namespace Internal { template<> EXPORT RefCount &ref_count<BufferContents>(const BufferContents *c) { return c->ref_count; } template<> EXPORT void destroy<BufferContents>(const BufferContents *c) { delete c; } Expr buffer_accessor(const Buffer<> &buf, const std::vector<Expr> &args) { std::vector<Expr> int_args; for (Expr e : args) { user_assert(Int(32).can_represent(e.type())) << "Args to a call to an Image must be representable as 32-bit integers.\n"; if (equal(e, _)) { // Expand the _ into the appropriate number of implicit vars. int missing_dimensions = buf.dimensions() - (int)args.size() + 1; for (int i = 0; i < missing_dimensions; i++) { int_args.push_back(Var::implicit(i)); } } else if (e.type() == Int(32)) { int_args.push_back(e); } else { int_args.push_back(cast<int>(e)); } } return Call::make(buf, int_args); } } }
27.02439
88
0.600181
[ "vector" ]
70ff680132b42fa677f4072980d91af6beb123c1
7,185
cpp
C++
PolhemusG4.ManagedLib/NativeTrackingDevice.cpp
chr33z/PolhemusG4.ManagedLib
5257b61f553b5f3e86cd468aff8ae5436fbc6ddf
[ "MIT" ]
2
2019-03-24T06:58:28.000Z
2019-05-27T09:53:47.000Z
PolhemusG4.ManagedLib/NativeTrackingDevice.cpp
chr33z/PolhemusG4.ManagedLib
5257b61f553b5f3e86cd468aff8ae5436fbc6ddf
[ "MIT" ]
null
null
null
PolhemusG4.ManagedLib/NativeTrackingDevice.cpp
chr33z/PolhemusG4.ManagedLib
5257b61f553b5f3e86cd468aff8ae5436fbc6ddf
[ "MIT" ]
null
null
null
#include "NativeTrackingDevice.h" NativeTrackingDevice::NativeTrackingDevice() { } NativeTrackingDevice::~NativeTrackingDevice() { } bool NativeTrackingDevice::Initialize(string calibrationFilePath) { tracker.Trace(TRUE, 9); tracker.SetPnoBuffer(g_pMotionBuf, BUFFER_SIZE); memset(&m_nHubIDs[0], 0, sizeof(INT)*G4_MAX_HUB_COUNT); memset(&m_stamap[0], 0, sizeof(UINT64)*G4_STAMAP_BLOCK_COUNT); const char* file = calibrationFilePath.c_str(); _tcsncpy_s(sourceCalibrationFilePath, _countof(sourceCalibrationFilePath), file, _tcslen(file)); return true; } bool NativeTrackingDevice::Connect() { if (!tracker.CnxReady()) { if (tracker.ConnectG4(sourceCalibrationFilePath)) { isConnected = true; return true; } else { isConnected = false; return false; } } else { // already connected isConnected = true; return true; } } bool NativeTrackingDevice::Disconnect() { if (tracker.CnxReady()) { if (tracker.Disconnect()) { isConnected = false; return true; } else { isConnected = false; return false; } } else { // not connected isConnected = false; return true; } } string NativeTrackingDevice::GetTrackerInformation() { if (tracker.CnxReady()) { LPCTSTR szWho; tracker.WhoAmIG4Sys(systemID, maxHubCount, szWho); return string(szWho); } else { return ""; } } bool NativeTrackingDevice::SetPNOPositionUnits(NativePositionUnits unit) { if (tracker.CnxReady()) { return tracker.SetPNOPosUnits((ePDIposUnits)unit); } return false; } NativePositionUnits NativeTrackingDevice::GetPNOPositionUnits() { if (tracker.CnxReady()) { ePDIposUnits units; if (tracker.GetPNOPosUnits(units)) { return (NativePositionUnits)units; } } return NativePositionUnits::MAX; } bool NativeTrackingDevice::ResetPNOPositionUnits() { if (tracker.CnxReady()) { return tracker.ResetPNOPosUnits(); } else { return false; } } bool NativeTrackingDevice::SetPNOOrientationUnits(NativeOrientationUnits units) { if (tracker.CnxReady()) { return tracker.SetPNOOriUnits((ePDIoriUnits)units); } return false; } NativeOrientationUnits NativeTrackingDevice::GetPNOOrientationUnits() { if (tracker.CnxReady()) { ePDIoriUnits units; if (tracker.GetPNOOriUnits(units)) { return (NativeOrientationUnits)units; } } } bool NativeTrackingDevice::ResetPNOOrientationUnits() { if (tracker.CnxReady()) { return tracker.ResetPNOOriUnits(); } else { return false; } } string NativeTrackingDevice::GetLastResultString() { return string(tracker.GetLastResultStr()); } string NativeTrackingDevice::GetSourceCalibrationFilePath() { return sourceCalibrationFilePath; } int NativeTrackingDevice::GetActiveHubs(int* hubIDs) { int hubCount; tracker.GetActiveHubs(hubCount, hubIDs); return hubCount; } int NativeTrackingDevice::GetActiveSensorCount() { int count; tracker.GetActiveSensorCount(count); return count; } UINT32 NativeTrackingDevice::GetHubSensorMap(int hub) { DWORD map; tracker.GetHubSensorMap(hub, map); return map; } NativeFrameOfReference NativeTrackingDevice::GetFrameOfReference() { NativeFrameOfReference frameOfReference; if (tracker.CnxReady()) { PDI7vec vec7; tracker.GetFrameOfRef(vec7); frameOfReference.x = vec7[0]; frameOfReference.y = vec7[1]; frameOfReference.z = vec7[2]; frameOfReference.r1 = vec7[3]; frameOfReference.r2 = vec7[4]; frameOfReference.r3 = vec7[5]; frameOfReference.r4 = vec7[6]; frameOfReference.valid = true; } return frameOfReference; } bool NativeTrackingDevice::SetFrameOfReference(NativeFrameOfReference frameOfReference) { if (tracker.CnxReady()) { PDI7vec v; v[0] = frameOfReference.x; v[1] = frameOfReference.y; v[2] = frameOfReference.z; v[3] = frameOfReference.r1; v[4] = frameOfReference.r2; v[5] = frameOfReference.r3; v[6] = frameOfReference.r4; return tracker.SetFrameOfRef(v); } return false; } bool NativeTrackingDevice::ResetFrameOfReference() { if (tracker.CnxReady()) { return tracker.ResetFrameOfRef(); } return false; } void NativeTrackingDevice::SetCommandPositionUnits(NativePositionUnits units) { if (tracker.CnxReady()) { tracker.SetCmdPosUnits((ePDIposUnits)units); } } void NativeTrackingDevice::SetCommandOrientationUnits(NativeOrientationUnits units) { if (tracker.CnxReady()) { tracker.SetCmdOriUnits((ePDIoriUnits)units); } } bool NativeTrackingDevice::SetTipOffset(int hub, int sensor, float x, float y, float z) { if (tracker.CnxReady()) { PDIpos position; position[0] = x; position[1] = y; position[2] = z; return tracker.SetSTipOffset(hub, sensor, position); } return false; } NativePDIvec3 NativeTrackingDevice::GetTipOffset(int hub, int sensor) { PDI3vec v; tracker.GetSTipOffset(hub, sensor, v); NativePDIvec3 tipOffset; tipOffset.x = v[0]; tipOffset.y = v[1]; tipOffset.z = v[2]; return tipOffset; } bool NativeTrackingDevice::ResetTipOffset(int hub, int sensor) { return tracker.ResetSTipOffset(hub, sensor, false); } std::vector<NativePNOFrame*>* NativeTrackingDevice::ReadSinglePNOFrame() { PBYTE pBuf; DWORD dwSize; if (tracker.CnxReady()) { if (tracker.ReadSinglePnoBufG4(pBuf, dwSize)) { return ParseG4NativeFrame(pBuf, dwSize); } } // in case of an error return nothing return new vector<NativePNOFrame*>();; } // Private Methods bool NativeTrackingDevice::SetIncrement(int hubID, int sensorID, float positionIncrement, float orientationIncrement, bool readSensorsAsBitmap) { if (tracker.CnxReady()) { return tracker.SetSIncrement(hubID, sensorID, positionIncrement, orientationIncrement, readSensorsAsBitmap); } return false; } bool NativeTrackingDevice::GetIncrement(int hubID, int sensorID, float & positionIncrement, float & orientationIncrement) { if (tracker.CnxReady()) { return tracker.GetSIncrement(hubID, sensorID, positionIncrement, orientationIncrement); } return false; } vector<NativePNOFrame*>* NativeTrackingDevice::ParseG4NativeFrame(PBYTE buffer, DWORD size) { std::vector<NativePNOFrame*>* frames = new vector<NativePNOFrame*>(); if ((!buffer) || (!size)) { } else { DWORD i = 0; LPG4_HUBDATA pHubFrame; while (i < size) { pHubFrame = (LPG4_HUBDATA)(&buffer[i]); i += sizeof(G4_HUBDATA); UINT nHubID = pHubFrame->nHubID; UINT nFrameNum = pHubFrame->nFrameCount; UINT nSensorMap = pHubFrame->dwSensorMap; UINT nDigIO = pHubFrame->dwDigIO; UINT nSensMask = 1; for (int j = 0; j < G4_MAX_SENSORS_PER_HUB; j++) { if (((nSensMask << j) & nSensorMap) != 0) { NativePNOFrame* frame = new NativePNOFrame; G4_SENSORDATA * pSD = &(pHubFrame->sd[j]); frame->hubID = pHubFrame->nHubID; frame->sensorID = pSD->nSnsID; frame->frameNumber = pHubFrame->nFrameCount; frame->DigIO = pHubFrame->dwDigIO; frame->x = pSD->pos[0]; frame->y = pSD->pos[1]; frame->z = pSD->pos[2]; frame->r1 = pSD->ori[0]; frame->r2 = pSD->ori[1]; frame->r3 = pSD->ori[2]; if (orientationUnits == NativeOrientationUnits::QUATERNION) { frame->r4 = pSD->ori[3]; } frames->push_back(frame); } } } // end while dwsize } return frames; }
20.29661
143
0.718441
[ "vector" ]
70ffb1542ed123260153fba9d23d966e6b122443
6,606
cpp
C++
PA1/src/RayTracer.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
PA1/src/RayTracer.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
PA1/src/RayTracer.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
#include "RayTracer.h" RayTracer::RayTracer(Scene const & scene, int sWidth, int sHeight) : ScreenWidth(sWidth), ScreenHeight(sHeight), mScene(scene), fov(30.0f), AspectRatio((float)(ScreenWidth/ScreenHeight)), MainCamera(), SampleRate(1), MaxTraceDepth(3) { angle = std::tan(M_PI * 0.5f * fov / 180.0f); MainCamera.SetScreenSize(ScreenWidth, ScreenHeight); SamplingType = PostProcess::UniformSampling; } RayTracer::~RayTracer() { } void RayTracer::Resize(int w, int h) { LOG(INFO) << "Resize called with width: " << w << ", height: " << h; ScreenWidth = w; ScreenHeight = h; MainCamera.SetScreenSize(w, h); } void RayTracer::BWRender(Image& image) const { LOG(INFO) << "No color render"; // Buffer to hold color values, reserve size of the window. std::vector<glm::vec3> buffer; HitData data; // Most expensive thing ive ever seen. for (int y = 0; y < ScreenHeight; ++y) { for (int x = 0; x < ScreenWidth; ++x) { Ray ray = MainCamera.GetRay(x, y); glm::vec3 result = BWTrace(ray); buffer.push_back(result); } } image.SetBuffer(buffer); } void RayTracer::Render(Image& image) const { LOG(INFO) << "Starting rendering to image"; // Buffer to hold color values, reserve size of the window. std::vector<glm::vec3> buffer; // Most expensive thing ive ever seen. for (int y = 0; y < ScreenHeight; ++y) { for (int x = 0; x < ScreenWidth; ++x) { Ray ray = MainCamera.GetRay(x, y); glm::vec3 result = Sampler(x, y); buffer.push_back(result); } } image.SetBuffer(buffer); } std::vector<Pixel> RayTracer::Render() const { LOG(INFO) << "Ray tracer render function for GL"; // generate buffer for window size std::vector<Pixel> buffer; for (int y = 0; y < ScreenHeight; ++y) { for (int x = 0; x < ScreenWidth; ++x ) { glm::vec3 result = Sampler(x, y); Pixel p = Image::ColorToPixel(result); buffer.push_back(p); } } return buffer; } glm::vec3 RayTracer::BWTrace(const Ray& ray) const { HitData data; bool result = mScene.IntersectSurfaces(ray, 1000.0f, data); if (data.HitSurface == nullptr) return glm::vec3(0.0f); return glm::vec3(1.0f); } glm::vec3 RayTracer::Trace(const Ray& ray, int depth) const { if (depth > MaxTraceDepth) return glm::vec3(0.0f); //If max depth has been reached return 0 HitData data; bool result = mScene.IntersectSurfaces(ray, 10000.0f, data); if (data.HitSurface == nullptr) return glm::vec3(0.0f); // Calculate diffuse and specular here glm::vec3 out = Shade(ray, data); // If the surface material has a reflection value float reflectionCoef = data.HitSurface->Mat().Reflection(); if (reflectionCoef > 0.0f) { // Calculate the reflection ray glm::vec3 incident = -ray.Direction; glm::vec3 Direction = incident - data.Normal * (2.0f * glm::dot( data.Normal, incident )); Ray reflectionRay(data.Point, glm::normalize(Direction)); out += Trace(reflectionRay, depth + 1) * reflectionCoef; } return out; } glm::vec3 RayTracer::Shade(const Ray& ray, const HitData& data) const { // Initial color is ambient of the hit material glm::vec3 result = data.HitSurface->Mat().Ambient(); for (Light* light : mScene.Lights) { // Trace for shadows here glm::vec3 shadowDir = light->GetPosition() - data.Point; float len = glm::length(shadowDir); shadowDir = glm::normalize(shadowDir); Ray shadowRay(data.Point + shadowDir, shadowDir); // Check for shadows if ( !mScene.IntersectSurfaces(shadowRay, len, data.HitSurface)) { result += CalculateDiffuse(data, light) + CalculateSpecular(ray, data, light); } } return result; } glm::vec3 RayTracer::CalculateDiffuse(const HitData& data, Light* light) const { // Diffuse light calculations // Find the direction vector from hit point to the light, don't forget to normalize // Calculate dot product of hit normal and the light vector // Multiply the diffuse and the clamped cos of the angle glm::vec3 lightdir = glm::normalize(light->GetPosition() - data.Point); float ndotl = glm::dot(data.Normal, lightdir); glm::vec3 Ldiff = data.HitSurface->Mat().Diffuse() * light->Intensity * std::max(0.0f, ndotl); return Ldiff; } glm::vec3 RayTracer::CalculateSpecular(const Ray& ray, const HitData& data, Light* light) const { // Specular Light calculations // Subtract the ray direction instead of add to reverse direction glm::vec3 lightdir = light->GetPosition() - data.Point; glm::vec3 half = glm::normalize(lightdir - ray.Direction); float ndoth = glm::dot(data.Normal, half); // I might be cheating here using auto, but not sure if i can get a reference // rather than the entire object. auto mat = data.HitSurface->Mat(); glm::vec3 Lspec = mat.Specular() * light->Intensity * std::pow(std::max(0.0f, ndoth), mat.SpecularPower()); return Lspec; } void RayTracer::SetSampleRate(int s) { SampleRate = s; } glm::vec3 RayTracer::Sampler(int x, int y) const { switch(SamplingType) { case UniformSampling: return UniformSampler(x, y); case RandomSampling: return RandomSampler(x, y); default: LOG(WARNING) << "Sampler not set, default 0 vector returned"; return glm::vec3(0.0f); } } glm::vec3 RayTracer::UniformSampler(int x, int y) const { glm::vec3 result; float coef = 1.0f / SampleRate; for (float offsetx = 0.0f; offsetx < 1.0f; offsetx += coef) { for (float offsety = 0.0f; offsety < 1.0f; offsety += coef) { Ray ray = MainCamera.GetRay(x, y, offsetx, offsety); result += Trace(ray, 0); } } return result * coef * coef; } glm::vec3 RayTracer::RandomSampler(int x, int y) const { std::default_random_engine generator; std::uniform_real_distribution<float> distribution(0.0f, 1.0f); glm::vec3 result; int s2 = SampleRate * SampleRate; for (int i = 0; i < s2; ++i) { float offsetx = distribution(generator); float offsety = distribution(generator); Ray ray = MainCamera.GetRay(x, y, offsetx, offsety); result += Trace(ray, 0); } result = (result / (float) s2); return result; }
27.991525
111
0.619285
[ "render", "object", "vector" ]
cb01e36f4bff571ac711029254c80e598c684951
918
cpp
C++
WinProj/CItchy.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
WinProj/CItchy.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
WinProj/CItchy.cpp
godekd3133/MyAquarium
1162522b11f6ff222b138dff9e9dd0fe9e36353f
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "CItchy.h" CItchy::CItchy() { } CItchy::~CItchy() { } void CItchy::Init() { m_pAnimation = new CAnimation(IMAGE["ITCHY"], 0.1f, 10, 4, 1); m_pReverse = new CAnimation(IMAGE["ITCHY_REVERSE"], 0.1f, 10, 4, 1); m_vPos = { 100,200 }; m_fMovespeed = 200.f; } void CItchy::Update() { m_pAnimation->Update(); m_pReverse->SetFrame(m_pAnimation->GetFrame()); m_vPos.x += m_fMovespeed * SYSTEM.GetDeltaTime() * m_iDir; if (m_vPos.x + m_pAnimation->GetFrameWidth() < 0) { m_vPos.y = rand() % (WINSIZEY - m_pAnimation->GetFrameHeight() + 30); m_iDir = 1; } else if (m_vPos.x > WINSIZEX) { m_vPos.y = rand() % (WINSIZEY - m_pAnimation->GetFrameHeight() + 30); m_iDir = -1; } } void CItchy::Render() { if (m_iDir == -1) m_pAnimation->Render(m_vPos); else m_pReverse->Render(m_vPos); } void CItchy::Release() { SAFE_DELETE(m_pAnimation); SAFE_DELETE(m_pReverse); }
17
71
0.652505
[ "render" ]
cb0ac94fe9636f3881e053f9f79eb74e91cc70c7
21,581
cxx
C++
Plugins/StreamingView/VTK/vtkImageNetCDFPOPReader.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/StreamingView/VTK/vtkImageNetCDFPOPReader.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/StreamingView/VTK/vtkImageNetCDFPOPReader.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkImageNetCDFPOPReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageNetCDFPOPReader.h" #include "vtkCallbackCommand.h" #include "vtkDataArraySelection.h" #include "vtkExtentTranslator.h" #include "vtkFloatArray.h" #include "vtkGridSampler1.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkMetaInfoDatabase.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtk_netcdf.h" #include <string> #include <vector> #include "vtkExtentTranslator.h" #define DEBUGPRINT(arg) ; #define DEBUGPRINT_RESOLUTION(arg) ; #define DEBUGPRINT_METAINFORMATION(arg) ; vtkStandardNewMacro(vtkImageNetCDFPOPReader); //============================================================================ #define CALL_NETCDF(call) \ { \ int errorcode = call; \ if (errorcode != NC_NOERR) \ { \ vtkErrorMacro(<< "netCDF Error: " << nc_strerror(errorcode)); \ return 0; \ } \ } //============================================================================ class vtkImageNetCDFPOPReader::Internal { public: vtkSmartPointer<vtkDataArraySelection> VariableArraySelection; // a mapping from the list of all variables to the list of available // point-based variables std::vector<int> VariableMap; Internal() { this->VariableArraySelection = vtkSmartPointer<vtkDataArraySelection>::New(); this->GridSampler = vtkGridSampler1::New(); this->RangeKeeper = vtkMetaInfoDatabase::New(); this->Resolution = 1.0; this->SI = 1; this->SJ = 1; this->SK = 1; this->WholeExtent[0] = this->WholeExtent[2] = this->WholeExtent[4] = 1; this->WholeExtent[1] = this->WholeExtent[3] = this->WholeExtent[5] = -1; } ~Internal() { this->GridSampler->Delete(); this->RangeKeeper->Delete(); } vtkGridSampler1 *GridSampler; vtkMetaInfoDatabase *RangeKeeper; double Resolution; int SI, SJ, SK; int WholeExtent[6]; }; //---------------------------------------------------------------------------- //set default values vtkImageNetCDFPOPReader::vtkImageNetCDFPOPReader() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->FileName = NULL; this->NCDFFD = 0; this->SelectionObserver = vtkCallbackCommand::New(); this->SelectionObserver->SetCallback (&vtkImageNetCDFPOPReader::SelectionModifiedCallback); this->SelectionObserver->SetClientData(this); this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Spacing[0] = this->Spacing[1] = this->Spacing[2] = 1.0; this->Internals = new vtkImageNetCDFPOPReader::Internal; this->Internals->VariableArraySelection->AddObserver( vtkCommand::ModifiedEvent, this->SelectionObserver); } //---------------------------------------------------------------------------- //delete filename and netcdf file descriptor vtkImageNetCDFPOPReader::~vtkImageNetCDFPOPReader() { this->SetFileName(0); nc_close(this->NCDFFD); if(this->SelectionObserver) { this->SelectionObserver->Delete(); this->SelectionObserver = NULL; } if(this->Internals) { delete this->Internals; this->Internals = NULL; } } //---------------------------------------------------------------------------- void vtkImageNetCDFPOPReader::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(NULL)") << endl; os << indent << "NCDFFD: " << this->NCDFFD << endl; this->Internals->VariableArraySelection->PrintSelf (os, indent.GetNextIndent()); } //---------------------------------------------------------------------------- // RequestInformation supplies global meta information // This should return the reality of what the reader is going to supply. // This retrieve the extents for the image grid // NC_MAX_VAR_DIMS comes from the nc library int vtkImageNetCDFPOPReader::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if(this->FileName == NULL) { vtkErrorMacro("FileName not set."); return 0; } int retval; if (!this->NCDFFD) { retval = nc_open(this->FileName, NC_NOWRITE, &this->NCDFFD); if (retval != NC_NOERR) { vtkErrorMacro(<< "Can't read file " << nc_strerror(retval)); return 0; } } retval = this->Superclass::RequestInformation(request, inputVector, outputVector); if (retval != VTK_OK) { return retval; } vtkInformation* outInfo = outputVector->GetInformationObject(0); outInfo->Set(vtkDataObject::ORIGIN(),this->Origin,3); outInfo->Set(vtkDataObject::SPACING(), this->Spacing, 3); // get number of variables from file int numberOfVariables; nc_inq_nvars(this->NCDFFD, &numberOfVariables); int dimidsp[NC_MAX_VAR_DIMS]; int dataDimension; size_t dimensions[4]; //dimension value this->Internals->VariableMap.resize(numberOfVariables); char variableName[NC_MAX_NAME+1]; int actualVariableCounter = 0; // For every variable in the file for(int i=0;i<numberOfVariables;i++) { this->Internals->VariableMap[i] = -1; //get number of dimensions CALL_NETCDF(nc_inq_varndims(this->NCDFFD, i, &dataDimension)); //Variable Dimension ID's containing x,y,z coords for the //grid spacing CALL_NETCDF(nc_inq_vardimid(this->NCDFFD, i, dimidsp)); if(dataDimension == 3) { this->Internals->VariableMap[i] = actualVariableCounter++; //get variable name CALL_NETCDF(nc_inq_varname(this->NCDFFD, i, variableName)); this->Internals->VariableArraySelection->AddArray(variableName); for(int m=0;m<dataDimension;m++) { CALL_NETCDF(nc_inq_dimlen(this->NCDFFD, dimidsp[m], dimensions+m)); //acquire variable dimensions } this->Internals->WholeExtent[0] = this->Internals->WholeExtent[2] = this->Internals->WholeExtent[4] =0; //set extent this->Internals->WholeExtent[1] = static_cast<int>((dimensions[2] -1)); this->Internals->WholeExtent[3] = static_cast<int>((dimensions[1] -1)); this->Internals->WholeExtent[5] = static_cast<int>((dimensions[0] -1)); } } int sWholeExtent[6]; sWholeExtent[0] = this->Internals->WholeExtent[0]; sWholeExtent[1] = this->Internals->WholeExtent[1]; sWholeExtent[2] = this->Internals->WholeExtent[2]; sWholeExtent[3] = this->Internals->WholeExtent[3]; sWholeExtent[4] = this->Internals->WholeExtent[4]; sWholeExtent[5] = this->Internals->WholeExtent[5]; outInfo->Set (vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), sWholeExtent, 6); double sSpacing[3]; sSpacing[0] = this->Spacing[0]; sSpacing[1] = this->Spacing[1]; sSpacing[2] = this->Spacing[2]; this->Internals->Resolution = 1.0; if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_RESOLUTION())) { double rRes = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_RESOLUTION()); int strides[3]; double aRes; int pathLen; int *splitPath; this->Internals->GridSampler->SetWholeExtent(sWholeExtent); vtkIntArray *ia = this->Internals->GridSampler->GetSplitPath(); pathLen = ia->GetNumberOfTuples(); splitPath = ia->GetPointer(0); DEBUGPRINT_RESOLUTION ( cerr << "pathlen = " << pathLen << endl; cerr << "SP = " << splitPath << endl; for (int i = 0; i <40 && i < pathLen; i++) { cerr << splitPath[i] << " "; } cerr << endl; ); //save split path in translator vtkImageData *outData = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkExtentTranslator *et = vtkExtentTranslator::SafeDownCast( outInfo->Get(vtkStreamingDemandDrivenPipeline::EXTENT_TRANSLATOR())); et->SetSplitPath(pathLen, splitPath); this->Internals->GridSampler->SetSpacing(sSpacing); this->Internals->GridSampler->ComputeAtResolution(rRes); this->Internals->GridSampler->GetStridedExtent(sWholeExtent); this->Internals->GridSampler->GetStridedSpacing(sSpacing); this->Internals->GridSampler->GetStrides(strides); aRes = this->Internals->GridSampler->GetStridedResolution(); DEBUGPRINT_RESOLUTION ( cerr << "PST GRID\t"; {for (int i = 0; i < 3; i++) cerr << sSpacing[i] << " ";} {for (int i = 0; i < 6; i++) cerr << sWholeExtent[i] << " ";} cerr << endl; ); outInfo->Set (vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), sWholeExtent, 6); outInfo->Set(vtkDataObject::SPACING(), sSpacing, 3); this->Internals->Resolution = aRes; this->Internals->SI = strides[0]; this->Internals->SJ = strides[1]; this->Internals->SK = strides[2]; DEBUGPRINT_RESOLUTION ( cerr << "RI SET STRIDE "; {for (int i = 0; i < 3; i++) cerr << strides[i] << " ";} cerr << endl; ); } outInfo->Get(vtkDataObject::ORIGIN(), this->Origin); double bounds[6]; bounds[0] = this->Origin[0] + sSpacing[0] * sWholeExtent[0]; bounds[1] = this->Origin[0] + sSpacing[0] * sWholeExtent[1]; bounds[2] = this->Origin[1] + sSpacing[1] * sWholeExtent[2]; bounds[3] = this->Origin[1] + sSpacing[1] * sWholeExtent[3]; bounds[4] = this->Origin[2] + sSpacing[2] * sWholeExtent[4]; bounds[5] = this->Origin[2] + sSpacing[2] * sWholeExtent[5]; DEBUGPRINT_RESOLUTION ( cerr << "RI SET BOUNDS "; {for (int i = 0; i < 6; i++) cerr << bounds[i] << " ";} cerr << endl; ); outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_BOUNDING_BOX(), bounds, 6); return 1; } //---------------------------------------------------------------------------- // Setting extents of the rectilinear grid int vtkImageNetCDFPOPReader::RequestData(vtkInformation* request, vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector ) { this->UpdateProgress(0); // the default implimentation is to do what the old pipeline did find what // output is requesting the data, and pass that into ExecuteData // which output port did the request come from int outputPort = request->Get(vtkDemandDrivenPipeline::FROM_OUTPUT_PORT()); // if output port is negative then that means this filter is calling the // update directly, in that case just assume port 0 if (outputPort == -1) { outputPort = 0; } // get the data object vtkInformation *outInfo = outputVector->GetInformationObject(outputPort); vtkDataObject* output = outInfo->Get(vtkDataObject::DATA_OBJECT()); int subext[6]; //vtkInformation * outInfo = output->GetInformationObject(0); outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),subext); vtkImageData *imageData = vtkImageData::SafeDownCast(output); imageData->SetExtent(subext); //setup extents for netcdf library to read the netcdf data file size_t start[]= {subext[4]*this->Internals->SK, subext[2]*this->Internals->SJ, subext[0]*this->Internals->SI}; size_t count[]= {subext[5]-subext[4]+1, subext[3]-subext[2]+1, subext[1]-subext[0]+1}; ptrdiff_t rStride[3] = { (ptrdiff_t)this->Internals->SK, (ptrdiff_t)this->Internals->SJ, (ptrdiff_t)this->Internals->SI }; double sSpacing[3]; outInfo->Get(vtkDataObject::SPACING(), sSpacing); double range[2]; int P = outInfo->Get (vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); int NP = outInfo->Get (vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); //initialize memory (raw data space, x y z axis space) and rectilinear grid for(size_t i=0;i<this->Internals->VariableMap.size();i++) { if(this->Internals->VariableMap[i] != -1 && this->Internals->VariableArraySelection->GetArraySetting( this->Internals->VariableMap[i]) != 0) { // varidp is probably i in which case nc_inq_varid isn't needed int varidp; nc_inq_varid(this->NCDFFD, this->Internals->VariableArraySelection->GetArrayName( this->Internals->VariableMap[i]), &varidp); imageData->SetSpacing(sSpacing[0], sSpacing[1], sSpacing[2]); //create vtkFloatArray and get the scalars into it vtkFloatArray *scalars = vtkFloatArray::New(); vtkIdType numberOfTuples = (count[0])*(count[1])*(count[2]); scalars->SetNumberOfComponents(1); scalars->SetNumberOfTuples(numberOfTuples); float* data = new float[numberOfTuples]; nc_get_vars_float(this->NCDFFD, varidp, start, count, rStride, data); scalars->SetArray(data, numberOfTuples, 0, 1); //set list of variables to display data on rectilinear grid const char *name = this->Internals->VariableArraySelection->GetArrayName (this->Internals->VariableMap[i]); scalars->SetName(name); imageData->GetPointData()->AddArray(scalars); scalars->GetRange(range); this->Internals->RangeKeeper->Insert(P, NP, subext, this->Internals->Resolution, 0, name, 0, range); DEBUGPRINT_METAINFORMATION ( cerr << "SIP(" << this << ") Calculated range " << range[0] << ".." << range[1] << " for " << name << " " << P << "/" << NP << "&" << this->Internals->Resolution << endl; ); scalars->Delete(); } this->UpdateProgress((i+1.0)/this->Internals->VariableMap.size()); } return 1; } //---------------------------------------------------------------------------- //following 5 functions are used for paraview user interface void vtkImageNetCDFPOPReader::SelectionModifiedCallback (vtkObject*, unsigned long, void* clientdata, void*) { static_cast<vtkImageNetCDFPOPReader*>(clientdata)->Modified(); } //----------------------------------------------------------------------------- int vtkImageNetCDFPOPReader::GetNumberOfVariableArrays() { return this->Internals->VariableArraySelection->GetNumberOfArrays(); } //----------------------------------------------------------------------------- const char* vtkImageNetCDFPOPReader::GetVariableArrayName(int index) { if(index < 0 || index >= this->GetNumberOfVariableArrays()) { return NULL; } return this->Internals->VariableArraySelection->GetArrayName(index); } //----------------------------------------------------------------------------- int vtkImageNetCDFPOPReader::GetVariableArrayStatus(const char* name) { return this->Internals->VariableArraySelection->ArrayIsEnabled(name); } //----------------------------------------------------------------------------- void vtkImageNetCDFPOPReader::SetVariableArrayStatus(const char* name, int status) { vtkDebugMacro("Set cell array \"" << name << "\" status to: " << status); if(this->Internals->VariableArraySelection->ArrayExists(name) == 0) { vtkErrorMacro(<< name << " is not available in the file."); return; } int enabled = this->Internals->VariableArraySelection->ArrayIsEnabled(name); if(status != 0 && enabled == 0) { this->Internals->VariableArraySelection->EnableArray(name); this->Modified(); } else if(status == 0 && enabled != 0) { this->Internals->VariableArraySelection->DisableArray(name); this->Modified(); } } //---------------------------------------------------------------------------- int vtkImageNetCDFPOPReader::ProcessRequest(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { DEBUGPRINT ( vtkInformation *outInfo = outputVector->GetInformationObject(0); int P = outInfo->Get (vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); int NP = outInfo->Get (vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); double res = outInfo->Get (vtkStreamingDemandDrivenPipeline::UPDATE_RESOLUTION()); cerr << "SIP(" << this << ") PR " << P << "/" << NP << "@" << res << "->" << this->Internals->SI << " " << this->Internals->SJ << " " << this->Internals->SK << endl; ); if(request->Has (vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT_INFORMATION())) { DEBUGPRINT_METAINFORMATION ( cerr << "SIP(" << this << ") RUEI ==============================="<<endl; ); //create meta information for this piece double *origin; double *spacing; int *ext; vtkInformation* outInfo = outputVector->GetInformationObject(0); origin = outInfo->Get(vtkDataObject::ORIGIN()); spacing = outInfo->Get(vtkDataObject::SPACING()); ext = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()); int P = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); int NP = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); double bounds[6]; bounds[0] = origin[0] + spacing[0] * ext[0]; bounds[1] = origin[0] + spacing[0] * ext[1]; bounds[2] = origin[1] + spacing[1] * ext[2]; bounds[3] = origin[1] + spacing[1] * ext[3]; bounds[4] = origin[2] + spacing[2] * ext[4]; bounds[5] = origin[2] + spacing[2] * ext[5]; outInfo->Set (vtkStreamingDemandDrivenPipeline::PIECE_BOUNDING_BOX(), bounds, 6); int ic = (ext[1]-ext[0]); if (ic < 1) { ic = 1; } int jc = (ext[3]-ext[2]); if (jc < 1) { jc = 1; } int kc = (ext[5]-ext[4]); if (kc < 1) { kc = 1; } outInfo->Set (vtkStreamingDemandDrivenPipeline::ORIGINAL_NUMBER_OF_CELLS(), ic*jc*kc); double range[2]; vtkInformationVector *miv = outInfo->Get(vtkDataObject::POINT_DATA_VECTOR()); int cnt = 0; for(size_t i=0;i<this->Internals->VariableMap.size();i++) { if(this->Internals->VariableMap[i] != -1 && this->Internals->VariableArraySelection->GetArraySetting (this->Internals->VariableMap[i]) != 0) { const char *name = this->Internals->VariableArraySelection->GetArrayName (this->Internals->VariableMap[i]); vtkInformation *fInfo = miv->GetInformationObject(cnt); if (!fInfo) { fInfo = vtkInformation::New(); miv->SetInformationObject(cnt, fInfo); fInfo->Delete(); } cnt++; range[0] = 0; range[1] = -1; if (this->Internals->RangeKeeper->Search(P, NP, ext, 0, name, 0, range)) { DEBUGPRINT_METAINFORMATION ( cerr << "Found range for " << name << " " << P << "/" << NP << " " << ext[0] << "," << ext[1] << "," << ext[2] << "," << ext[3] << "," << ext[4] << "," << ext[5] << " is " << range[0] << " .. " << range[1] << endl; ); fInfo->Set(vtkDataObject::FIELD_ARRAY_NAME(), name); fInfo->Set(vtkDataObject::PIECE_FIELD_RANGE(), range, 2); } else { DEBUGPRINT_METAINFORMATION ( cerr << "No range for " << ext[0] << "," << ext[1] << "," << ext[2] << "," << ext[3] << "," << ext[4] << "," << ext[5] << " yet" << endl; ); fInfo->Remove(vtkDataObject::FIELD_ARRAY_NAME()); fInfo->Remove(vtkDataObject::PIECE_FIELD_RANGE()); } } } } //This is overridden just to intercept requests for debugging purposes. if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { DEBUGPRINT (cerr << "SIP(" << this << ") RD =============================" << endl;); vtkInformation* outInfo = outputVector->GetInformationObject(0); int updateExtent[6]; int wholeExtent[6]; outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), updateExtent); outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent); double res = this->Internals->Resolution; if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_RESOLUTION())) { res = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_RESOLUTION()); } bool match = true; for (int i = 0; i< 6; i++) { if (updateExtent[i] != wholeExtent[i]) { match = false; } } if (match && (res == 1.0)) { vtkErrorMacro("Whole extent requested, streaming is not working."); } } int rc = this->Superclass::ProcessRequest(request, inputVector, outputVector); return rc; }
34.147152
82
0.597609
[ "object", "vector" ]
cb0bb5840a8496dcae9c9a37a685cbc34bbda052
1,724
cpp
C++
lio/io/httpclient.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
1
2021-01-23T09:24:35.000Z
2021-01-23T09:24:35.000Z
lio/io/httpclient.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
lio/io/httpclient.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
#include "httpclient.h" #include <stdarg.h> #include <stdio.h> #include <sys/ioctl.h> #include <net/if.h> namespace GNET { void LOG_TRACE(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stdout,format,args); va_end(args); puts(""); } bool get_local_ip(std::vector<std::string> &ips) { int sockfd; if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0) return false; ips.clear(); struct ifconf ifconf; char buf[512]; ifconf.ifc_len = sizeof(buf); ifconf.ifc_buf = buf; ioctl(sockfd, SIOCGIFCONF, &ifconf); //获取所有接口信息 //一个一个的获取IP地址 struct ifreq *req = (struct ifreq*)ifconf.ifc_buf; for(int i = (ifconf.ifc_len/sizeof(struct ifreq)); i>0; --i) { if(req->ifr_flags == AF_INET) //for ipv4 { //printf("name=[%s]\n", req->ifr_name); //printf("local_addr=[%s]\n", inet_ntoa(((struct sockaddr_in*)&(req->ifr_addr))->sin_addr)); ips.push_back(inet_ntoa(((struct sockaddr_in*)&(req->ifr_addr))->sin_addr)); ++req; } } return !ips.empty(); } HttpConnectIO *CreateHttpLink(const HttpClientSession &session, const char *ip, int port) { int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(s < 0) return NULL; struct sockaddr addr; memset(&addr, 0, sizeof(addr)); struct sockaddr_in *pad = (struct sockaddr_in *)&addr; pad->sin_family = AF_INET; pad->sin_addr.s_addr = inet_addr(ip); pad->sin_port = htons(port); int optval = 1; setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)); optval = 1; setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval)); return (HttpConnectIO*)PollController::Register(new HttpConnectIO(s, addr, session), true, true); } }
27.806452
104
0.655452
[ "vector" ]
cb17b9b78b2f08cda71539ab5b0d6031eb171120
2,341
hpp
C++
src/vbk/pop_service.hpp
VeriBlock/b
1c2dccb1f87251b72049b75cc4db630c4da1b5c9
[ "MIT" ]
null
null
null
src/vbk/pop_service.hpp
VeriBlock/b
1c2dccb1f87251b72049b75cc4db630c4da1b5c9
[ "MIT" ]
14
2020-11-09T11:25:12.000Z
2022-03-30T04:02:05.000Z
src/vbk/pop_service.hpp
VeriBlock/b
1c2dccb1f87251b72049b75cc4db630c4da1b5c9
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SRC_VBK_POP_SERVICE_HPP #define BITCOIN_SRC_VBK_POP_SERVICE_HPP #include "pop_common.hpp" #include <vbk/adaptors/payloads_provider.hpp> class BlockValidationState; class CBlock; class CBlockTreeDB; class CBlockIndex; class CDBIterator; class CDBWrapper; class CChainParams; namespace Consensus { struct Params; } namespace VeriBlock { using BlockBytes = std::vector<uint8_t>; using PoPRewards = std::map<CScript, CAmount>; void InitPopContext(CDBWrapper& db); CBlockIndex* compareTipToBlock(CBlockIndex* candidate); bool acceptBlock(const CBlockIndex& indexNew, BlockValidationState& state); bool checkPopDataSize(const altintegration::PopData& popData, altintegration::ValidationState& state); bool addAllBlockPayloads(const CBlock& block, BlockValidationState& state); bool setState(const uint256& block, altintegration::ValidationState& state); PoPRewards getPopRewards(const CBlockIndex& pindexPrev, const CChainParams& params); void addPopPayoutsIntoCoinbaseTx(CMutableTransaction& coinbaseTx, const CBlockIndex& pindexPrev, const CChainParams& params); bool checkCoinbaseTxWithPopRewards(const CTransaction& tx, const CAmount& nFees, const CBlockIndex& pindex, const CChainParams& params, BlockValidationState& state); std::vector<BlockBytes> getLastKnownVBKBlocks(size_t blocks); std::vector<BlockBytes> getLastKnownBTCBlocks(size_t blocks); //! returns true if all tips are stored in database, false otherwise bool hasPopData(CBlockTreeDB& db); altintegration::PopData generatePopData(); void saveTrees(CDBBatch* batch); bool loadTrees(); void removePayloadsFromMempool(const altintegration::PopData& popData); int compareForks(const CBlockIndex& left, const CBlockIndex& right); void addDisconnectedPopdata(const altintegration::PopData& popData); bool isCrossedBootstrapBlock(); bool isCrossedBootstrapBlock(int32_t height); bool isPopActive(); bool isPopActive(int32_t height); // get stats on POP score comparisons uint64_t getPopScoreComparisons(); CAmount GetSubsidyMultiplier(int nHeight, const CChainParams& params); } // namespace VeriBlock #endif //BITCOIN_SRC_VBK_POP_SERVICE_HPP
33.927536
165
0.818454
[ "vector" ]
0e12fa02c6db39cb80dc1a54a363974fc9b49429
3,788
cpp
C++
csrc/apis/c/restorer.cpp
zhiqwang/mmdeploy
997d111a6f4ca9624ab3b36717748e6ce002037d
[ "Apache-2.0" ]
1
2022-02-17T06:12:31.000Z
2022-02-17T06:12:31.000Z
csrc/apis/c/restorer.cpp
zhiqwang/mmdeploy
997d111a6f4ca9624ab3b36717748e6ce002037d
[ "Apache-2.0" ]
null
null
null
csrc/apis/c/restorer.cpp
zhiqwang/mmdeploy
997d111a6f4ca9624ab3b36717748e6ce002037d
[ "Apache-2.0" ]
null
null
null
// Copyright (c) OpenMMLab. All rights reserved. #include "restorer.h" #include "codebase/mmedit/mmedit.h" #include "core/device.h" #include "core/graph.h" #include "core/mat.h" #include "core/utils/formatter.h" #include "handle.h" using namespace mmdeploy; namespace { const Value &config_template() { // clang-format off static Value v { { "pipeline", { { "tasks", { { {"name", "det"}, {"type", "Inference"}, {"params", {{"model", "TBD"}}}, {"input", {"img"}}, {"output", {"out"}} } } }, {"input", {"img"}}, {"output", {"out"}} } } }; // clang-format on return v; } template <class ModelType> int mmdeploy_restorer_create_impl(ModelType &&m, const char *device_name, int device_id, mm_handle_t *handle) { try { auto config = config_template(); config["pipeline"]["tasks"][0]["params"]["model"] = std::forward<ModelType>(m); auto restorer = std::make_unique<Handle>(device_name, device_id, std::move(config)); *handle = restorer.release(); return MM_SUCCESS; } catch (const std::exception &e) { ERROR("exception caught: {}", e.what()); } catch (...) { ERROR("unknown exception caught"); } return MM_E_FAIL; } } // namespace int mmdeploy_restorer_create(mm_model_t model, const char *device_name, int device_id, mm_handle_t *handle) { return mmdeploy_restorer_create_impl(*static_cast<Model *>(model), device_name, device_id, handle); } int mmdeploy_restorer_create_by_path(const char *model_path, const char *device_name, int device_id, mm_handle_t *handle) { return mmdeploy_restorer_create_impl(model_path, device_name, device_id, handle); } int mmdeploy_restorer_apply(mm_handle_t handle, const mm_mat_t *images, int count, mm_mat_t **results) { if (handle == nullptr || images == nullptr || count == 0 || results == nullptr) { return MM_E_INVALID_ARG; } try { auto restorer = static_cast<Handle *>(handle); Value input{Value::kArray}; for (int i = 0; i < count; ++i) { Mat _mat{images[i].height, images[i].width, PixelFormat(images[i].format), DataType(images[i].type), images[i].data, Device{"cpu"}}; input.front().push_back({{"ori_img", _mat}}); } auto output = restorer->Run(std::move(input)).value().front(); auto restorer_output = from_value<std::vector<mmedit::RestorerOutput>>(output); auto deleter = [&](mm_mat_t *p) { mmdeploy_restorer_release_result(p, count); }; std::unique_ptr<mm_mat_t[], decltype(deleter)> _results(new mm_mat_t[count]{}, deleter); for (int i = 0; i < count; ++i) { auto upscale = restorer_output[i]; auto &res = _results[i]; res.data = new uint8_t[upscale.byte_size()]; memcpy(res.data, upscale.data<uint8_t>(), upscale.byte_size()); res.format = (mm_pixel_format_t)upscale.pixel_format(); res.height = upscale.height(); res.width = upscale.width(); res.channel = upscale.channel(); res.type = (mm_data_type_t)upscale.type(); } *results = _results.release(); return MM_SUCCESS; } catch (const std::exception &e) { ERROR("exception caught: {}", e.what()); } catch (...) { ERROR("unknown exception caught"); } return MM_E_FAIL; } void mmdeploy_restorer_release_result(mm_mat_t *results, int count) { for (int i = 0; i < count; ++i) { delete[] results[i].data; } delete[] results; } void mmdeploy_restorer_destroy(mm_handle_t handle) { delete static_cast<Handle *>(handle); }
30.796748
100
0.601373
[ "vector", "model" ]
0e1906d2666d842a7f2cede13b03bfacfaba5c96
490
hpp
C++
SRCS/ENTITIES/OBJECTS/Wall.hpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
1
2021-07-12T21:59:28.000Z
2021-07-12T21:59:28.000Z
SRCS/ENTITIES/OBJECTS/Wall.hpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
null
null
null
SRCS/ENTITIES/OBJECTS/Wall.hpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** Wall ** File description: ** Wall */ #ifndef BOMBERMAN_WALL_HPP #define BOMBERMAN_WALL_HPP #include "ENTITIES/Object.hpp" #include "Collide.hpp" #include "Serialize.hpp" class Wall : public Object, public Serialize, public Collide { public: Wall(std::string path_texture, Vector3 position, std::vector<Model> *models); ~Wall(); void pack() override; static Wall *unpack(int nb, std::vector<Model> *models); }; #endif //BOMBERMAN_WALL_HPP
19.6
81
0.710204
[ "object", "vector", "model" ]
0e1bd20b8fe9a9637fb29fca63e5936b8b3292d2
10,234
hpp
C++
applications/PoromechanicsApplication/custom_elements/small_strain_U_Pw_diff_order_element.hpp
SADPR/Kratos
82d1e335d2e7e674f77022a3d91c958168805d59
[ "BSD-4-Clause" ]
null
null
null
applications/PoromechanicsApplication/custom_elements/small_strain_U_Pw_diff_order_element.hpp
SADPR/Kratos
82d1e335d2e7e674f77022a3d91c958168805d59
[ "BSD-4-Clause" ]
null
null
null
applications/PoromechanicsApplication/custom_elements/small_strain_U_Pw_diff_order_element.hpp
SADPR/Kratos
82d1e335d2e7e674f77022a3d91c958168805d59
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Ignasi de Pouplana // #if !defined(KRATOS_SMALL_STRAIN_U_PW_DIFF_ORDER_ELEMENT_H_INCLUDED ) #define KRATOS_SMALL_STRAIN_U_PW_DIFF_ORDER_ELEMENT_H_INCLUDED // Project includes #include "containers/array_1d.h" #include "includes/define.h" #include "includes/element.h" #include "includes/serializer.h" #include "geometries/geometry.h" #include "utilities/math_utils.h" #include "includes/constitutive_law.h" // Application includes #include "custom_utilities/element_utilities.hpp" #include "poromechanics_application_variables.h" namespace Kratos { class KRATOS_API(POROMECHANICS_APPLICATION) SmallStrainUPwDiffOrderElement : public Element { public: KRATOS_CLASS_POINTER_DEFINITION( SmallStrainUPwDiffOrderElement ); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Default constructor SmallStrainUPwDiffOrderElement(); // Constructor 1 SmallStrainUPwDiffOrderElement(IndexType NewId, GeometryType::Pointer pGeometry); // Constructor 2 SmallStrainUPwDiffOrderElement(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties); // Destructor virtual ~SmallStrainUPwDiffOrderElement(); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Element::Pointer Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const override; int Check(const ProcessInfo& rCurrentProcessInfo) override; void Initialize() override; void GetDofList(DofsVectorType& rElementalDofList, const ProcessInfo& rCurrentProcessInfo) const override; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo) override; void CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix,const ProcessInfo& rCurrentProcessInfo ) override; void CalculateRightHandSide(VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo) override; void CalculateMassMatrix(MatrixType& rMassMatrix, const ProcessInfo& rCurrentProcessInfo) override; void EquationIdVector(EquationIdVectorType& rResult, const ProcessInfo& rCurrentProcessInfo) const override; void GetSecondDerivativesVector(Vector& rValues, int Step = 0) override; void FinalizeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void SetValuesOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void SetValuesOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void SetValuesOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo) override; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GetValueOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void GetValueOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void GetValueOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void GetValueOnIntegrationPoints( const Variable<ConstitutiveLaw::Pointer>& rVariable, std::vector<ConstitutiveLaw::Pointer>& rValues,const ProcessInfo& rCurrentProcessInfo ) override; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalculateOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<Matrix >& rVariable, std::vector< Matrix >& rOutput, const ProcessInfo& rCurrentProcessInfo) override; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- protected: struct ElementalVariables { //Variables at all integration points Matrix NuContainer; Matrix NpContainer; GeometryType::ShapeFunctionsGradientsType DNu_DXContainer; GeometryType::ShapeFunctionsGradientsType DNp_DXContainer; Vector detJuContainer; //Variables at each integration point Vector Nu; //Contains the displacement shape functions at every node Vector Np; //Contains the pressure shape functions at every node Matrix DNu_DX; //Contains the global derivatives of the displacement shape functions Matrix GradNpT; //Contains the global derivatives of the pressure shape functions Matrix B; double IntegrationCoefficient; Vector StrainVector; Matrix ConstitutiveMatrix; Vector StressVector; //It is the "Effective Stress Vector": sigma'_ij = sigma_ij + alpha*pw*delta_ij //Variables needed for consistency with the general constitutive law double detF; Matrix F; //Nodal variables Vector BodyAcceleration; Vector DisplacementVector; Vector VelocityVector; Vector PressureVector; Vector PressureDtVector; //Properties and processinfo variables double BiotCoefficient; double BiotModulusInverse; double DynamicViscosity; Matrix IntrinsicPermeability; double NewmarkCoefficient1; double NewmarkCoefficient2; }; // Member Variables GeometryData::IntegrationMethod mThisIntegrationMethod; std::vector<ConstitutiveLaw::Pointer> mConstitutiveLawVector; Geometry< Node<3> >::Pointer mpPressureGeometry; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void CalculateAll(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo, bool CalculateLHSMatrixFlag, bool CalculateResidualVectorFlag); void InitializeElementalVariables (ElementalVariables& rVariables, const ProcessInfo& rCurrentProcessInfo); void InitializeNodalVariables (ElementalVariables& rVariables); void InitializeProperties (ElementalVariables& rVariables); void CalculateKinematics(ElementalVariables& rVariables, unsigned int PointNumber); void SetElementalVariables(ElementalVariables& rVariables,ConstitutiveLaw::Parameters& rConstitutiveParameters); void CalculateIntegrationCoefficient(double& rIntegrationCoefficient, double detJ, double weight); void CalculateAndAddLHS(MatrixType& rLeftHandSideMatrix, ElementalVariables& rVariables); void CalculateAndAddStiffnessMatrix(MatrixType& rLeftHandSideMatrix, ElementalVariables& rVariables); void CalculateAndAddCouplingMatrix(MatrixType& rLeftHandSideMatrix, ElementalVariables& rVariables); void CalculateAndAddCompressibilityMatrix(MatrixType& rLeftHandSideMatrix, ElementalVariables& rVariables); void CalculateAndAddPermeabilityMatrix(MatrixType& rLeftHandSideMatrix, ElementalVariables& rVariables); void CalculateAndAddRHS(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddStiffnessForce(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddMixBodyForce(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddCouplingTerms(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddCompressibilityFlow(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddPermeabilityFlow(VectorType& rRightHandSideVector, ElementalVariables& rVariables); void CalculateAndAddFluidBodyFlow(VectorType& rRightHandSideVector, ElementalVariables& rVariables); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private: // Serialization friend class Serializer; void save(Serializer& rSerializer) const override { KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, Element ) } void load(Serializer& rSerializer) override { KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, Element ) } // Private Operations template < class TValueType > inline void ThreadSafeNodeWrite(NodeType& rNode, const Variable<TValueType>& Var, const TValueType Value) { rNode.SetLock(); rNode.FastGetSolutionStepValue(Var) = Value; rNode.UnSetLock(); } }; // Class SmallStrainUPwDiffOrderElement } // namespace Kratos #endif // KRATOS_SMALL_STRAIN_U_PW_DIFF_ORDER_ELEMENT_H_INCLUDED defined
43.548936
188
0.645789
[ "geometry", "shape", "vector" ]
0e1ca439d26440daa81e6f4d185f89aa3494e473
536
cpp
C++
Data Structures/static rmq/max_value.cpp
Cephian/Competitive-Programming
6f14ba02245577b858db45f5f1368985aaa9fbfb
[ "MIT" ]
2
2020-02-16T20:28:08.000Z
2020-02-17T23:29:01.000Z
Data Structures/static rmq/max_value.cpp
Cephian/Competitive-Programming
6f14ba02245577b858db45f5f1368985aaa9fbfb
[ "MIT" ]
null
null
null
Data Structures/static rmq/max_value.cpp
Cephian/Competitive-Programming
6f14ba02245577b858db45f5f1368985aaa9fbfb
[ "MIT" ]
null
null
null
// O(n log n) space, O(1) query R(max)Q struct rMq { vector<vector<int> > t; rMq(){} void init(int* a, int n) { t.resize(32-__builtin_clz(n),vector<int>(n)); for(int i = 0; i < n; ++i) t[0][i] = a[i]; for(int k = 1, p = 1; k < (int)t.size(); ++k, p<<=1) for(int i = 0; i < n; ++i) t[k][i] = (i+p<n)?max(t[k-1][i],t[k-1][i+p]):t[k-1][i]; } rMq(int* a, int n) {init(a,n);} //inclusive max query inline int query(int l, int r) const { int p = 31-__builtin_clz(r-l+1); return max(t[p][l],t[p][r+1-(1<<p)]); } };
26.8
59
0.507463
[ "vector" ]
0e2b5af41186c7cd7d4dbf4dea88b21b9f5a4c27
866
cpp
C++
08/Driver.cpp
sanskarkatiyar/CSCI2270
aee0261e35d16ca8e17f8f950b080053bd6afe0f
[ "MIT" ]
2
2020-03-18T22:56:41.000Z
2020-04-16T22:33:23.000Z
08/Driver.cpp
sanskarkatiyar/CSCI2270
aee0261e35d16ca8e17f8f950b080053bd6afe0f
[ "MIT" ]
null
null
null
08/Driver.cpp
sanskarkatiyar/CSCI2270
aee0261e35d16ca8e17f8f950b080053bd6afe0f
[ "MIT" ]
2
2020-04-24T17:00:57.000Z
2021-04-05T03:55:43.000Z
#include <iostream> #include <vector> #include "Graph.hpp" using namespace std; int main() { // edges are undirected Graph g; g.addVertex("B"); g.addVertex("D"); // g.addVertex("C"); // to demonstrate edge feature g.addVertex("F"); // g.addVertex("M"); // to demonstrate edge feature g.addVertex("L"); g.addEdge("C","M"); // will create the node as well g.addEdge("B", "D"); g.addEdge("B", "C"); g.addEdge("B", "F"); g.addEdge("F", "D"); g.addEdge("M","F"); g.addEdge("L","M"); g.removeVertex("L"); g.addEdge("L","M"); g.addEdge("L", "M"); // check edge exists g.displayEdges(); cout << endl; g.breadthFirstTraverse_iterative("C"); g.breadthFirstTraverse_recursive("C"); g.depthFirstTraverse_iterative("C"); g.depthFirstTraverse_recursive("C"); return 0; }
21.121951
56
0.576212
[ "vector" ]
0e2c174e298d3306026add8f3cce289bdf822a85
2,321
cpp
C++
leetcode/1947/solution.cpp
mkmark/leetcode
638a9d37fb3223107d2852ce493d831996a7649e
[ "MIT" ]
null
null
null
leetcode/1947/solution.cpp
mkmark/leetcode
638a9d37fb3223107d2852ce493d831996a7649e
[ "MIT" ]
null
null
null
leetcode/1947/solution.cpp
mkmark/leetcode
638a9d37fb3223107d2852ce493d831996a7649e
[ "MIT" ]
null
null
null
/* author: mark@mkmark.net time: O(P_m^m) space: O(2^m) Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Compatibility Score Sum. Memory Usage: 10.2 MB, less than 28.86% of C++ online submissions for Maximum Compatibility Score Sum. */ #include <vector> // std::vector #include <iostream> // std::iostream using namespace std; class Solution { public: static const int MAX = 1<<8; int dp[MAX]; int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) { int m = students.size(); int n = students[0].size(); int students_bit[8]; int mentors_bit[8]; for (int i=0; i<m; ++i){ students_bit[i] = vec_to_int(students[i]); mentors_bit[i] = vec_to_int(mentors[i]); } int compatibility[8][8]; for (int i=0; i<m; ++i){ for (int j=0; j<m; ++j){ compatibility[i][j] = count_bin_0(students_bit[i] ^ mentors_bit[j], n); } } for (int i=0;i<(1<<m);++i){ dp[i] = 0; } return dfs_max_sum(compatibility, m, 0, 0); } inline int vec_to_int(vector<int> v){ int res = 0; for (int i=0; i<v.size(); ++i){ res |= (v[i]<<i); } return res; } inline int count_bin_0(int num, int n){ int count = 0; for (int i=0; i<n; ++i){ count += ((num & (1<<i)) == 0); } return count; } int dfs_max_sum( int compatibility[8][8], int& m, int i, int used_j_mask ){ if (i>=m){ return 0; } if (dp[used_j_mask] != 0){ return dp[used_j_mask]; } int res = 0; for (int j=0; j<m; ++j){ // j used, skip if (used_j_mask & (1<<j)){ continue; } res = max( res, compatibility[i][j] + dfs_max_sum( compatibility, m, i+1, used_j_mask | (1<<j) ) ); } return dp[used_j_mask] = res; } }; static bool _foo = ios::sync_with_stdio(false); static ostream* _bar = cin.tie(NULL);
24.431579
102
0.467471
[ "vector" ]
0e2c8ccab5d4821b795782f6d09a30e4d116bbb8
1,458
cxx
C++
test/sframe_query_engine/operators/sarray_source.cxx
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
test/sframe_query_engine/operators/sarray_source.cxx
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
test/sframe_query_engine/operators/sarray_source.cxx
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
#define BOOST_TEST_MODULE #include <boost/test/unit_test.hpp> #include <core/util/test_macros.hpp> #include <core/storage/query_engine/execution/execution_node.hpp> #include <core/storage/query_engine/operators/sarray_source.hpp> #include <core/storage/sframe_data/sarray.hpp> #include <core/storage/sframe_data/algorithm.hpp> #include "check_node.hpp" using namespace turi; using namespace turi::query_eval; struct sarray_source_test { public: void test_empty_source() { auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); sa->close(); auto node = make_node(sa); check_node(node, std::vector<flexible_type>()); } void test_simple_sarray() { std::vector<flexible_type> expected {0,1,2,3,4,5}; auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); turi::copy(expected.begin(), expected.end(), *sa); sa->close(); auto node = make_node(sa); check_node(node, expected); } std::shared_ptr<execution_node> make_node(std::shared_ptr<sarray<flexible_type>> source) { auto node = std::make_shared<execution_node>(std::make_shared<op_sarray_source>(source)); return node; } }; BOOST_FIXTURE_TEST_SUITE(_sarray_source_test, sarray_source_test) BOOST_AUTO_TEST_CASE(test_empty_source) { sarray_source_test::test_empty_source(); } BOOST_AUTO_TEST_CASE(test_simple_sarray) { sarray_source_test::test_simple_sarray(); } BOOST_AUTO_TEST_SUITE_END()
29.755102
93
0.745542
[ "vector" ]
0e304885d8a7670204c41d2b4cd3b2798dbfed71
1,172
hpp
C++
stan/math/prim/arr/fun/array_builder.hpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
1
2019-07-23T14:57:41.000Z
2019-07-23T14:57:41.000Z
stan/math/prim/arr/fun/array_builder.hpp
Capri2014/math
d4042bdf8623bba5a1633b557227325a324e32e9
[ "BSD-3-Clause" ]
1
2019-09-23T19:58:36.000Z
2019-09-24T12:03:41.000Z
stan/math/prim/arr/fun/array_builder.hpp
riddell-stan/math
d84ee0d991400d6cf4b08a07a4e8d86e0651baea
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_ARR_FUN_ARRAY_BUILDER_HPP #define STAN_MATH_PRIM_ARR_FUN_ARRAY_BUILDER_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/scal/fun/promote_elements.hpp> #include <vector> namespace stan { namespace math { /** * Structure for building up arrays in an expression (rather than * in statements) using an argumentchaining add() method and * a getter method array() to return the result. * Array elements are held in std::vector of type T. * * @tparam T type of array elements */ template <typename T> class array_builder { private: std::vector<T> x_; public: /** * Construct an array_builder. */ array_builder() : x_() {} /** * Add one element of type S to array, promoting to type T. * * @param u element to add * @returns this array_builder object */ template <typename S> array_builder& add(const S& u) { x_.push_back(promote_elements<T, S>::promote(u)); return *this; } /** * Getter method to return array itself. * * @returns std:vector<T> of composed array elements. */ std::vector<T> array() { return x_; } }; } // namespace math } // namespace stan #endif
22.113208
65
0.6843
[ "object", "vector" ]
0e307ceb7c43ca38ef4ac398dcfc2c3545ac3ea4
44,658
cpp
C++
src/tree/node.cpp
sagpant/cascadb
cc2a118f2548fd7221e8dba42774edea8af080f7
[ "BSD-3-Clause" ]
166
2015-01-26T15:21:26.000Z
2022-03-25T03:22:27.000Z
src/tree/node.cpp
sagpant/cascadb
cc2a118f2548fd7221e8dba42774edea8af080f7
[ "BSD-3-Clause" ]
1
2015-05-01T23:52:46.000Z
2015-05-01T23:52:46.000Z
src/tree/node.cpp
weicao/cascadb
cc2a118f2548fd7221e8dba42774edea8af080f7
[ "BSD-3-Clause" ]
44
2015-01-26T15:21:28.000Z
2021-05-29T14:18:35.000Z
// Copyright (c) 2013 The CascaDB 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 <assert.h> #include <algorithm> #include <set> #include <stdexcept> #include "node.h" #include "tree.h" #include "keycomp.h" #include "util/logger.h" #include "util/crc16.h" #include "util/bloom.h" using namespace std; using namespace cascadb; /******************************************************** SchemaNode *********************************************************/ #define SCHEMA_NODE_SIZE 32 size_t SchemaNode::size() { return SCHEMA_NODE_SIZE; } size_t SchemaNode::estimated_buffer_size() { return SCHEMA_NODE_SIZE; } bool SchemaNode::read_from(BlockReader& reader, bool skeleton_only) { if (!reader.readUInt64(&root_node_id)) return false; if (!reader.readUInt64(&next_inner_node_id)) return false; if (!reader.readUInt64(&next_leaf_node_id)) return false; if (!reader.readUInt64(&tree_depth)) return false; return true; } bool SchemaNode::write_to(BlockWriter& writer, size_t& skeleton_size) { if (!writer.writeUInt64(root_node_id)) return false; if (!writer.writeUInt64(next_inner_node_id)) return false; if (!writer.writeUInt64(next_leaf_node_id)) return false; if (!writer.writeUInt64(tree_depth)) return false; skeleton_size = SCHEMA_NODE_SIZE; return true; } /******************************************************** InnerNode *********************************************************/ InnerNode::~InnerNode() { delete first_msgbuf_; first_msgbuf_ = NULL; for(vector<Pivot>::iterator it = pivots_.begin(); it != pivots_.end(); it++) { it->key.destroy(); delete it->msgbuf; } pivots_.clear(); } void InnerNode::init_empty_root() { assert(first_msgbuf_ == NULL); // create the first child for root first_msgbuf_ = new MsgBuf(tree_->options_.comparator); msgbufsz_ = first_msgbuf_->size(); bottom_ = true; set_dirty(true); } bool InnerNode::write(const Msg& m) { read_lock(); if (status_ == kSkeletonLoaded) { load_all_msgbuf(); } Slice k = m.key; insert_msgbuf(m, find_pivot(k)); set_dirty(true); maybe_cascade(); return true; } bool InnerNode::cascade(MsgBuf *mb, InnerNode* parent){ read_lock(); // lazy load if (status_ == kSkeletonLoaded) { load_all_msgbuf(); } // lock message buffer mb->write_lock(); size_t oldcnt = mb->count(); size_t oldsz = mb->size(); MsgBuf::Iterator rs, it, end; rs = it = mb->begin(); // range start end = mb->end(); // range end size_t i = 0; while (it != end && i < pivots_.size()) { if( comp_pivot(it->key, i) < 0 ) { it ++; } else { if (rs != it) { insert_msgbuf(rs, it, i); rs = it; } i ++; } } if(rs != end) { insert_msgbuf(rs, end, i); } // clear message buffer and modify parent's status mb->clear(); parent->msgcnt_ = parent->msgcnt_ + mb->count() - oldcnt; parent->msgbufsz_ = parent->msgbufsz_ + mb->size() - oldsz; // unlock message buffer mb->unlock(); // crab walk parent->unlock(); set_dirty(true); maybe_cascade(); return true; } int InnerNode::comp_pivot(Slice k, int i) { assert(i >=0 && (size_t)i < pivots_.size()); return tree_->options_.comparator->compare(k, pivots_[i].key); } int InnerNode::find_pivot(Slice k) { // int idx = 0; // for(vector<Pivot>::iterator it = pivots_.begin(); // it != pivots_.end(); it++ ) { // if (tree_->options_.comparator->compare(k, it->key) < 0) { // return idx; // } // idx ++; // } // return idx; // optimize for sequential write size_t size = pivots_.size(); if (size && tree_->options_.comparator->compare(pivots_[size-1].key, k) < 0) { return size; } vector<Pivot>::iterator first = pivots_.begin(); vector<Pivot>::iterator last = pivots_.end(); vector<Pivot>::iterator it; // binary search iterator_traits<vector<Pivot>::iterator>::difference_type count, step; count = distance(first,last); while (count > 0) { it = first; step = count/2; advance(it, step); if (tree_->options_.comparator->compare(it->key, k) <= 0) { first = ++ it; count -= step + 1; } else { count = step; } } return distance(pivots_.begin(), first); } MsgBuf* InnerNode::msgbuf(int idx) { assert(idx >= 0 && (size_t)idx <= pivots_.size()); MsgBuf **pb = (idx == 0) ? &first_msgbuf_ : &(pivots_[idx-1].msgbuf); if (*pb) { return *pb; } else { assert(status_ == kSkeletonLoaded); load_msgbuf(idx); return *pb; } } MsgBuf* InnerNode::msgbuf(int idx, Slice& key) { assert(idx >= 0 && (size_t)idx <= pivots_.size()); Slice *filter = (idx == 0) ? &first_filter_ : &pivots_[idx-1].filter; MsgBuf **pb = (idx == 0) ? &first_msgbuf_ : &(pivots_[idx-1].msgbuf); if (*pb) { return *pb; } else { assert(status_ == kSkeletonLoaded); // i am not in this msgbuf, don't to load msgbuf if (bloom_matches(key, *filter)) load_msgbuf(idx); return *pb; } } bid_t InnerNode::child(int idx) { assert(idx >= 0 && (size_t)idx <= pivots_.size()); if (idx == 0) { return first_child_; } else { return pivots_[idx-1].child; } } void InnerNode::set_child(int idx, bid_t c) { assert(idx >= 0 && (size_t)idx <= pivots_.size()); if (idx == 0) { first_child_ = c; } else { pivots_[idx-1].child = c; } } void InnerNode::insert_msgbuf(const Msg& m, int idx) { MsgBuf *b = msgbuf(idx); assert(b); b->write_lock(); size_t oldcnt = b->count(); size_t oldsz = b->size(); b->write(m); msgcnt_ = msgcnt_ + b->count() - oldcnt; msgbufsz_ = msgbufsz_ + b->size() - oldsz; b->unlock(); } void InnerNode::insert_msgbuf(MsgBuf::Iterator begin, MsgBuf::Iterator end, int idx) { MsgBuf *b = msgbuf(idx); assert(b); b->write_lock(); size_t oldcnt = b->count(); size_t oldsz = b->size(); b->append(begin, end); msgcnt_ = msgcnt_ + b->count() - oldcnt; msgbufsz_ = msgbufsz_ + b->size() - oldsz; b->unlock(); } int InnerNode::find_msgbuf_maxcnt() { int idx = 0, ret = 0; size_t maxcnt = first_msgbuf_->count(); for(vector<Pivot>::iterator it = pivots_.begin(); it != pivots_.end(); it++ ) { idx ++; if (it->msgbuf->count() > maxcnt ) { it->msgbuf->read_lock(); maxcnt = it->msgbuf->count(); it->msgbuf->unlock(); ret = idx; } } return ret; } int InnerNode::find_msgbuf_maxsz() { int idx = 0, ret = 0; size_t maxsz = first_msgbuf_->size(); for(vector<Pivot>::iterator it = pivots_.begin(); it != pivots_.end(); it++ ) { idx ++; if (it->msgbuf->size() > maxsz ) { it->msgbuf->read_lock(); maxsz = it->msgbuf->size(); it->msgbuf->unlock(); ret = idx; } } return ret; } void InnerNode::maybe_cascade() { int idx = -1; if (msgcnt_ >= tree_->options_.inner_node_msg_count) { idx = find_msgbuf_maxcnt(); } else if (size() >= tree_->options_.inner_node_page_size) { idx = find_msgbuf_maxsz(); } else { unlock(); return; } assert(idx >= 0); MsgBuf* b = msgbuf(idx); bid_t nid = child(idx); DataNode *node = NULL; if (nid == NID_NIL) { // cannot be inner node assert(bottom_); node = tree_->new_leaf_node(); set_child(idx, node->nid()); } else { node = tree_->load_node(nid, false); } assert(node); node->cascade(b, this); node->dec_ref(); // it's possible to cascade twice // lock is released in child, so it's nescessarty to obtain it again read_lock(); if (msgcnt_ >= tree_->options_.inner_node_msg_count || size() >= tree_->options_.inner_node_page_size) { maybe_cascade(); } else { unlock(); } } void InnerNode::add_pivot(Slice key, bid_t nid, std::vector<DataNode*>& path) { assert(path.back() == this); if (status_ == kSkeletonLoaded) { load_all_msgbuf(); } vector<Pivot>::iterator it = std::lower_bound(pivots_.begin(), pivots_.end(), key, KeyComp(tree_->options_.comparator)); MsgBuf* mb = new MsgBuf(tree_->options_.comparator); pivots_.insert(it, Pivot(key.clone(), nid, mb)); pivots_sz_ += pivot_size(key); msgbufsz_ += mb->size(); set_dirty(true); if (pivots_.size() + 1 > tree_->options_.inner_node_children_number) { split(path); } else { while(path.size()) { path.back()->unlock(); path.back()->dec_ref(); path.pop_back(); } } } void InnerNode::split(std::vector<DataNode*>& path) { assert(pivots_.size() > 1); size_t n = pivots_.size()/2; size_t n1 = pivots_.size() - n - 1; Slice k = pivots_[n].key; InnerNode *ni = tree_->new_inner_node(); ni->bottom_ = IS_LEAF(pivots_[n].child); assert(ni); ni->first_child_ = pivots_[n].child; ni->first_msgbuf_ = pivots_[n].msgbuf; ni->pivots_.resize(n1); std::copy(pivots_.begin() + n + 1, pivots_.end(), ni->pivots_.begin()); pivots_.resize(n); size_t pivots_sz1 = 0; size_t msgcnt1 = 0; size_t msgbufsz1 = 0; msgcnt1 += ni->first_msgbuf_->count(); msgbufsz1 += ni->first_msgbuf_->size(); for(size_t i = 0; i < ni->pivots_.size(); i++) { pivots_sz1 += pivot_size(ni->pivots_[i].key); msgcnt1 += ni->pivots_[i].msgbuf->count(); msgbufsz1 += ni->pivots_[i].msgbuf->size(); } ni->pivots_sz_ = pivots_sz1; ni->msgcnt_ = msgcnt1; ni->msgbufsz_ = msgbufsz1; pivots_sz_ -= (pivots_sz1 + pivot_size(k)); msgcnt_ -= msgcnt1; msgbufsz_ -= msgbufsz1; ni->set_dirty(true); ni->dec_ref(); path.pop_back(); unlock(); dec_ref(); // propagation if( path.size() == 0) { // i'm root InnerNode *nr = tree_->new_inner_node(); assert(nr); nr->bottom_ = false; nr->first_child_ = nid_; MsgBuf* mb0 = new MsgBuf(tree_->options_.comparator); nr->first_msgbuf_ = mb0; nr->msgbufsz_ += mb0->size(); nr->pivots_.resize(1); MsgBuf* mb1 = new MsgBuf(tree_->options_.comparator); nr->pivots_[0] = Pivot(k.clone(), ni->nid_, mb1); nr->pivots_sz_ += pivot_size(k); nr->msgbufsz_ += mb1->size(); nr->set_dirty(true); tree_->pileup(nr); // need not do nr->dec_ref() here } else { // propagation InnerNode* parent = (InnerNode*) path.back(); assert(parent); parent->add_pivot(k, ni->nid_, path); } } void InnerNode::rm_pivot(bid_t nid, std::vector<DataNode*>& path) { // todo free memory of pivot key assert(path.back() == this); if (status_ == kSkeletonLoaded) { load_all_msgbuf(); } if (first_child_ == nid) { /// @todo this is true only for single thread, fix me assert(first_msgbuf_->count() == 0); msgbufsz_ -= first_msgbuf_->size(); delete first_msgbuf_; if (pivots_.size() == 0) { first_msgbuf_ = NULL; dead_ = true; path.pop_back(); unlock(); dec_ref(); if (path.size() == 0) { // reach root tree_->collapse(); } else { // propagation InnerNode* parent = (InnerNode*) path.back(); assert(parent); parent->rm_pivot(nid_, path); } return; } // shift pivots first_child_ = pivots_[0].child; first_msgbuf_ = pivots_[0].msgbuf; pivots_sz_ -= pivot_size(pivots_[0].key); pivots_.erase(pivots_.begin()); // TODO adjst size } else { vector<Pivot>::iterator it; for (it = pivots_.begin(); it != pivots_.end(); it ++) { if (it->child == nid) { break; } } assert(it != pivots_.end()); /// @todo this is true only for single thread, fix me assert(it->msgbuf->count() == 0); msgbufsz_ -= it->msgbuf->size(); delete it->msgbuf; pivots_sz_ -= pivot_size(it->key); pivots_.erase(it); // TODO adjust size } set_dirty(true); // unlock all parents while (path.size()) { path.back()->unlock(); path.back()->dec_ref(); path.pop_back(); } } bool InnerNode::find(Slice key, Slice& value, InnerNode *parent) { bool ret = false; read_lock(); if (parent) { parent->unlock(); // lock coupling } int idx = find_pivot(key); MsgBuf* b = msgbuf(idx, key); // if b is NULL, means rejected by bloom filter if (b) { b->read_lock(); MsgBuf::Iterator it = b->find(key); if (it != b->end() && it->key == key ) { if (it->type == Put) { value = it->value.clone(); ret = true; } // otherwise deleted b->unlock(); unlock(); return ret; } b->unlock(); } bid_t chidx = child(idx); if (chidx == NID_NIL) { assert(idx == 0); // must be the first child unlock(); return false; } // find in child DataNode* ch = tree_->load_node(chidx, true); assert(ch); ret = ch->find(key, value, this); ch->dec_ref(); return ret; } void InnerNode::lock_path(Slice key, std::vector<DataNode*>& path) { int idx = find_pivot(key); DataNode* ch = tree_->load_node(child(idx), false); assert(ch); ch->write_lock(); path.push_back(ch); ch->lock_path(key, path); } size_t InnerNode::pivot_size(Slice key) { return 4 + key.size() + // key 8 + // child nid size 4 + // msgbuf offset 4 + // msgbuf length 4 + // msgbuf uncompressed length 2;// msgbuf crc } size_t InnerNode::bloom_size(int n) { return 4 + cascadb::bloom_size(n); //bloom sizes } size_t InnerNode::size() { size_t sz = 0; sz += 1 + 4 + (8 + 4 + 4 + 4 + 2); sz += pivots_sz_; sz += msgbufsz_; return sz; } size_t InnerNode::estimated_buffer_size() { size_t sz = 0; sz += 1 + 4 + (8 + 4 + 4 + 4 + 2); // first msgbuf bloom bitsets sz += bloom_size(first_msgbuf_->count()); sz += pivots_sz_; if (tree_->compressor_) { sz += tree_->compressor_->max_compressed_length(first_msgbuf_->size()); for (size_t i = 0; i < pivots_.size(); i++) { sz += tree_->compressor_->max_compressed_length(pivots_[i].msgbuf->size()); sz += bloom_size(pivots_[i].msgbuf->count()); } } else { sz += first_msgbuf_->size(); for (size_t i = 0; i < pivots_.size(); i++) { sz += pivots_[i].msgbuf->size(); sz += bloom_size(pivots_[i].msgbuf->count()); } } return sz; } bool InnerNode::read_from(BlockReader& reader, bool skeleton_only) { if (!reader.readBool(&bottom_)) return false; uint32_t pn; if (!reader.readUInt32(&pn)) return false; pivots_.resize(pn); if (!reader.readUInt64(&first_child_)) return false; if (!reader.readUInt32(&first_msgbuf_offset_)) return false; if (!reader.readUInt32(&first_msgbuf_length_)) return false; if (!reader.readUInt32(&first_msgbuf_uncompressed_length_)) return false; if (!reader.readUInt16(&first_msgbuf_crc_)) return false; if (!reader.readSlice(first_filter_)) return false; for (size_t i = 0; i < pn; i++) { if (!reader.readSlice(pivots_[i].key)) return false; pivots_sz_ += pivot_size(pivots_[i].key); if (!reader.readUInt64(&(pivots_[i].child))) return false; pivots_[i].msgbuf = NULL; // unloaded if (!reader.readUInt32(&(pivots_[i].offset))) return false; if (!reader.readUInt32(&(pivots_[i].length))) return false; if (!reader.readUInt32(&(pivots_[i].uncompressed_length))) return false; if (!reader.readUInt16(&(pivots_[i].crc))) return false; if (!reader.readSlice(pivots_[i].filter)) return false; } if (!skeleton_only) { if (!load_all_msgbuf(reader)) return false; } else { status_ = kSkeletonLoaded; } return true; } bool InnerNode::load_msgbuf(int idx) { uint32_t offset; uint32_t length; uint32_t uncompressed_length; uint16_t expected_crc; uint16_t actual_crc; if (idx == 0) { offset = first_msgbuf_offset_; length = first_msgbuf_length_; uncompressed_length = first_msgbuf_uncompressed_length_; expected_crc = first_msgbuf_crc_; } else { offset = pivots_[idx-1].offset; length = pivots_[idx-1].length; uncompressed_length = pivots_[idx-1].uncompressed_length; expected_crc = pivots_[idx-1].crc; } Block* block = tree_->layout_->read(nid_, offset, length); if (block == NULL) { LOG_ERROR("read msgbuf from layout error " << " nid " << nid_ << ", idx " << idx << ", offset " << offset << ", length " << length); return false; } actual_crc = crc16(block->start(), length); if (actual_crc != expected_crc) { LOG_ERROR("msgbuf crc error " << " nid " << nid_ << ", idx " << idx << ", expected_crc " << expected_crc << ", actual_crc " << actual_crc << ", offset " << offset << ", length " << length); tree_->layout_->destroy(block); return false; } BlockReader reader(block); Slice buffer; if (tree_->compressor_) { buffer = Slice::alloc(uncompressed_length); } MsgBuf *b = new MsgBuf(tree_->options_.comparator); assert(b); if (!read_msgbuf(reader, length, uncompressed_length, b, buffer)) { LOG_ERROR("read_msgbuf error " << " nid " << nid_ << ", idx " << idx); delete b; if (buffer.size()) { buffer.destroy(); } tree_->layout_->destroy(block); return false; } if (buffer.size()) { buffer.destroy(); } // lazy load, upgrade lock to write lock // TODO: write a upgradable rwlock unlock(); write_lock(); MsgBuf **pb = (idx == 0) ? &first_msgbuf_ : &(pivots_[idx-1].msgbuf); if (*pb == NULL) { *pb = b; msgcnt_ += b->count(); msgbufsz_ += b->size(); } else { delete b; } unlock(); read_lock(); tree_->layout_->destroy(block); return true; } bool InnerNode::load_all_msgbuf() { Block* block = tree_->layout_->read(nid_, false); if (block == NULL) { LOG_ERROR("load all msgbuf error, cannot read " << " nid " << nid_); return false; } BlockReader reader(block); // lazy load, upgrade lock to write lock // TODO: write a upgradable rwlock unlock(); write_lock(); bool ret = load_all_msgbuf(reader); unlock(); read_lock(); tree_->layout_->destroy(block); return ret; } bool InnerNode::load_all_msgbuf(BlockReader& reader) { Slice buffer; if (tree_->compressor_) { size_t buffer_length = first_msgbuf_uncompressed_length_; for (size_t i = 0; i < pivots_.size(); i++) { if (buffer_length < pivots_[i].uncompressed_length) { buffer_length = pivots_[i].uncompressed_length; } } buffer = Slice::alloc(buffer_length); } if (first_msgbuf_ == NULL) { reader.seek(first_msgbuf_offset_); first_msgbuf_ = new MsgBuf(tree_->options_.comparator); if (!read_msgbuf(reader, first_msgbuf_length_, first_msgbuf_uncompressed_length_, first_msgbuf_, buffer)) { if (buffer.size()) { buffer.destroy(); } return false; } msgcnt_ += first_msgbuf_->count(); msgbufsz_ += first_msgbuf_->size(); } for (size_t i = 0; i < pivots_.size(); i++) { if (pivots_[i].msgbuf == NULL) { reader.seek(pivots_[i].offset); pivots_[i].msgbuf = new MsgBuf(tree_->options_.comparator); if (!read_msgbuf(reader, pivots_[i].length, pivots_[i].uncompressed_length, pivots_[i].msgbuf, buffer)) { if (buffer.size()) { buffer.destroy(); } return false; } msgcnt_ += pivots_[i].msgbuf->count(); msgbufsz_ += pivots_[i].msgbuf->size(); } } if (buffer.size()) { buffer.destroy(); } status_ = kFullLoaded; return true; } bool InnerNode::read_msgbuf(BlockReader& reader, size_t compressed_length, size_t uncompressed_length, MsgBuf *mb, Slice buffer) { if (tree_->compressor_) { assert(compressed_length <= reader.remain()); assert(uncompressed_length <= buffer.size()); // 1. uncompress if (!tree_->compressor_->uncompress(reader.addr(), compressed_length, (char *)buffer.data())) { return false; } reader.skip(compressed_length); // 2. deserialize Block block(buffer, 0, uncompressed_length); BlockReader rr(&block); return mb->read_from(rr); } else { return mb->read_from(reader); } } bool InnerNode::write_to(BlockWriter& writer, size_t& skeleton_size) { // get length of skeleton and reserve space for skeleton size_t skeleton_offset = writer.pos(); size_t skeleton_length = 1 + 4 + 8 + 4 + 4 + 4 + 2 + bloom_size(first_msgbuf_->count()); for (size_t i = 0; i < pivots_.size(); i++) { skeleton_length += pivot_size(pivots_[i].key); skeleton_length += bloom_size(pivots_[i].msgbuf->count()); } if (!writer.skip(skeleton_length)) return false; // prepare buffer if compression is enabled Slice buffer; if (tree_->compressor_) { // get buffer length to serialize msgbuf size_t buffer_length = first_msgbuf_->size(); for (size_t i = 0; i < pivots_.size(); i++) { if (pivots_[i].msgbuf->size() > buffer_length) buffer_length = pivots_[i].msgbuf->size(); } buffer = Slice::alloc(buffer_length); } char *mb_start; // write the first msgbuf mb_start = writer.addr(); first_msgbuf_offset_ = writer.pos(); if (!write_msgbuf(writer, first_msgbuf_, buffer)) return false; first_msgbuf_length_ = writer.pos() - first_msgbuf_offset_; first_msgbuf_uncompressed_length_ = first_msgbuf_->size(); first_msgbuf_crc_ = crc16(mb_start, first_msgbuf_length_); // write rest msgbufs for (size_t i = 0; i < pivots_.size(); i++) { mb_start = writer.addr(); pivots_[i].offset = writer.pos(); if (!write_msgbuf(writer, pivots_[i].msgbuf, buffer)) return false; pivots_[i].length = writer.pos() - pivots_[i].offset; pivots_[i].uncompressed_length = pivots_[i].msgbuf->size(); pivots_[i].crc = crc16(mb_start, pivots_[i].length); } if (buffer.size()) { buffer.destroy(); } size_t last_offset = writer.pos(); // seek to the head and write index writer.seek(skeleton_offset); if (!writer.writeBool(bottom_)) return false; if (!writer.writeUInt32(pivots_.size())) return false; if (!writer.writeUInt64(first_child_)) return false; if (!writer.writeUInt32(first_msgbuf_offset_)) return false; if (!writer.writeUInt32(first_msgbuf_length_)) return false; if (!writer.writeUInt32(first_msgbuf_uncompressed_length_)) return false; if (!writer.writeUInt16(first_msgbuf_crc_)) return false; // first msgbuf bloom filter std::string filter; first_msgbuf_->get_filter(&filter); first_filter_ = Slice(filter); if (!writer.writeSlice(first_filter_)) return false; filter.clear(); for (size_t i = 0; i < pivots_.size(); i++) { if (!writer.writeSlice(pivots_[i].key)) return false; if (!writer.writeUInt64(pivots_[i].child)) return false; if (!writer.writeUInt32(pivots_[i].offset)) return false; if (!writer.writeUInt32(pivots_[i].length)) return false; if (!writer.writeUInt32(pivots_[i].uncompressed_length)) return false; if (!writer.writeUInt16(pivots_[i].crc)) return false; // get the bloom filter bitsets pivots_[i].msgbuf->get_filter(&filter); if (!writer.writeSlice(Slice(filter))) return false; filter.clear(); } writer.seek(last_offset); skeleton_size = skeleton_length; return true; } bool InnerNode::write_msgbuf(BlockWriter& writer, MsgBuf *mb, Slice buffer) { if (tree_->compressor_) { // 1. write to buffer Block block(buffer, 0, 0); BlockWriter wr(&block); if (!mb->write_to(wr)) return false; // 2. compress assert(tree_->compressor_->max_compressed_length(block.size()) <= writer.remain()); size_t compressed_length; if (!tree_->compressor_->compress(buffer.data(), block.size(), writer.addr(), &compressed_length)) { LOG_ERROR("compress msgbuf error, nid " << nid_); return false; } // 3. skip writer.skip(compressed_length); return true; } else { return mb->write_to(writer); } } /******************************************************** LeafNode *********************************************************/ LeafNode::LeafNode(const std::string& table_name, bid_t nid, Tree *tree) : DataNode(table_name, nid, tree), balancing_(false), left_sibling_(NID_NIL), right_sibling_(NID_NIL), buckets_info_size_(0), records_(tree->options_.leaf_node_bucket_size) { assert(nid >= NID_LEAF_START); } LeafNode::~LeafNode() { for (size_t i = 0; i < buckets_info_.size(); i++ ) { buckets_info_[i].key.destroy(); } for (size_t i = 0; i < records_.buckets_number(); i++ ) { RecordBucket *bucket = records_.bucket(i); if (bucket) { for (RecordBucket::iterator it = bucket->begin(); it != bucket->end(); it++) { it->key.destroy(); it->value.destroy(); } } } } bool LeafNode::cascade(MsgBuf *mb, InnerNode* parent) { write_lock(); if (status_ == kSkeletonLoaded) { load_all_buckets(); } // lock message buffer from parent mb->write_lock(); size_t oldcnt = mb->count(); size_t oldsz = mb->size(); Slice anchor = mb->begin()->key.clone(); // merge message buffer into leaf RecordBuckets res(tree_->options_.leaf_node_bucket_size); MsgBuf::Iterator it = mb->begin(); RecordBuckets::Iterator jt = records_.get_iterator(); while (it != mb->end() && jt.valid()) { int n = tree_->options_.comparator->compare(it->key, jt.record().key); if (n < 0) { if (it->type == Put) { res.push_back(to_record(*it)); } else { // just throw deletion to non-exist record it->destroy(); } it ++; } else if (n > 0) { res.push_back(jt.record()); jt.next(); } else { if (it->type == Put) { res.push_back(to_record(*it)); } // old record is deleted it ++; jt.record().key.destroy(); jt.record().value.destroy(); jt.next(); } } for (; it != mb->end(); it++) { if (it->type == Put) { res.push_back(to_record(*it)); } } while(jt.valid()) { res.push_back(jt.record()); jt.next(); } records_.swap(res); refresh_buckets_info(); set_dirty(true); // clear message buffer mb->clear(); parent->msgcnt_ = parent->msgcnt_ + mb->count() - oldcnt; parent->msgbufsz_ = parent->msgbufsz_ + mb->size() - oldsz; // unlock message buffer mb->unlock(); // crab walk parent->unlock(); if (records_.size() == 0) { merge(anchor); } else if (records_.size() > 1 && (records_.size() > tree_->options_.leaf_node_record_count || size() > tree_->options_.leaf_node_page_size)) { split(anchor); } else { unlock(); } anchor.destroy(); return true; } Record LeafNode::to_record(const Msg& m) { assert(m.type == Put); return Record(m.key, m.value); } void LeafNode::split(Slice anchor) { if (balancing_) { unlock(); return; } balancing_ = true; assert(records_.size() > 1); // release the write lock unlock(); // need to search from root to leaf again // since the path may be modified vector<DataNode*> path; tree_->lock_path(anchor, path); assert(path.back() == this); // may have deletions during this period if (records_.size() <= 1 || (records_.size() <= (tree_->options_.leaf_node_record_count / 2) && size() <= (tree_->options_.leaf_node_page_size / 2) )) { while (path.size()) { path.back()->unlock(); path.back()->dec_ref(); path.pop_back(); } return; } // create new leaf LeafNode *nl = tree_->new_leaf_node(); assert(nl); // set siblings nl->left_sibling_ = nid_; nl->right_sibling_ = right_sibling_; if(right_sibling_ >= NID_LEAF_START) { LeafNode *rl = (LeafNode*)tree_->load_node(right_sibling_, false); assert(rl); rl->write_lock(); rl->left_sibling_ = nl->nid_; rl->set_dirty(true); rl->unlock(); rl->dec_ref(); } right_sibling_ = nl->nid_; Slice k = records_.split(nl->records_); refresh_buckets_info(); nl->refresh_buckets_info(); set_dirty(true); nl->set_dirty(true); nl->dec_ref(); balancing_ = false; path.pop_back(); unlock(); dec_ref(); // propagation InnerNode *parent = (InnerNode*) path.back(); assert(parent); parent->add_pivot(k, nl->nid_, path); } void LeafNode::merge(Slice anchor) { if (balancing_) { unlock(); return; } balancing_ = true; assert(records_.size() == 0); // release the write lock unlock(); // acquire write locks from root to leaf vector<DataNode*> path; tree_->lock_path(anchor, path); assert(path.back() == this); // may have insertions during this period if (records_.size() > 0) { while (path.size()) { path.back()->unlock(); path.back()->dec_ref(); path.pop_back(); } return; } if (left_sibling_ >= NID_LEAF_START) { LeafNode *ll = (LeafNode*)tree_->load_node(left_sibling_, false); assert(ll); ll->write_lock(); ll->right_sibling_ = right_sibling_; ll->set_dirty(true); ll->unlock(); ll->dec_ref(); } if (right_sibling_ >= NID_LEAF_START) { LeafNode *rl = (LeafNode*)tree_->load_node(right_sibling_, false); assert(rl); rl->write_lock(); rl->left_sibling_ = left_sibling_; rl->set_dirty(true); rl->unlock(); rl->dec_ref(); } dead_ = true; balancing_ = false; path.pop_back(); unlock(); dec_ref(); // propagation InnerNode *parent = (InnerNode*) path.back(); assert(parent); parent->rm_pivot(nid_, path); } bool LeafNode::find(Slice key, Slice& value, InnerNode *parent) { assert(parent); read_lock(); parent->unlock(); size_t idx = 0; for (; idx < buckets_info_.size(); idx ++) { if (tree_->options_.comparator->compare(key, buckets_info_[idx].key) < 0) { break; } } if (idx == 0) { unlock(); return false; } RecordBucket *bucket = records_.bucket(idx - 1); if (bucket == NULL) { if (!load_bucket(idx - 1)) { LOG_ERROR("load bucket error nid " << nid_ << ", bucket " << (idx-1)); unlock(); return false; } bucket = records_.bucket(idx - 1); assert(bucket); } bool ret = false; vector<Record>::iterator it = lower_bound( bucket->begin(), bucket->end(), key, KeyComp(tree_->options_.comparator)); if (it != bucket->end() && it->key == key) { ret = true; value = it->value.clone(); } unlock(); return ret; } void LeafNode::lock_path(Slice key, std::vector<DataNode*>& path) { } size_t LeafNode::size() { return 8 + 8 + buckets_info_size_ + records_.length(); } size_t LeafNode::estimated_buffer_size() { size_t length = 8 + 8 + buckets_info_size_; if (tree_->compressor_) { for (size_t i = 0; i < records_.buckets_number(); i++) { length += tree_->compressor_->max_compressed_length(records_.bucket_length(i)); } } else { length += records_.length(); } return length; } bool LeafNode::read_from(BlockReader& reader, bool skeleton_only) { if (!reader.readUInt64(&left_sibling_)) return false; if (!reader.readUInt64(&right_sibling_)) return false; if (!read_buckets_info(reader)) { LOG_ERROR("read buckets info error, nid " << nid_); return false; } if (!skeleton_only) { if (!load_all_buckets(reader)) { LOG_ERROR("read all records bucket error, nid " << nid_); return false; } } return true; } bool LeafNode::write_to(BlockWriter& writer, size_t& skeleton_size) { assert(status_ == kNew || status_ == kFullLoaded); size_t skeleton_pos = writer.pos(); skeleton_size = 8 + 8 + buckets_info_size_; if (!writer.skip(skeleton_size)) return false; Slice buffer; if (tree_->compressor_) { size_t buffer_length = 0; for (size_t i = 0; i < records_.buckets_number(); i++) { if (buffer_length < records_.bucket_length(i)) { buffer_length = records_.bucket_length(i); } } buffer = Slice::alloc(buffer_length); } assert(records_.buckets_number() == buckets_info_.size()); for (size_t i = 0; i < records_.buckets_number(); i++ ) { RecordBucket* bucket = records_.bucket(i); char *bkt_buffer = writer.addr(); buckets_info_[i].offset = writer.pos(); if (!write_bucket(writer, bucket, buffer)) { if (buffer.size()) { buffer.destroy(); } return false; } buckets_info_[i].length = writer.pos() - buckets_info_[i].offset; buckets_info_[i].uncompressed_length = records_.bucket_length(i); buckets_info_[i].crc = crc16(bkt_buffer, buckets_info_[i].length); } size_t last_pos = writer.pos(); if (buffer.size()) { buffer.destroy(); } writer.seek(skeleton_pos); if (!writer.writeUInt64(left_sibling_)) return false; if (!writer.writeUInt64(right_sibling_)) return false; if (!write_buckets_info(writer)) { LOG_ERROR("write buckets info error, nid " << nid_); return false; } writer.seek(last_pos); return true; } bool LeafNode::write_bucket(BlockWriter& writer, RecordBucket *bucket, Slice buffer) { if (tree_->compressor_) { // 1. write to buffer Block block(buffer, 0, 0); BlockWriter wr(&block); if (!write_bucket(wr, bucket)) return false; // 2. compress assert(tree_->compressor_->max_compressed_length(block.size()) <= writer.remain()); size_t compressed_length; if (!tree_->compressor_->compress(buffer.data(), block.size(), writer.addr(), &compressed_length)) { LOG_ERROR("compress msgbuf error, nid " << nid_); return false; } // 3. skip writer.skip(compressed_length); return true; } else { return write_bucket(writer, bucket); } } bool LeafNode::write_bucket(BlockWriter& writer, RecordBucket *bucket) { if (!writer.writeUInt32(bucket->size())) return false; for (size_t j = 0; j < bucket->size(); j++) { if (!(*bucket)[j].write_to(writer)) return false; } return true; } void LeafNode::refresh_buckets_info() { // clean old info for (size_t i = 0; i < buckets_info_.size(); i++) { buckets_info_[i].key.destroy(); } buckets_info_size_ = 4; buckets_info_.resize(records_.buckets_number()); for (size_t i = 0; i < records_.buckets_number(); i++) { RecordBucket *bucket = records_.bucket(i); assert(bucket); assert(bucket->size()); buckets_info_[i].key = bucket->front().key.clone(); buckets_info_[i].offset = 0; buckets_info_[i].length = 0; buckets_info_[i].uncompressed_length = 0; buckets_info_[i].crc = 0; buckets_info_size_ += 4 + buckets_info_[i].key.size() + 4 // sizeof(offset) + 4 // sizeof(length) + 4 // sizeof(uncomoressed_length) + 2;// sizeof(crc) } } bool LeafNode::read_buckets_info(BlockReader& reader) { uint32_t nbuckets; if (!reader.readUInt32(&nbuckets)) return false; buckets_info_.resize(nbuckets); buckets_info_size_ = 4; for (size_t i = 0; i < nbuckets; i++ ) { if (!reader.readSlice(buckets_info_[i].key)) return false; if (!reader.readUInt32(&(buckets_info_[i].offset))) return false; if (!reader.readUInt32(&(buckets_info_[i].length))) return false; if (!reader.readUInt32(&(buckets_info_[i].uncompressed_length))) return false; if (!reader.readUInt16(&(buckets_info_[i].crc))) return false; buckets_info_size_ += 4 + buckets_info_[i].key.size() + 4 // sizeof(offset) + 4 // sizeof(length) + 4 // sizeof(uncomoressed_length) + 2;// sizeof(crc) } // init buckets number records_.set_buckets_number(nbuckets); status_ = kSkeletonLoaded; return true; } bool LeafNode::write_buckets_info(BlockWriter& writer) { if (!writer.writeUInt32(buckets_info_.size())) return false; for (size_t i = 0; i < buckets_info_.size(); i++ ) { if (!writer.writeSlice(buckets_info_[i].key)) return false; if (!writer.writeUInt32(buckets_info_[i].offset)) return false; if (!writer.writeUInt32(buckets_info_[i].length)) return false; if (!writer.writeUInt32(buckets_info_[i].uncompressed_length)) return false; if (!writer.writeUInt16(buckets_info_[i].crc)) return false; } return true; } bool LeafNode::load_bucket(size_t idx) { assert(status_ != kFullLoaded); assert(idx < buckets_info_.size()); assert(records_.bucket(idx) == NULL); uint32_t offset = buckets_info_[idx].offset; uint32_t length = buckets_info_[idx].length; uint32_t uncompressed_length = buckets_info_[idx].uncompressed_length; Block* block = tree_->layout_->read(nid_, offset, length); if (block == NULL) { LOG_ERROR("read bucket error " << " nid " << nid_ << ", idx " << idx << ", offset " << offset << ", length " << length); return false; } // do bucket crc checking uint16_t expected_crc = buckets_info_[idx].crc; uint16_t actual_crc = crc16(block->start(), length); if (expected_crc != actual_crc) { LOG_ERROR("bucket crc checking error " << " nid " << nid_ << ", idx " << idx << ", offset " << offset << ", length " << length << ", expected_crc " << expected_crc << " ,actual_crc " << actual_crc); tree_->layout_->destroy(block); return false; } BlockReader reader(block); RecordBucket *bucket = new RecordBucket(); if (bucket == NULL) { tree_->layout_->destroy(block); return false; } Slice buffer; if (tree_->compressor_) { buffer = Slice::alloc(uncompressed_length); } if (!read_bucket(reader, length, uncompressed_length, bucket, buffer)) { if (buffer.size()) { buffer.destroy(); } delete bucket; tree_->layout_->destroy(block); return false; } if (buffer.size()) { buffer.destroy(); } // this operation must be inside read lock // lazy load, upgrade lock to write lock // TODO: write a upgradable rwlock unlock(); write_lock(); if (records_.bucket(idx) == NULL) { records_.set_bucket(idx, bucket); } else { // it's possible another read thread loading // the same block at the same time delete bucket; } unlock(); read_lock(); tree_->layout_->destroy(block); return true; } bool LeafNode::load_all_buckets() { // skeleton has already been loaded assert(status_ == kSkeletonLoaded); Block* block = tree_->layout_->read(nid_, false); if (block == NULL) { LOG_ERROR("read node error " << " nid " << nid_); return false; } // this operation must be inside write lock BlockReader reader(block); if (!load_all_buckets(reader)) { tree_->layout_->destroy(block); return false; } tree_->layout_->destroy(block); return true; } bool LeafNode::load_all_buckets(BlockReader& reader) { Slice buffer; if (tree_->compressor_) { size_t buffer_length = 0; for (size_t i = 0; i < buckets_info_.size(); i++ ) { if (buffer_length < buckets_info_[i].uncompressed_length) { buffer_length = buckets_info_[i].uncompressed_length; } } buffer = Slice::alloc(buffer_length); } bool ret = true; for (size_t i = 0; i < buckets_info_.size(); i++) { reader.seek(buckets_info_[i].offset); RecordBucket *bucket = new RecordBucket(); if (bucket == NULL) { ret = false; break; } if (!read_bucket(reader, buckets_info_[i].length, buckets_info_[i].uncompressed_length, bucket, buffer)) { ret = false; delete bucket; break; } records_.set_bucket(i, bucket); } if (buffer.size()) { buffer.destroy(); } status_ = kFullLoaded; return ret; } bool LeafNode::read_bucket(BlockReader& reader, size_t compressed_length, size_t uncompressed_length, RecordBucket *bucket, Slice buffer) { if (tree_->compressor_) { // 1. uncompress assert(compressed_length <= reader.remain()); assert(uncompressed_length <= buffer.size()); // 1. uncompress if (!tree_->compressor_->uncompress(reader.addr(), compressed_length, (char *)buffer.data())) { return false; } reader.skip(compressed_length); // 2. deserialize Block block(buffer, 0, uncompressed_length); BlockReader rr(&block); return read_bucket(rr, bucket); } else { return read_bucket(reader, bucket); } } bool LeafNode::read_bucket(BlockReader& reader, RecordBucket *bucket) { uint32_t nrecords; if (!reader.readUInt32(&nrecords)) return false; bucket->resize(nrecords); for (size_t i = 0; i < nrecords; i++) { if (!(*bucket)[i].read_from(reader)) { return false; } } return true; }
27.313761
91
0.563169
[ "vector" ]
0e313e30162ea262f59605c2907edd3ab77548ef
3,908
hpp
C++
sfq/src/crates/lzt/src/ffi/lzt_core/vizualization/NodeArrayToDot.hpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
sfq/src/crates/lzt/src/ffi/lzt_core/vizualization/NodeArrayToDot.hpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
sfq/src/crates/lzt/src/ffi/lzt_core/vizualization/NodeArrayToDot.hpp
lisp-rbi/sfq
93855f63e15561ea36644fa6bcf7d72266974f4d
[ "Apache-2.0" ]
null
null
null
#ifndef NODEARRAYTODOT_HPP #define NODEARRAYTODOT_HPP #include <string> #include <fstream> #include <cstdio> #include <cctype> #include <map> using namespace std; /** Class for writing a node array to GraphViz's dot file, for visualization. */ template <typename TNodeArray> class NodeArrayToDot { private: typedef typename TNodeArray::Symbol TSymbol; typedef typename TNodeArray::Index TIndex; typedef typename TNodeArray::Node TNode; public: NodeArrayToDot(TNodeArray* arr): array(arr) {}; void write(string file); private: void writeBeginning(); void writeEnd(); void writeTree(TIndex i); TIndex resolvePointer(TIndex i); // filter out all non-aphanumeric symbols char processSymbol(char c) { if (isalpha(c)) return c; else return 'x'; } string intToStr(int); TNodeArray* array; fstream file; long nodeCounter; map<TIndex, string> posToNode; }; template <typename TNodeArray> void NodeArrayToDot<TNodeArray>::write(string fname) { file.open(fname.c_str(), ios_base::out); writeBeginning(); posToNode.clear(); nodeCounter = 0; writeTree(0); writeEnd(); file.close(); } /** Write a subtree with a first edge at index i in the array. */ template <typename TNodeArray> void NodeArrayToDot<TNodeArray>::writeTree(TIndex i) { long nodeIndex = nodeCounter; // current node label string node = "N"; node += intToStr(nodeCounter); while (true) { posToNode[i] = node; // next node label string next = "N"; next += intToStr(nodeCounter+1); // TIndex res = resolvePointer(i); TIndex sib = (*array)[res].getSibling(); bool pointer = (*array)[i].isPointer(); TSymbol symbol; if (pointer) symbol = '_'; else symbol = processSymbol((*array)[i].getSymbol()); // draw edge to next node file << node << " -> " << next << " [label=" << symbol << "];" << endl; // draw pointer edge if (pointer) { string targetNode; if (posToNode.count((*array)[i].getSibling()) == 0) targetNode = node; else targetNode = posToNode[(*array)[i].getSibling()]; //cout << (*array)[i].getSibling() << endl; file << node << " -> " << targetNode << "[constraint=false,color=red]"<< endl; } // nodeCounter++; // continue recursively if there are edges (nodes) at deeper levels if (pointer) { TIndex offset = (*array)[i].getSymbol(); TIndex next = (i + offset + 1); if ((*array)[i+offset].getCow()) writeTree(next); // if (sib) { // if (next < i + sib) writeTree(next); // } // else { // // } } else { if ((*array)[i].getCow()) writeTree(i+1); } if (sib != 0) i += sib; else break; } } /** Recursively resolve pointers. */ template <typename TNodeArray> typename TNodeArray::Index NodeArrayToDot<TNodeArray>::resolvePointer(TIndex i) { while((*array)[i].isPointer()) i = (*array)[i].getSibling(); return i; } template <typename TNodeArray> string NodeArrayToDot<TNodeArray>::intToStr(int i) { char number[20]; sprintf(number,"%d",i); return number; } template <typename TNodeArray> void NodeArrayToDot<TNodeArray>::writeBeginning() { file << "digraph DFA { " << endl << "splines=false;" << endl << "bgcolor=\"white\";" << endl << "rankdir=LR;" << endl << "node [shape=circle, width=0.4, label=\"\", style=filled, color=\"black\"];" << endl << "edge [arrowsize = 0.2, penwidth=3];" << endl; } template <typename TNodeArray> void NodeArrayToDot<TNodeArray>::writeEnd() { file << "}" << endl; } #endif /* NODEARRAYTODOT_HPP */
26.053333
96
0.581372
[ "shape" ]
0e34ee3e4ea82feae13e483a4a7d407ae44fbba3
12,453
cc
C++
onnxruntime/core/optimizer/qdq_transformer/qdq_propagation.cc
kota-row/onnxruntime
eb116595d4c4b28eedc009eae98e2bba777e0a1b
[ "MIT" ]
null
null
null
onnxruntime/core/optimizer/qdq_transformer/qdq_propagation.cc
kota-row/onnxruntime
eb116595d4c4b28eedc009eae98e2bba777e0a1b
[ "MIT" ]
null
null
null
onnxruntime/core/optimizer/qdq_transformer/qdq_propagation.cc
kota-row/onnxruntime
eb116595d4c4b28eedc009eae98e2bba777e0a1b
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/optimizer/qdq_transformer/qdq_propagation.h" #include <optional> #include "core/graph/extended_graph_edge.h" #include "core/graph/graph_utils.h" #include "core/optimizer/initializer.h" #include "core/optimizer/qdq_transformer/qdq_util.h" #include "core/optimizer/utils.h" using onnxruntime::graph_utils::ExtendedGraphEdge; namespace onnxruntime { namespace { bool CanNodePropagate(const Node& node) { return graph_utils::IsSupportedOptypeVersionAndDomain(node, "MaxPool", {12}) || graph_utils::IsSupportedOptypeVersionAndDomain(node, "Reshape", {5, 13, 14}) || graph_utils::IsSupportedOptypeVersionAndDomain(node, "Transpose", {1, 13}); } // convert this: src_node -> dst_node // to this: src_node -> Q -> DQ -> dst_node // assumptions: // 1. insertion_edge is valid - node indexes refer to valid nodes, arg name refers to a valid NodeArg, and it // corresponds to an actual graph relationship // 2. scale_initializer_nodearg and zp_initializer_nodearg_ptr (if not null) are constant initializers Status InsertQDQPair(Graph& graph, const ExtendedGraphEdge& insertion_edge, NodeArg& scale_initializer_nodearg, NodeArg* zp_initializer_nodearg_ptr, const logging::Logger& logger) { auto* src_node = insertion_edge.GetMutableNodeAtEnd(graph, ExtendedGraphEdge::End::Source); auto* dst_node = insertion_edge.GetMutableNodeAtEnd(graph, ExtendedGraphEdge::End::Destination); ORT_ENFORCE(src_node || dst_node, "At least one graph node must be specified in the propagation edge."); const auto& base_name = insertion_edge.arg_name; auto& base_node_arg = *graph.GetNodeArg(base_name); LOGS(logger, VERBOSE) << "Inserting Q/DQ pair between " << (src_node ? MakeString("node (\"", src_node->Name(), "\", index: ", src_node->Index(), ")") : "input") << " and " << (dst_node ? MakeString("node (\"", dst_node->Name(), "\", index: ", dst_node->Index(), ")") : "output") << " at NodeArg \"" << base_name << "\"."; // set up new NodeArgs auto& pre_q_nodearg = insertion_edge.HasGraphInputOrInitializer() ? base_node_arg : graph.GetOrCreateNodeArg(graph.GenerateNodeArgName(base_name + "_pre_q"), nullptr); auto& q_to_dq_nodearg = graph.GetOrCreateNodeArg(graph.GenerateNodeArgName(base_name + "_q_to_dq"), nullptr); auto& post_dq_nodearg = insertion_edge.HasGraphOutput() ? base_node_arg : graph.GetOrCreateNodeArg(graph.GenerateNodeArgName(base_name + "_post_dq"), nullptr); // set up new Nodes auto make_q_or_dq_inputs = [](NodeArg& data, NodeArg& scale, NodeArg* zero_point) { return zero_point ? std::vector<NodeArg*>{&data, &scale, zero_point} : std::vector<NodeArg*>{&data, &scale}; }; auto& q_node = graph.AddNode(graph.GenerateNodeName(base_name + "_q"), QDQ::QOpName, "Inserted by QDQPropagationTransformer", // inputs make_q_or_dq_inputs(pre_q_nodearg, scale_initializer_nodearg, zp_initializer_nodearg_ptr), // outputs {&q_to_dq_nodearg}); ORT_RETURN_IF_NOT(graph.SetOpSchemaFromRegistryForNode(q_node), "Failed to set op schema for added Q node."); auto& dq_node = graph.AddNode(graph.GenerateNodeName(base_name + "_dq"), QDQ::DQOpName, "Inserted by QDQPropagationTransformer", // inputs make_q_or_dq_inputs(q_to_dq_nodearg, scale_initializer_nodearg, zp_initializer_nodearg_ptr), // outputs {&post_dq_nodearg}); ORT_RETURN_IF_NOT(graph.SetOpSchemaFromRegistryForNode(dq_node), "Failed to set op schema for added DQ node."); // set up edges if (src_node && dst_node) { graph.RemoveEdge(src_node->Index(), dst_node->Index(), insertion_edge.src->arg_idx, insertion_edge.dst->arg_idx); } if (src_node) { src_node->MutableOutputDefs()[insertion_edge.src->arg_idx] = &pre_q_nodearg; graph.AddEdge(src_node->Index(), q_node.Index(), insertion_edge.src->arg_idx, 0); } graph.AddEdge(q_node.Index(), dq_node.Index(), 0, 0); if (dst_node) { dst_node->MutableInputDefs()[insertion_edge.dst->arg_idx] = &post_dq_nodearg; graph.AddEdge(dq_node.Index(), dst_node->Index(), 0, insertion_edge.dst->arg_idx); } return Status::OK(); } std::optional<ExtendedGraphEdge> GetPreviousEdge(const Graph& graph, const Node& node) { // for now we can just consider the first input (index 0) const auto input_edges = graph_utils::GraphEdge::GetNodeInputEdges(node); const auto input_edge_it = std::find_if( input_edges.begin(), input_edges.end(), [](const graph_utils::GraphEdge& edge) { return edge.dst_arg_index == 0; }); if (input_edge_it == input_edges.end()) { // maybe edge from input return ExtendedGraphEdge::TryCreateFromInputOrInitializerToNode(graph, node, 0); } const auto& src_node = *graph.GetNode(input_edge_it->src_node); const auto src_node_output_edges = graph_utils::GraphEdge::GetNodeOutputEdges(src_node, input_edge_it->src_arg_index); if (!graph.IsOutput(src_node.OutputDefs()[input_edge_it->src_arg_index]) && src_node_output_edges.size() == 1) { // single edge from previous node return ExtendedGraphEdge::CreateFromValidGraphEdge(*input_edge_it); } return std::nullopt; } std::optional<ExtendedGraphEdge> GetPreviousPropagationEdge(const Graph& graph, const ExtendedGraphEdge& edge) { if (edge.HasGraphInputOrInitializer()) { return std::nullopt; } const auto* src_node = edge.GetNodeAtEnd(graph, ExtendedGraphEdge::End::Source); ORT_ENFORCE(src_node != nullptr); if (!CanNodePropagate(*src_node)) { return std::nullopt; } return GetPreviousEdge(graph, *src_node); } std::optional<ExtendedGraphEdge> GetNextEdge(const Graph& graph, const Node& node) { // for now we can just consider the first output (index 0) const auto output_edges = graph_utils::GraphEdge::GetNodeOutputEdges(node, 0); if (output_edges.empty()) { // maybe edge to output return ExtendedGraphEdge::TryCreateFromNodeToOutput(graph, node, 0); } if (!graph.IsOutput(node.OutputDefs()[0]) && output_edges.size() == 1) { // single edge to next node return ExtendedGraphEdge::CreateFromValidGraphEdge(output_edges.front()); } return std::nullopt; } std::optional<ExtendedGraphEdge> GetNextPropagationEdge(const Graph& graph, const ExtendedGraphEdge& edge) { if (edge.HasGraphOutput()) { return std::nullopt; } const auto* dst_node = edge.GetNodeAtEnd(graph, ExtendedGraphEdge::End::Destination); ORT_ENFORCE(dst_node != nullptr); if (!CanNodePropagate(*dst_node)) { return std::nullopt; } return GetNextEdge(graph, *dst_node); } class GraphConstantInitializerGetter { const Graph& graph_; public: GraphConstantInitializerGetter(const Graph& graph) : graph_{graph} {} const ONNX_NAMESPACE::TensorProto* operator()(const std::string& initializer_name) const { return graph_utils::GetConstantInitializer(graph_, initializer_name); } }; Status PropagateDQForward(Graph& graph, gsl::span<const NodeIndex> node_indices, const InlinedHashSet<std::string_view>& compatible_eps, const logging::Logger& logger, bool& modified) { for (auto node_index : node_indices) { auto* dq_node_ptr = graph.GetNode(node_index); if (dq_node_ptr == nullptr) { continue; // node removed as part of an earlier fusion } Node& dq_node = *dq_node_ptr; if (!QDQ::MatchDQNode(dq_node) || !graph_utils::IsSupportedProvider(dq_node, compatible_eps) || !optimizer_utils::CheckOutputEdges(graph, dq_node, 1)) { continue; } bool dq_zero_point_exists = false; if (!QDQ::QOrDQNodeHasConstantScalarScaleAndZeroPoint(dq_node, GraphConstantInitializerGetter{graph}, dq_zero_point_exists)) { continue; } auto& dq_scale = *dq_node.MutableInputDefs()[QDQ::InputIndex::SCALE_ID]; auto* dq_zero_point = dq_zero_point_exists ? dq_node.MutableInputDefs()[QDQ::InputIndex::ZERO_POINT_ID] : nullptr; const auto edge_after_dq = GetNextEdge(graph, dq_node); if (!edge_after_dq) { continue; } for (auto curr_edge = GetNextPropagationEdge(graph, *edge_after_dq); curr_edge.has_value(); curr_edge = GetNextPropagationEdge(graph, *curr_edge)) { if (const auto* dst_node = curr_edge->GetNodeAtEnd(graph, ExtendedGraphEdge::End::Destination); dst_node && QDQ::MatchQNode(*dst_node)) { break; } ORT_RETURN_IF_ERROR(InsertQDQPair(graph, *curr_edge, dq_scale, dq_zero_point, logger)); modified = true; } } return Status::OK(); } Status PropagateQBackward(Graph& graph, gsl::span<const NodeIndex> node_indices, const InlinedHashSet<std::string_view>& compatible_eps, const logging::Logger& logger, bool& modified) { for (auto node_index : node_indices) { auto* q_node_ptr = graph.GetNode(node_index); if (q_node_ptr == nullptr) { continue; // node removed as part of an earlier fusion } Node& q_node = *q_node_ptr; if (!QDQ::MatchQNode(q_node) || !graph_utils::IsSupportedProvider(q_node, compatible_eps)) { continue; } bool q_zero_point_exists = false; if (!QDQ::QOrDQNodeHasConstantScalarScaleAndZeroPoint(q_node, GraphConstantInitializerGetter{graph}, q_zero_point_exists)) { continue; } auto& q_scale = *q_node.MutableInputDefs()[QDQ::InputIndex::SCALE_ID]; auto* q_zero_point = q_zero_point_exists ? q_node.MutableInputDefs()[QDQ::InputIndex::ZERO_POINT_ID] : nullptr; const auto edge_before_q = GetPreviousEdge(graph, q_node); if (!edge_before_q) { continue; } for (auto curr_edge = GetPreviousPropagationEdge(graph, *edge_before_q); curr_edge.has_value(); curr_edge = GetPreviousPropagationEdge(graph, *curr_edge)) { if (auto* src_node = curr_edge->GetNodeAtEnd(graph, ExtendedGraphEdge::End::Source); src_node && QDQ::MatchDQNode(*src_node)) { break; } ORT_RETURN_IF_ERROR(InsertQDQPair(graph, *curr_edge, q_scale, q_zero_point, logger)); modified = true; } } return Status::OK(); } } // namespace Status QDQPropagationTransformer::ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const { GraphViewer graph_viewer(graph); const auto node_indices = gsl::make_span(graph_viewer.GetNodesInTopologicalOrder()); for (auto node_index : node_indices) { auto* node_ptr = graph.GetNode(node_index); if (node_ptr == nullptr) continue; // node removed as part of an earlier fusion ORT_RETURN_IF_ERROR(Recurse(*node_ptr, modified, graph_level, logger)); } const auto& compatible_eps = GetCompatibleExecutionProviders(); ORT_RETURN_IF_ERROR(PropagateQBackward(graph, node_indices, compatible_eps, logger, modified)); ORT_RETURN_IF_ERROR(PropagateDQForward(graph, node_indices, compatible_eps, logger, modified)); return Status::OK(); } } // namespace onnxruntime
39.283912
118
0.635831
[ "vector" ]
0e3b7ad316391d9a5f5dfa493269f7fe2e84062e
924
cpp
C++
Vector4.cpp
SungJJinKang/JINMATH
0c96719d061de63eac4421b0b8d91d316e2d20c1
[ "MIT" ]
null
null
null
Vector4.cpp
SungJJinKang/JINMATH
0c96719d061de63eac4421b0b8d91d316e2d20c1
[ "MIT" ]
null
null
null
Vector4.cpp
SungJJinKang/JINMATH
0c96719d061de63eac4421b0b8d91d316e2d20c1
[ "MIT" ]
null
null
null
#include "Vector4.h" #include "Vector2.h" #include "Vector3.h" const math::Vector4 math::Vector4::forward{0.0f, 0.0f, -1.0f, 0.0f}; const math::Vector4 math::Vector4::right{ 1.0f, 0.0f, 0.0f, 0.0f }; const math::Vector4 math::Vector4::up{ 0.0f, 1.0f, 0.0f, 0.0f }; const math::Vector4 math::Vector4::zero{ 0.0f, 0.0f, 0.0f, 0.0f }; const math::Vector4 math::Vector4::one{ 1.0f, 1.0f, 1.0f, 1.0f }; math::Vector4::Vector4(const Vector2& vector) noexcept: x{ vector.x }, y{ vector.y }, z{ 0 }, w{ 0 } { } math::Vector4::Vector4(const Vector3& vector, float w) noexcept: x{ vector.x }, y{ vector.y }, z{ vector.z }, w{ w } { } math::Vector4::type& math::Vector4::operator=(const Vector2& vector) noexcept { x = vector.x; y = vector.y; z = 0; w = 0; return *this; } math::Vector4::type& math::Vector4::operator=(const Vector3& vector) noexcept { x = vector.x; y = vector.y; z = vector.z; w = 0; return *this; }
24.315789
116
0.635281
[ "vector" ]
0e3bdccf20ea4f987ba1f578bfc1cfaebecf6d58
372
cpp
C++
c++/hw-thread/main.cpp
OGLinuk/ptp
bf498759d9958e4fbf4bda30e2b069efa6b7ff5c
[ "Apache-2.0" ]
1
2022-01-31T04:55:59.000Z
2022-01-31T04:55:59.000Z
c++/hw-thread/main.cpp
oglinuk/labs
619f25238cd1631ee3446cb91e46e2376bea6dba
[ "Apache-2.0" ]
null
null
null
c++/hw-thread/main.cpp
oglinuk/labs
619f25238cd1631ee3446cb91e46e2376bea6dba
[ "Apache-2.0" ]
1
2018-10-05T01:54:12.000Z
2018-10-05T01:54:12.000Z
#include <iostream> #include <thread> #include <vector> void printSomething(int i) { printf("Hello world from C++ concurrency number %d\n\n", i); } int main() { std::vector<std::thread> t; for (int i = 0; i < 7; i++) { t.push_back(std::thread(printSomething, i)); } for (int i = 0; i < 7; i++) { t[i].join(); } return 0; }
16.173913
65
0.537634
[ "vector" ]
0e412e0a724cb1a55c7aeabd1e5d4f7753cd3a74
3,524
cpp
C++
camps/winter_school_Kremenchuk_2016/DAY_4_SQRT_DECOMPOSITION/D_right.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
camps/winter_school_Kremenchuk_2016/DAY_4_SQRT_DECOMPOSITION/D_right.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
camps/winter_school_Kremenchuk_2016/DAY_4_SQRT_DECOMPOSITION/D_right.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> using namespace std; const int SQRT = 316; struct Orbit { vector<int> answers; vector<int> whatWant; vector<pair<pair<int,int>, long long> > queries; vector<vector<int> > owners; vector<int> sectors; vector<long long> currSumOnOwners; int n, m, q; Orbit(istream & in) { in >> n >> m; answers.assign(n,-1); whatWant.assign(n,0); sectors.assign(m,0); owners.assign(n,vector<int>(0,0)); for(int i = 0; i<m; i++) { in >> sectors[i]; owners[--sectors[i]].push_back(i); } for(auto & i : whatWant) in >> i; for(auto & i : owners) sort(i.begin(), i.end()); in >> q; for(int i = 0; i<q; i++) { int l, r, c; cin >> l >> r >> c; l--; r--; queries.push_back({{l,r},c}); } } int getCountOnSegment(int owner, int l, int r) { if(l>r) return getCountOnSegment(owner, 0, r) + getCountOnSegment(owner, l, m-1); return upper_bound(owners[owner].begin(), owners[owner].end(), r) - lower_bound(owners[owner].begin(), owners[owner].end(), l); } int getShortAns(int owner, int lastQ) { while(currSumOnOwners[owner]>=whatWant[owner]) { currSumOnOwners[owner]-=queries[lastQ].second * getCountOnSegment(owner, queries[lastQ].first.first, queries[lastQ].first.second); lastQ--; } return lastQ + 2; } vector<int> & getAnswer() { vector<long long> additionals(m+1, 0); currSumOnOwners.assign(n,0); for(int _i = 0; _i<(int)queries.size(); _i++) { if(queries[_i].first.first <= queries[_i].first.second) { additionals[queries[_i].first.first] += queries[_i].second; additionals[queries[_i].first.second+1] -= queries[_i].second; } else { additionals[0] +=queries[_i].second; additionals[queries[_i].first.second + 1]-=queries[_i].second; additionals[queries[_i].first.first] +=queries[_i].second; additionals[m] -=queries[_i].second; } if((_i+1)%SQRT == 0 || _i==(int)queries.size()-1) { long long currAdd = 0; for(int i = 0; i<m; i++) { currAdd+=additionals[i]; currSumOnOwners[sectors[i]]+=currAdd; } additionals.assign(m+1, 0); for(int i = 0; i<n; i++) if(answers[i]==-1 && currSumOnOwners[i]>=whatWant[i]) { answers[i] = getShortAns(i, _i); } } } return answers; } }; ostream & operator << (ostream & outStream, const vector<int> & toWrite) { for(auto i : toWrite) outStream << i << '\n'; return outStream; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); Orbit orbit(cin); cout << orbit.getAnswer(); return 0; }
27.748031
114
0.450341
[ "vector" ]
0e4afead70ebf54ab1a80c285d4e96aacf6d86d7
18,121
hpp
C++
lib/decorators/EventPropertiesDecorator.hpp
sulahane/cpp_client_telemetry
759412c158d88ae8de8a64cf7b756ca24fd0a3e6
[ "Apache-2.0" ]
null
null
null
lib/decorators/EventPropertiesDecorator.hpp
sulahane/cpp_client_telemetry
759412c158d88ae8de8a64cf7b756ca24fd0a3e6
[ "Apache-2.0" ]
null
null
null
lib/decorators/EventPropertiesDecorator.hpp
sulahane/cpp_client_telemetry
759412c158d88ae8de8a64cf7b756ca24fd0a3e6
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // #ifndef EVENTPROPERTIESDECORATOR_HPP #define EVENTPROPERTIESDECORATOR_HPP #include "IDecorator.hpp" #include "EventProperties.hpp" #include "CorrelationVector.hpp" #include "utils/Utils.hpp" #include <algorithm> #include <map> #include <string> namespace MAT_NS_BEGIN { // Bit remapping has to happen on bits passed via API surface. // Ref CS2.1+ : https://osgwiki.com/wiki/CommonSchema/flags // #define MICROSOFT_EVENTTAG_MARK_PII 0x08000000 #define RECORD_FLAGS_EVENTTAG_MARK_PII 0x00080000 // #define MICROSOFT_EVENTTAG_HASH_PII 0x04000000 #define RECORD_FLAGS_EVENTTAG_HASH_PII 0x00100000 // #define MICROSOFT_EVENTTAG_DROP_PII 0x02000000 #define RECORD_FLAGS_EVENTTAG_DROP_PII 0x00200000 class EventPropertiesDecorator : public IDecorator { protected: std::string randomLocalId; ILogManager& m_owner; bool decorate(::CsProtocol::Record&) override { return false; } public: EventPropertiesDecorator(ILogManager& owner) : m_owner(owner) { // // Random local deviceId must be used for events tagged with Pii DROP EventTag. // Since we generate a new random id for every SDK session - products tagging // their telemetry events with Pii DROP tag cannot use ext.device.localId field // in Kusto for DAU/MAU user engagement metrics. // // It would have been more logical to adjust the Pii flags spec to require all // devices running with Pii DROP flag to the same identical bogus {deadbeef-...} // id. That would have allowed the apps to continue using ext.device.localId for // engagement metrics, estimating their population size using that field. // randomLocalId = "r:"; randomLocalId+= PAL::generateUuidString(); }; void dropPiiPartA(::CsProtocol::Record& record) { // MICROSOFT_EVENTTAG_DROP_PII tag functionality reference: // https://osgwiki.com/wiki/Telemetry#De-Identification_of_Telemetry_Events // // Drop Pii EventTag scrubs Part A Pii data client-side. // The flag has no effect on Part C Pii data. // // clear tickets because these provide a way to identify the end-user record.extProtocol[0].ticketKeys.clear(); // clean Pii from Device extension record.extDevice[0].localId = randomLocalId; record.extDevice[0].authId.clear(); record.extDevice[0].authSecId.clear(); record.extDevice[0].id.clear(); // clean Pii from User extension record.extUser[0].localId.clear(); record.extUser[0].authId.clear(); record.extUser[0].id.clear(); // clean epoch and seq + installId record.extSdk[0].seq = 0; record.extSdk[0].epoch.clear(); record.extSdk[0].installId.clear(); // clear correlation vector record.cV = ""; } bool decorate(::CsProtocol::Record& record, EventLatency& latency, EventProperties const& eventProperties) { if (latency == EventLatency_Unspecified) latency = EventLatency_Normal; if (eventProperties.GetName().empty()) { // OK, using some default set by earlier decorator. } else { EventRejectedReason isValidEventName = validateEventName(eventProperties.GetName()); if (isValidEventName != REJECTED_REASON_OK) { LOG_ERROR("Invalid event properties!"); DebugEvent evt; evt.type = DebugEventType::EVT_REJECTED; evt.param1 = isValidEventName; m_owner.DispatchEvent(evt); return false; } } if (record.data.size() == 0) { ::CsProtocol::Data data; record.data.push_back(data); } //auto timestamp = eventProperties.GetTimestamp(); //if (timestamp != 0) // record.time = timestamp; record.popSample = eventProperties.GetPopSample(); // API surface tags('flags') are different from on-wire record.flags int64_t tags = eventProperties.GetPolicyBitFlags(); int64_t flags = 0; // We must remap from one bitfield set to another, no way to bit-shift :( // At the moment 1DS SDK in direct upload mode supports DROP and MARK tags only: flags |= (tags & MICROSOFT_EVENTTAG_MARK_PII) ? RECORD_FLAGS_EVENTTAG_MARK_PII : 0; flags |= (tags & MICROSOFT_EVENTTAG_DROP_PII) ? RECORD_FLAGS_EVENTTAG_DROP_PII : 0; // Caller asked to drop Pii from Part A of that event bool tagDropPii = bool(tags & MICROSOFT_EVENTTAG_DROP_PII); if (EventPersistence_Critical == eventProperties.GetPersistence()) { flags = flags | 0x02; } else { flags = flags | 0x01; } if (latency >= EventLatency_RealTime) { flags = flags | 0x0200; } else if (latency == EventLatency_CostDeferred) { flags = flags | 0x0300; } else { flags = flags | 0x0100; } record.flags = flags; std::map<std::string, ::CsProtocol::Value>& ext = record.data[0].properties; std::map<std::string, ::CsProtocol::Value> extPartB; for (auto &kv : eventProperties.GetProperties()) { EventRejectedReason isValidPropertyName = validatePropertyName(kv.first); if (isValidPropertyName != REJECTED_REASON_OK) { DebugEvent evt; evt.type = DebugEventType::EVT_REJECTED; evt.param1 = isValidPropertyName; m_owner.DispatchEvent(evt); return false; } const auto &k = kv.first; const auto &v = kv.second; if (v.piiKind != PiiKind_None) { if (v.piiKind == PiiKind::CustomerContentKind_GenericData) { //LOG_TRACE("PIIExtensions: %s=%s (PiiKind=%u)", k.c_str(), v.to_string().c_str(), v.piiKind); CsProtocol::CustomerContent cc; cc.Kind = CsProtocol::CustomerContentKind::GenericContent; CsProtocol::Value temp; CsProtocol::Attributes attrib; attrib.customerContent.push_back(cc); temp.attributes.push_back(attrib); temp.stringValue = v.to_string(); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } } else { //LOG_TRACE("PIIExtensions: %s=%s (PiiKind=%u)", k.c_str(), v.to_string().c_str(), v.piiKind); CsProtocol::PII pii; pii.Kind = static_cast<CsProtocol::PIIKind>(v.piiKind); CsProtocol::Value temp; CsProtocol::Attributes attrib; attrib.pii.push_back(pii); temp.attributes.push_back(attrib); temp.stringValue = v.to_string(); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } #if 0 /* v2 code */ if (v.piiKind != PiiKind_None) { //LOG_TRACE("PIIExtensions: %s=%s (PiiKind=%u)", k.c_str(), v.to_string().c_str(), v.piiKind); CsProtocol::PII pii; pii.Kind = static_cast<CsProtocol::PIIKind>(v.piiKind); pii.RawContent = v.to_string(); // ScrubType = 1 is the O365 scrubber which is the default behavior. // pii.ScrubType = static_cast<PIIScrubber>(O365); pii.ScrubType = CsProtocol::O365; PIIExtensions[k] = pii; // 4. Send event's Pii context fields as record.PIIExtensions } else { //LOG_TRACE("PIIExtensions: %s=%s (PiiKind=%u)", k.c_str(), v.to_string().c_str(), v.piiKind); CsProtocol::CustomerContent cc; cc.Kind = static_cast<CsProtocol::CustomerContentKind>(v.ccKind); cc.RawContent = v.to_string(); ccExtensions[k] = cc; // 4. Send event's Pii context fields as record.PIIExtensions #endif } } else { std::vector<uint8_t> guid; uint8_t guid_bytes[16] = { 0 }; switch (v.type) { case EventProperty::TYPE_STRING: { CsProtocol::Value temp; temp.stringValue = v.to_string(); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_INT64: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueInt64; temp.longValue = v.as_int64; if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_DOUBLE: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueDouble; temp.doubleValue = v.as_double; if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_TIME: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueDateTime; temp.longValue = v.as_time_ticks.ticks; if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_BOOLEAN: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueBool; temp.longValue = v.as_bool; if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_GUID: { GUID_t temp = v.as_guid; temp.to_bytes(guid_bytes); guid = std::vector<uint8_t>(guid_bytes, guid_bytes + sizeof(guid_bytes) / sizeof(guid_bytes[0])); CsProtocol::Value tempValue; tempValue.type = ::CsProtocol::ValueKind::ValueGuid; tempValue.guidValue.push_back(guid); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = tempValue; } else { ext[k] = tempValue; } break; } case EventProperty::TYPE_INT64_ARRAY: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueArrayInt64; temp.longArray.push_back(*v.as_longArray); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_DOUBLE_ARRAY: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueArrayDouble; temp.doubleArray.push_back(*v.as_doubleArray); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_STRING_ARRAY: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueArrayString; temp.stringArray.push_back(*v.as_stringArray); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } case EventProperty::TYPE_GUID_ARRAY: { CsProtocol::Value temp; temp.type = ::CsProtocol::ValueKind::ValueArrayGuid; std::vector<std::vector<uint8_t>> values; for (const auto& tempValue : *v.as_guidArray) { tempValue.to_bytes(guid_bytes); guid = std::vector<uint8_t>(guid_bytes, guid_bytes + sizeof(guid_bytes) / sizeof(guid_bytes[0])); values.push_back(guid); } temp.guidArray.push_back(values); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } break; } default: { // Convert all unknown types to string CsProtocol::Value temp; temp.stringValue = v.to_string(); if (v.dataCategory == DataCategory_PartB) { extPartB[k] = temp; } else { ext[k] = temp; } } } } } if (extPartB.size() > 0) { ::CsProtocol::Data partBdata; partBdata.properties = extPartB; record.baseData.push_back(partBdata); } // special case of CorrelationVector value if (ext.count(CorrelationVector::PropertyName) > 0) { CsProtocol::Value cvValue = ext[CorrelationVector::PropertyName]; if (cvValue.type == ::CsProtocol::ValueKind::ValueString) { record.cV = cvValue.stringValue; } else { LOG_TRACE("CorrelationVector value type is invalid %u", cvValue.type); } ext.erase(CorrelationVector::PropertyName); } // scrub if MICROSOFT_EVENTTAG_DROP_PII is set if (tagDropPii) { dropPiiPartA(record); } return true; } }; } MAT_NS_END #endif
39.138229
125
0.429612
[ "vector" ]
0e5025a17a453c4ec53297008323aad93ea74cdb
6,910
cc
C++
src/filesystem_testing.cc
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
null
null
null
src/filesystem_testing.cc
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
12
2021-02-24T22:48:56.000Z
2021-03-21T12:33:05.000Z
src/filesystem_testing.cc
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Karl Wiberg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "filesystem_testing.hh" #include <absl/random/random.h> #include <filesystem> #include <fstream> #include <ostream> #include <sstream> #include "base32.hh" namespace frz { namespace { constexpr std::string_view DescribeFileType(std::filesystem::file_type type) { switch (type) { case std::filesystem::file_type::regular: return "regular file"; case std::filesystem::file_type::directory: return "directory"; case std::filesystem::file_type::symlink: return "symlink"; case std::filesystem::file_type::block: return "block device"; case std::filesystem::file_type::character: return "character device"; case std::filesystem::file_type::fifo: return "fifo"; case std::filesystem::file_type::socket: return "socket"; case std::filesystem::file_type::not_found: return "doesn't exist"; default: return "unknown type of filesystem object"; }; } class FileTypeMatcher final { public: using is_gtest_matcher = void; FileTypeMatcher(std::filesystem::file_type expected_type) : expected_type_(expected_type) {} bool MatchAndExplain(const std::filesystem::path& path, std::ostream* out) const { auto type = std::filesystem::symlink_status(path).type(); if (type == expected_type_) { return true; } else { if (out != nullptr) { *out << DescribeFileType(type); } return false; } } void DescribeTo(std::ostream* out) const { Desc("is", out); } void DescribeNegationTo(std::ostream* out) const { Desc("is not", out); } private: void Desc(std::string_view prefix, std::ostream* out) const { *out << prefix << " a " << DescribeFileType(expected_type_); } std::filesystem::file_type expected_type_; }; class SymlinkMatcher final { public: using is_gtest_matcher = void; SymlinkMatcher(testing::Matcher<std::filesystem::path> target_matcher) : target_matcher_(std::move(target_matcher)) {} bool MatchAndExplain(const std::filesystem::path& path, std::ostream* out) const { if (auto type = std::filesystem::symlink_status(path).type(); type != std::filesystem::file_type::symlink) { if (out != nullptr) { *out << DescribeFileType(type); } return false; } if (auto target = std::filesystem::read_symlink(path); !target_matcher_.Matches(target)) { if (out != nullptr) { *out << "is a symlink whose target is " << target; } return false; } return true; } void DescribeTo(std::ostream* out) const { Desc("is", out); } void DescribeNegationTo(std::ostream* out) const { Desc("is not", out); } private: void Desc(std::string_view prefix, std::ostream* out) const { *out << prefix << " a symlink whose target "; target_matcher_.DescribeTo(out); } testing::Matcher<std::filesystem::path> target_matcher_; }; class FileContentMatcher final { public: using is_gtest_matcher = void; FileContentMatcher(testing::Matcher<std::string> content_matcher) : content_matcher_(std::move(content_matcher)) {} bool MatchAndExplain(const std::filesystem::path& path, std::ostream* out) const { std::ostringstream content; std::ifstream in(path, std::ios::binary); content << in.rdbuf(); if (content_matcher_.Matches(content.str())) { return true; } else { if (out != nullptr) { *out << "is a filesystem path whose content is \"" << content.str() << "\""; } return false; } } void DescribeTo(std::ostream* out) const { Desc("is", out); } void DescribeNegationTo(std::ostream* out) const { Desc("is not", out); } private: void Desc(std::string_view prefix, std::ostream* out) const { *out << prefix << " a filesystem path whose content "; content_matcher_.DescribeTo(out); } testing::Matcher<std::string> content_matcher_; }; } // namespace testing::Matcher<std::filesystem::path> IsRegularFile() { return FileTypeMatcher(std::filesystem::file_type::regular); } testing::Matcher<std::filesystem::path> IsNotFound() { return FileTypeMatcher(std::filesystem::file_type::not_found); } testing::Matcher<std::filesystem::path> IsSymlinkWhoseTarget( testing::Matcher<std::filesystem::path> target_matcher) { return SymlinkMatcher(std::move(target_matcher)); } testing::Matcher<std::filesystem::path> ReadContents( testing::Matcher<std::string> content_matcher) { return FileContentMatcher(std::move(content_matcher)); } std::vector<std::filesystem::path> RecursiveListDirectory( const std::filesystem::path& dir) { std::vector<std::filesystem::path> result; for (const std::filesystem::directory_entry& dent : std::filesystem::recursive_directory_iterator(dir)) { if (!std::filesystem::is_directory(dent.symlink_status())) { result.push_back(dent.path()); } } return result; } std::filesystem::path TempDir::CreateTempDir() { absl::BitGen bitgen; std::filesystem::path d = std::filesystem::temp_directory_path() / "_"; while (true) { d += kBase32Digits[absl::Uniform(bitgen, 0u, std::size(kBase32Digits))]; try { if (std::filesystem::create_directory(d)) { // New directory successfully created. return d; } else { // A directory with this name already existed; try another, // longer, random path name. } } catch (const std::filesystem::filesystem_error& e) { if (e.code() == std::errc::file_exists) { // Something (not a directory) with this name already // existed; try another, longer, random path name. } else { throw; // Unexpected error; re-throw. } } } } } // namespace frz
32.28972
80
0.610709
[ "object", "vector" ]
0e517f4c898d0c82d9c51cdd773386f22d1dffc5
5,590
cpp
C++
modules/assimp/ext/assimp/code/BlenderBMesh.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
13
2015-10-27T22:43:19.000Z
2022-01-07T14:44:56.000Z
modules/assimp/ext/assimp/code/BlenderBMesh.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
1
2019-05-20T23:10:19.000Z
2019-05-20T23:13:49.000Z
modules/assimp/ext/assimp/code/BlenderBMesh.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2013, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ /** @file BlenderBMesh.cpp * @brief Conversion of Blender's new BMesh stuff */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER #include "BlenderDNA.h" #include "BlenderScene.h" #include "BlenderBMesh.h" #include "BlenderTessellator.h" namespace Assimp { template< > const std::string LogFunctions< BlenderBMeshConverter >::log_prefix = "BLEND_BMESH: "; } using namespace Assimp; using namespace Assimp::Blender; using namespace Assimp::Formatter; // ------------------------------------------------------------------------------------------------ BlenderBMeshConverter::BlenderBMeshConverter( const Mesh* mesh ): BMesh( mesh ), triMesh( NULL ) { AssertValidMesh( ); } // ------------------------------------------------------------------------------------------------ BlenderBMeshConverter::~BlenderBMeshConverter( ) { DestroyTriMesh( ); } // ------------------------------------------------------------------------------------------------ bool BlenderBMeshConverter::ContainsBMesh( ) const { // TODO - Should probably do some additional verification here return BMesh->totpoly && BMesh->totloop && BMesh->totvert; } // ------------------------------------------------------------------------------------------------ const Mesh* BlenderBMeshConverter::TriangulateBMesh( ) { AssertValidMesh( ); AssertValidSizes( ); PrepareTriMesh( ); for ( int i = 0; i < BMesh->totpoly; ++i ) { const MPoly& poly = BMesh->mpoly[ i ]; ConvertPolyToFaces( poly ); } return triMesh; } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::AssertValidMesh( ) { if ( !ContainsBMesh( ) ) { ThrowException( "BlenderBMeshConverter requires a BMesh with \"polygons\" - please call BlenderBMeshConverter::ContainsBMesh to check this first" ); } } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::AssertValidSizes( ) { if ( BMesh->totpoly != static_cast<int>( BMesh->mpoly.size( ) ) ) { ThrowException( "BMesh poly array has incorrect size" ); } if ( BMesh->totloop != static_cast<int>( BMesh->mloop.size( ) ) ) { ThrowException( "BMesh loop array has incorrect size" ); } } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::PrepareTriMesh( ) { if ( triMesh ) { DestroyTriMesh( ); } triMesh = new Mesh( *BMesh ); triMesh->totface = 0; triMesh->mface.clear( ); } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::DestroyTriMesh( ) { delete triMesh; triMesh = NULL; } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::ConvertPolyToFaces( const MPoly& poly ) { const MLoop* polyLoop = &BMesh->mloop[ poly.loopstart ]; if ( poly.totloop == 3 || poly.totloop == 4 ) { AddFace( polyLoop[ 0 ].v, polyLoop[ 1 ].v, polyLoop[ 2 ].v, poly.totloop == 4 ? polyLoop[ 3 ].v : 0 ); } else if ( poly.totloop > 4 ) { #if ASSIMP_BLEND_WITH_GLU_TESSELLATE BlenderTessellatorGL tessGL( *this ); tessGL.Tessellate( polyLoop, poly.totloop, triMesh->mvert ); #elif ASSIMP_BLEND_WITH_POLY_2_TRI BlenderTessellatorP2T tessP2T( *this ); tessP2T.Tessellate( polyLoop, poly.totloop, triMesh->mvert ); #endif } } // ------------------------------------------------------------------------------------------------ void BlenderBMeshConverter::AddFace( int v1, int v2, int v3, int v4 ) { MFace face; face.v1 = v1; face.v2 = v2; face.v3 = v3; face.v4 = v4; // TODO - Work out how materials work face.mat_nr = 0; triMesh->mface.push_back( face ); triMesh->totface = triMesh->mface.size( ); } #endif // ASSIMP_BUILD_NO_BLEND_IMPORTER
31.581921
150
0.589267
[ "mesh" ]
0e5589a658301fa245e32cb94b1b4ca454ba4429
16,447
cpp
C++
examples/volcano/window-vulkan.cpp
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
2
2019-08-16T13:33:28.000Z
2020-08-12T21:48:24.000Z
examples/volcano/window-vulkan.cpp
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
examples/volcano/window-vulkan.cpp
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
#include "window.h" #include "resources/shaders/shadertypes.h" #include "typeinfo.h" #include "vk-utils.h" #include "volcano.h" #include <stb_sprintf.h> #if defined(__WINDOWS__) #include <execution> #endif #include <filesystem> #include <future> #include <numeric> #include <string> #include <string_view> #define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <imgui.h> #include <backends/imgui_impl_vulkan.h> template <> void WindowContext<Vk>::internalCreateFrameObjects(Extent2d<Vk> framebufferExtent) { ZoneScopedN("WindowContext::internalCreateFrameObjects"); myViewBuffer = std::make_unique<Buffer<Vk>>( getDeviceContext(), BufferCreateDesc<Vk>{ myConfig.imageCount * ShaderTypes_ViewBufferCount * sizeof(ViewData), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT}); myViews.resize(myConfig.splitScreenGrid.width * myConfig.splitScreenGrid.height); for (auto& view : myViews) { if (!view.desc().viewport.width) view.desc().viewport.width = framebufferExtent.width / myConfig.splitScreenGrid.width; if (!view.desc().viewport.height) view.desc().viewport.height = framebufferExtent.height / myConfig.splitScreenGrid.height; view.updateAll(); } } template <> void WindowContext<Vk>::internalUpdateViewBuffer() const { ZoneScopedN("WindowContext::internalUpdateViewBuffer"); void* data; VK_CHECK(vmaMapMemory(getDeviceContext()->getAllocator(), myViewBuffer->getBufferMemory(), &data)); ViewData* viewDataPtr = &reinterpret_cast<ViewData*>(data)[internalGetFrameIndex() * ShaderTypes_ViewCount]; auto viewCount = (myConfig.splitScreenGrid.width * myConfig.splitScreenGrid.height); assert(viewCount <= ShaderTypes_ViewCount); for (uint32_t viewIt = 0ul; viewIt < viewCount; viewIt++) { viewDataPtr->viewProjectionTransform = myViews[viewIt].getProjectionMatrix() * glm::mat4(myViews[viewIt].getViewMatrix()); viewDataPtr++; } vmaFlushAllocation( getDeviceContext()->getAllocator(), myViewBuffer->getBufferMemory(), internalGetFrameIndex() * ShaderTypes_ViewCount * sizeof(ViewData), viewCount * sizeof(ViewData)); vmaUnmapMemory(getDeviceContext()->getAllocator(), myViewBuffer->getBufferMemory()); } template <> uint32_t WindowContext<Vk>::internalDrawViews( PipelineContext<Vk>& pipeline, CommandPoolContext<Vk>* secondaryContexts, uint32_t secondaryContextCount, const RenderPassBeginInfo<Vk>& renderPassInfo) { // setup draw parameters uint32_t drawCount = myConfig.splitScreenGrid.width * myConfig.splitScreenGrid.height; uint32_t drawThreadCount = std::min<uint32_t>(drawCount, secondaryContextCount); std::atomic_uint32_t drawAtomic = 0ul; // draw views using secondary command buffers // todo: generalize this to other types of draws if (pipeline.resources().model) { ZoneScopedN("WindowContext::drawViews"); std::array<uint32_t, 128> seq; std::iota(seq.begin(), seq.begin() + drawThreadCount, 0); std::for_each_n( #if defined(__WINDOWS__) std::execution::par, #endif seq.begin(), drawThreadCount, [&pipeline, &secondaryContexts, &renderPassInfo, frameIndex = internalGetFrameIndex(), &drawAtomic, &drawCount, &desc = myConfig](uint32_t threadIt) { ZoneScoped; auto drawIt = drawAtomic++; if (drawIt >= drawCount) return; static constexpr std::string_view drawPartitionStr = "WindowContext::drawPartition"; char drawPartitionWithNumberStr[drawPartitionStr.size()+3]; stbsp_sprintf(drawPartitionWithNumberStr, "%.*s%u", static_cast<int>(drawPartitionStr.size()), drawPartitionStr.data(), threadIt); ZoneName(drawPartitionWithNumberStr, sizeof_array(drawPartitionWithNumberStr)); CommandBufferInheritanceInfo<Vk> inheritInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO }; inheritInfo.renderPass = renderPassInfo.renderPass; inheritInfo.framebuffer = renderPassInfo.framebuffer; CommandBufferAccessScopeDesc<Vk> beginInfo = {}; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT; beginInfo.pInheritanceInfo = &inheritInfo; beginInfo.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY; auto& commandContext = secondaryContexts[threadIt]; auto cmd = commandContext.commands(beginInfo); auto bindState = [&pipeline](VkCommandBuffer cmd) { ZoneScopedN("bindState"); // bind descriptor sets pipeline.bindDescriptorSetAuto(cmd, DescriptorSetCategory_GlobalTextures); pipeline.bindDescriptorSetAuto(cmd, DescriptorSetCategory_GlobalSamplers); pipeline.bindDescriptorSetAuto(cmd, DescriptorSetCategory_View); pipeline.bindDescriptorSetAuto(cmd, DescriptorSetCategory_Material); pipeline.bindDescriptorSetAuto(cmd, DescriptorSetCategory_Object); // bind pipeline and vertex/index buffers pipeline.bindPipelineAuto(cmd); VkBuffer vertexBuffers[] = { *pipeline.resources().model }; VkDeviceSize vertexOffsets[] = { pipeline.resources().model->getVertexOffset() }; vkCmdBindVertexBuffers(cmd, 0, 1, vertexBuffers, vertexOffsets); vkCmdBindIndexBuffer(cmd, *pipeline.resources().model, pipeline.resources().model->getIndexOffset(), VK_INDEX_TYPE_UINT32); }; bindState(cmd); uint32_t dx = renderPassInfo.renderArea.extent.width / desc.splitScreenGrid.width; uint32_t dy = renderPassInfo.renderArea.extent.height / desc.splitScreenGrid.height; while (drawIt < drawCount) { auto drawView = [&frameIndex, &pipeline, &cmd, &dx, &dy, &desc](uint16_t viewIt) { ZoneScopedN("drawView"); uint32_t i = viewIt % desc.splitScreenGrid.width; uint32_t j = viewIt / desc.splitScreenGrid.width; auto setViewportAndScissor = [](VkCommandBuffer cmd, int32_t x, int32_t y, uint32_t width, uint32_t height) { ZoneScopedN("setViewportAndScissor"); VkViewport viewport = {}; viewport.x = static_cast<float>(x); viewport.y = static_cast<float>(y); viewport.width = static_cast<float>(width); viewport.height = static_cast<float>(height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = {x, y}; scissor.extent = {width, height}; vkCmdSetViewport(cmd, 0, 1, &viewport); vkCmdSetScissor(cmd, 0, 1, &scissor); }; setViewportAndScissor(cmd, i * dx, j * dy, dx, dy); auto drawModel = [&pipeline, &frameIndex, &viewIt](VkCommandBuffer cmd) { ZoneScopedN("drawModel"); { ZoneScopedN("drawModel::vkCmdPushConstants"); uint16_t viewId = frameIndex * ShaderTypes_ViewCount + viewIt; uint16_t materialId = 0ui16; uint16_t objectBufferIndex = 42ui16; uint16_t objectArrayIndex = 666ui16; PushConstants pushConstants = { (static_cast<uint32_t>(viewId) << 16ul) | materialId, (static_cast<uint32_t>(objectBufferIndex) << 16ul) | objectArrayIndex}; vkCmdPushConstants( cmd, pipeline.getLayout(), VK_SHADER_STAGE_ALL, // todo: input active shader stages + ranges from pipeline 0, sizeof(PushConstants), &pushConstants); } { ZoneScopedN("drawModel::vkCmdDrawIndexed"); vkCmdDrawIndexed(cmd, pipeline.resources().model->getDesc().indexCount, 1, 0, 0, 0); } }; drawModel(cmd); }; drawView(drawIt); drawIt = drawAtomic++; } cmd.end(); }); } return drawThreadCount; } template <> void WindowContext<Vk>::draw( TaskExecutor& executor, PipelineContext<Vk>& pipeline, CommandPoolContext<Vk>& primaryContext, CommandPoolContext<Vk>* secondaryContexts, uint32_t secondaryContextCount) { ZoneScopedN("WindowContext::draw"); auto updateViewBufferFuture = executor.fork([this]{ internalUpdateViewBuffer(); }); auto& renderTarget = pipeline.getRenderTarget(); auto cmd = primaryContext.commands(); auto renderPassInfo = renderTarget.begin(cmd, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); uint32_t drawThreadCount = internalDrawViews( pipeline, secondaryContexts, secondaryContextCount, renderPassInfo.value()); for (uint32_t contextIt = 0ul; contextIt < drawThreadCount; contextIt++) primaryContext.execute(secondaryContexts[contextIt]); //renderTarget.nextSubpass(cmd, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); renderTarget.end(cmd); renderTarget.transitionColor(cmd, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 0); blit(cmd, renderTarget, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, 0, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, 0); executor.join(std::move(updateViewBufferFuture)); } template <> void WindowContext<Vk>::onResizeFramebuffer(Extent2d<Vk> framebufferExtent) { myConfig.extent = framebufferExtent; internalCreateSwapchain(myConfig, *this); internalCreateFrameObjects(framebufferExtent); } template <> void WindowContext<Vk>::updateInput(const InputState& input) { ZoneScopedN("WindowContext::updateInput"); // todo: unify all keyboard and mouse input. rely on imgui instead of glfw internally. { using namespace ImGui; auto& io = GetIO(); if (io.WantCaptureMouse) return; } myTimestamps[1] = myTimestamps[0]; myTimestamps[0] = std::chrono::high_resolution_clock::now(); float dt = (myTimestamps[1] - myTimestamps[0]).count(); if (input.mouseButtonsPressed[2]) { // todo: generic view index calculation size_t viewIdx = input.mousePosition[0].x / (myConfig.windowExtent.width / myConfig.splitScreenGrid.width); size_t viewIdy = input.mousePosition[0].y / (myConfig.windowExtent.height / myConfig.splitScreenGrid.height); myActiveView = std::min((viewIdy * myConfig.splitScreenGrid.width) + viewIdx, myViews.size() - 1); //std::cout << *myActiveView << ":[" << input.mousePosition[0].x << ", " << input.mousePosition[0].y << "]" << std::endl; } else if (!input.mouseButtonsPressed[0]) { myActiveView.reset(); //std::cout << "myActiveView.reset()" << std::endl; } if (myActiveView) { //std::cout << "window.myActiveView read/consume" << std::endl; float dx = 0.f; float dz = 0.f; for (const auto& [key, pressed] : input.keysPressed) { if (pressed) { switch (key) { case GLFW_KEY_W: dz = -1; break; case GLFW_KEY_S: dz = 1; break; case GLFW_KEY_A: dx = -1; break; case GLFW_KEY_D: dx = 1; break; default: break; } } } auto& view = myViews[*myActiveView]; bool doUpdateViewMatrix = false; if (dx != 0 || dz != 0) { const auto& viewMatrix = view.getViewMatrix(); auto forward = glm::vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2]); auto strafe = glm::vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]); constexpr auto moveSpeed = 0.000000002f; view.desc().cameraPosition += dt * (dz * forward + dx * strafe) * moveSpeed; // std::cout << *myActiveView << ":pos:[" << view.desc().cameraPosition.x << ", " << // view.desc().cameraPosition.y << ", " << view.desc().cameraPosition.z << "]" << std::endl; doUpdateViewMatrix = true; } if (input.mouseButtonsPressed[0]) { constexpr auto rotSpeed = 0.00000001f; auto dM = input.mousePosition[1] - input.mousePosition[0]; view.desc().cameraRotation += dt * glm::vec3(dM.y / view.desc().viewport.height, dM.x / view.desc().viewport.width, 0.0f) * rotSpeed; // std::cout << *myActiveView << ":rot:[" << view.desc().cameraRotation.x << ", " << // view.desc().cameraRotation.y << ", " << view.desc().cameraRotation.z << "]" << std::endl; doUpdateViewMatrix = true; } if (doUpdateViewMatrix) { myViews[*myActiveView].updateViewMatrix(); } } } template <> WindowContext<Vk>::WindowContext( const std::shared_ptr<DeviceContext<Vk>>& deviceContext, SurfaceHandle<Vk>&& surface, WindowConfiguration<Vk>&& defaultConfig) : Swapchain( deviceContext, defaultConfig, std::forward<SurfaceHandle<Vk>>(surface), VK_NULL_HANDLE) , myConfig( AutoSaveJSONFileObject<WindowConfiguration<Vk>>( std::filesystem::path(volcano_getUserProfilePath()) / "window.json", std::forward<WindowConfiguration<Vk>>(defaultConfig))) { ZoneScopedN("Window()"); internalCreateFrameObjects(myConfig.extent); myTimestamps[0] = std::chrono::high_resolution_clock::now(); } template <> WindowContext<Vk>::WindowContext(WindowContext&& other) noexcept : Swapchain(std::forward<WindowContext>(other)) , myConfig(std::exchange(other.myConfig, {})) , myTimestamps(std::exchange(other.myTimestamps, {})) , myViews(std::exchange(other.myViews, {})) , myActiveView(std::exchange(other.myActiveView, {})) , myViewBuffer(std::exchange(other.myViewBuffer, {})) { } template <> WindowContext<Vk>::~WindowContext() { ZoneScopedN("~Window()"); } template <> WindowContext<Vk>& WindowContext<Vk>::operator=(WindowContext&& other) noexcept { Swapchain::operator=(std::forward<WindowContext>(other)); myConfig = std::exchange(other.myConfig, {}); myTimestamps = std::exchange(other.myTimestamps, {}); myViews = std::exchange(other.myViews, {}); myActiveView = std::exchange(other.myActiveView, {}); myViewBuffer = std::exchange(other.myViewBuffer, {}); return *this; } template <> void WindowContext<Vk>::swap(WindowContext& other) noexcept { Swapchain::swap(other); std::swap(myConfig, other.myConfig); std::swap(myTimestamps, other.myTimestamps); std::swap(myViews, other.myViews); std::swap(myActiveView, other.myActiveView); std::swap(myViewBuffer, other.myViewBuffer); }
36.467849
160
0.588436
[ "model" ]
0e568d17a2e4c581a88f797d39931ef02aebb91a
3,946
hpp
C++
ThirdParty-mod/java2cpp/android/webkit/HttpAuthHandler.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/webkit/HttpAuthHandler.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/webkit/HttpAuthHandler.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.webkit.HttpAuthHandler ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_DECL #define J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace android { namespace os { class Handler; } } } namespace j2cpp { namespace android { namespace os { class Message; } } } #include <android/os/Handler.hpp> #include <android/os/Message.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace webkit { class HttpAuthHandler; class HttpAuthHandler : public object<HttpAuthHandler> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) explicit HttpAuthHandler(jobject jobj) : object<HttpAuthHandler>(jobj) { } operator local_ref<android::os::Handler>() const; void handleMessage(local_ref< android::os::Message > const&); void proceed(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&); void cancel(); jboolean useHttpAuthUsernamePassword(); }; //class HttpAuthHandler } //namespace webkit } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_IMPL #define J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_IMPL namespace j2cpp { android::webkit::HttpAuthHandler::operator local_ref<android::os::Handler>() const { return local_ref<android::os::Handler>(get_jobject()); } void android::webkit::HttpAuthHandler::handleMessage(local_ref< android::os::Message > const &a0) { return call_method< android::webkit::HttpAuthHandler::J2CPP_CLASS_NAME, android::webkit::HttpAuthHandler::J2CPP_METHOD_NAME(1), android::webkit::HttpAuthHandler::J2CPP_METHOD_SIGNATURE(1), void >(get_jobject(), a0); } void android::webkit::HttpAuthHandler::proceed(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1) { return call_method< android::webkit::HttpAuthHandler::J2CPP_CLASS_NAME, android::webkit::HttpAuthHandler::J2CPP_METHOD_NAME(2), android::webkit::HttpAuthHandler::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject(), a0, a1); } void android::webkit::HttpAuthHandler::cancel() { return call_method< android::webkit::HttpAuthHandler::J2CPP_CLASS_NAME, android::webkit::HttpAuthHandler::J2CPP_METHOD_NAME(3), android::webkit::HttpAuthHandler::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject()); } jboolean android::webkit::HttpAuthHandler::useHttpAuthUsernamePassword() { return call_method< android::webkit::HttpAuthHandler::J2CPP_CLASS_NAME, android::webkit::HttpAuthHandler::J2CPP_METHOD_NAME(4), android::webkit::HttpAuthHandler::J2CPP_METHOD_SIGNATURE(4), jboolean >(get_jobject()); } J2CPP_DEFINE_CLASS(android::webkit::HttpAuthHandler,"android/webkit/HttpAuthHandler") J2CPP_DEFINE_METHOD(android::webkit::HttpAuthHandler,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::webkit::HttpAuthHandler,1,"handleMessage","(Landroid/os/Message;)V") J2CPP_DEFINE_METHOD(android::webkit::HttpAuthHandler,2,"proceed","(Ljava/lang/String;Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(android::webkit::HttpAuthHandler,3,"cancel","()V") J2CPP_DEFINE_METHOD(android::webkit::HttpAuthHandler,4,"useHttpAuthUsernamePassword","()Z") } //namespace j2cpp #endif //J2CPP_ANDROID_WEBKIT_HTTPAUTHHANDLER_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
30.122137
133
0.717689
[ "object" ]
0e580b51325f44fb2542d3419b3c096cf3f2f0b7
2,667
cpp
C++
rtdoom/MapStore.cpp
rohatsu/rtdoom
0edcaa628a1470731f9af04d50453cf9e1736ecf
[ "MIT" ]
15
2020-02-03T13:12:21.000Z
2021-09-08T12:46:09.000Z
rtdoom/MapStore.cpp
mausimus/rtdoom
0edcaa628a1470731f9af04d50453cf9e1736ecf
[ "MIT" ]
1
2021-03-10T23:04:18.000Z
2021-03-22T23:02:36.000Z
rtdoom/MapStore.cpp
mausimus/rtdoom
0edcaa628a1470731f9af04d50453cf9e1736ecf
[ "MIT" ]
3
2021-02-20T23:16:15.000Z
2021-05-31T19:18:35.000Z
#include "pch.h" #include "MapStore.h" #include "Helpers.h" using namespace std::literals::string_literals; namespace rtdoom { MapStore::MapStore() { } void MapStore::Load(const std::string& mapFolder) { m_vertexes = Helpers::LoadEntities<Vertex>(mapFolder + "\\vertexes.lmp"s); m_lineDefs = Helpers::LoadEntities<LineDef>(mapFolder + "\\linedefs.lmp"s); m_sideDefs = Helpers::LoadEntities<SideDef>(mapFolder + "\\sidedefs.lmp"s); m_sectors = Helpers::LoadEntities<Sector>(mapFolder + "\\sectors.lmp"s); m_subSectors = Helpers::LoadEntities<SubSector>(mapFolder + "\\ssectors.lmp"s); m_nodes = Helpers::LoadEntities<Node>(mapFolder + "\\nodes.lmp"s); m_segments = Helpers::LoadEntities<Segment>(mapFolder + "\\segs.lmp"s); m_things = Helpers::LoadEntities<Thing>(mapFolder + "\\things.lmp"s); } void MapStore::Load(const std::map<std::string, std::vector<char>>& mapLumps) { m_vertexes = Helpers::LoadEntities<Vertex>(mapLumps.at("VERTEXES"s)); m_lineDefs = Helpers::LoadEntities<LineDef>(mapLumps.at("LINEDEFS"s)); m_sideDefs = Helpers::LoadEntities<SideDef>(mapLumps.at("SIDEDEFS"s)); m_sectors = Helpers::LoadEntities<Sector>(mapLumps.at("SECTORS"s)); m_subSectors = Helpers::LoadEntities<SubSector>(mapLumps.at("SSECTORS"s)); m_nodes = Helpers::LoadEntities<Node>(mapLumps.at("NODES"s)); m_segments = Helpers::LoadEntities<Segment>(mapLumps.at("SEGS"s)); m_things = Helpers::LoadEntities<Thing>(mapLumps.at("THINGS"s)); } void MapStore::LoadGL(const std::map<std::string, std::vector<char>>& glLumps) { const auto& glVertexes = glLumps.at("GL_VERT"s); if(strncmp(glVertexes.data(), "gNd2", 4) != 0) { throw std::runtime_error("Only V2 glBSP format is supported."); } m_glVertexes = Helpers::LoadEntities<GLVertex>(glVertexes, 4); m_glSegments = Helpers::LoadEntities<GLSegment>(glLumps.at("GL_SEGS"s)); m_subSectors = Helpers::LoadEntities<SubSector>(glLumps.at("GL_SSECT"s)); m_nodes = Helpers::LoadEntities<Node>(glLumps.at("GL_NODES"s)); } void MapStore::GetStartingPosition(signed short& x, signed short& y, unsigned short& a) const { auto foundPlayer = find_if(m_things.cbegin(), m_things.cend(), [](const Thing& t) { return t.type == 1; }); if(foundPlayer == m_things.cend()) { throw std::runtime_error("No player starting location on map"); } const Thing& playerThing = *foundPlayer; x = playerThing.x; y = playerThing.y; a = playerThing.a; } MapStore::~MapStore() { } } // namespace rtdoom
42.333333
111
0.665167
[ "vector" ]
0e5bbc1c31a0728196b2e7874d9fb3a2f7e0bddd
7,792
cpp
C++
tests/core/RssSituationIdProviderTests.cpp
tier4/ad-rss-lib
7634fd6f040e33e176d5be83638a74b29f5a012b
[ "BSD-3-Clause" ]
1
2019-07-20T02:10:53.000Z
2019-07-20T02:10:53.000Z
tests/core/RssSituationIdProviderTests.cpp
ANTi7kZ/ad-rss-lib
7634fd6f040e33e176d5be83638a74b29f5a012b
[ "BSD-3-Clause" ]
null
null
null
tests/core/RssSituationIdProviderTests.cpp
ANTi7kZ/ad-rss-lib
7634fd6f040e33e176d5be83638a74b29f5a012b
[ "BSD-3-Clause" ]
1
2021-02-25T01:02:15.000Z
2021-02-25T01:02:15.000Z
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (c) 2019 Intel Corporation // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // ----------------- END LICENSE BLOCK ----------------------------------- #include "RssCheckTestBaseT.hpp" #include "world/RssSituationIdProvider.hpp" namespace ad_rss { namespace world { class RssSituationIdProviderTests : public core::RssCheckTestBaseT<testing::Test> { public: ::ad_rss::world::Object &getEgoObject() override { return objectOnSegment0; } ::ad_rss::world::Object &getSceneObject(uint32_t) override { return objectOnSegment8; } situation::SituationType getSituationType() override { return situation::SituationType::IntersectionEgoHasPriority; } RssSituationIdProvider situationIdProvider; }; TEST_F(RssSituationIdProviderTests, same_scene_result_in_same_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(firstSituationId, secondSituationId); worldModel.timeIndex++; secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_objectids_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].object.objectId = 49; auto const secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_situation_types_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].situationType = situation::SituationType::IntersectionObjectHasPriority; auto const secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_ego_intersection_route_id_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].egoVehicleRoad.back().back().id = 88; auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_object_intersection_route_id_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].intersectingRoad.back().back().id = 99; auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_ego_intersection_route_size_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].egoVehicleRoad.back().push_back(worldModel.scenes[0].egoVehicleRoad.back().back()); worldModel.scenes[0].egoVehicleRoad.back().back().id = 88; auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_object_intersection_route_size_result_in_different_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].intersectingRoad.back().push_back(worldModel.scenes[0].intersectingRoad.back().back()); worldModel.scenes[0].intersectingRoad.back().back().id = 99; auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_ego_non_intersection_route_size_result_in_same_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].egoVehicleRoad.erase(worldModel.scenes[0].egoVehicleRoad.begin()); auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, different_object_non_intersection_route_size_result_in_same_situations) { auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].intersectingRoad.erase(worldModel.scenes[0].intersectingRoad.begin()); auto secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(firstSituationId, secondSituationId); } TEST_F(RssSituationIdProviderTests, history_is_cleaned) { auto const originalObjectId = worldModel.scenes[0].object.objectId; auto const firstSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); worldModel.scenes[0].object.objectId = 49; auto const secondSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, secondSituationId); worldModel.timeIndex++; auto thirdSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(secondSituationId, thirdSituationId); worldModel.timeIndex++; // 49 still tracked thirdSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_EQ(secondSituationId, thirdSituationId); // original already forgotten worldModel.scenes[0].object.objectId = originalObjectId; auto fourthSituationId = situationIdProvider.getSituationId(worldModel.timeIndex, worldModel.scenes[0]); EXPECT_NE(firstSituationId, fourthSituationId); } } // namespace world } // namespace ad_rss
46.380952
112
0.799795
[ "object" ]
0e5cf21e662265519e9b0e06e86d06483dcb2959
96,761
cpp
C++
dev/Code/CryEngine/RenderDll/XRenderD3D9/D3DRenderRE.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
1
2019-02-12T06:44:50.000Z
2019-02-12T06:44:50.000Z
dev/Code/CryEngine/RenderDll/XRenderD3D9/D3DRenderRE.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
null
null
null
dev/Code/CryEngine/RenderDll/XRenderD3D9/D3DRenderRE.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : implementation of the Rendering RenderElements pipeline. #include "StdAfx.h" #include "DriverD3D.h" #include "../Common/RendElements/Stars.h" #include "I3DEngine.h" #include "../Common/PostProcess/PostProcessUtils.h" #include "../Common/PostProcess/PostEffects.h" #include "D3DPostProcess.h" #include "CREParticle.h" #include "CREParticleGPU.h" #include "D3DGPUParticleEngine.h" #include "../Common/Renderer.h" #include "../Common/Textures/TextureManager.h" #pragma warning(disable: 4244) //======================================================================= bool CRESky::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd = gcpRendD3D; #if !defined(_RELEASE) if (ef->m_eShaderType != eST_Sky) { CryWarning(VALIDATOR_MODULE_RENDERER, VALIDATOR_ERROR, "Incorrect shader set for sky"); return false; } #endif if (!rd->m_RP.m_pShaderResources || !rd->m_RP.m_pShaderResources->m_pSky) { return false; } // pass 0 - skybox SSkyInfo* pSky = rd->m_RP.m_pShaderResources->m_pSky; if (!pSky->m_SkyBox[0]) { return false; } float v(gEnv->p3DEngine->GetGlobalParameter(E3DPARAM_SKYBOX_MULTIPLIER)); rd->SetMaterialColor(v, v, v, m_fAlpha); if (!sfm) { ef->FXSetTechnique(CCryNameTSCRC((uint32)0)); } uint32 nPasses = 0; ef->FXBegin(&nPasses, FEF_DONTSETTEXTURES); //ef->FXBegin(&nPasses, 0 ); if (!nPasses) { return false; } ef->FXBeginPass(0); rd->FX_PushVP(); rd->m_NewViewport.fMinZ = 1.0f; rd->m_NewViewport.fMaxZ = 1.0f; rd->m_bViewportDirty = true; STexState pTexState; pTexState.SetFilterMode(FILTER_LINEAR); pTexState.SetClampMode(1, 1, 1); int texStateID = CTexture::GetTexState(pTexState); const float fSkyBoxSize = SKY_BOX_SIZE; rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); if (rd->m_RP.m_nBatchFilter & FB_Z) { CTextureManager::Instance()->GetBlackTexture()->Apply(0, texStateID); { // top SVF_P3F_C4B_T2F data[] = { {Vec3(+fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(-fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(+fSkyBoxSize, +fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(-fSkyBoxSize, +fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 0)} }; CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 4, eptTriangleStrip); } { // nesw SVF_P3F_C4B_T2F data[] = { { Vec3(-fSkyBoxSize, -fSkyBoxSize, +fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(+fSkyBoxSize, -fSkyBoxSize, +fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(+fSkyBoxSize, -fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(+fSkyBoxSize, +fSkyBoxSize, +fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(+fSkyBoxSize, +fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(-fSkyBoxSize, +fSkyBoxSize, +fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(-fSkyBoxSize, +fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(-fSkyBoxSize, -fSkyBoxSize, +fSkyBoxSize), { {0} }, Vec2(0, 0)}, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, }; CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 10, eptTriangleStrip); } { // b SVF_P3F_C4B_T2F data[] = { {Vec3(+fSkyBoxSize, -fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(-fSkyBoxSize, -fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(+fSkyBoxSize, +fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)}, {Vec3(-fSkyBoxSize, +fSkyBoxSize, -fSkyBoxSize), { {0} }, Vec2(0, 0)} }; CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 4, eptTriangleStrip); } } else { { // top SVF_P3F_C4B_T2F data[] = { {Vec3(fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1, 1.f - 1)}, {Vec3(-fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 1.f - 1)}, {Vec3(fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1, 1.f - 0)}, {Vec3(-fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0, 1.f - 0)} }; ((CTexture*)(pSky->m_SkyBox[2]))->Apply(0, texStateID); CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 4, eptTriangleStrip); } Vec3 camera = iSystem->GetViewCamera().GetPosition(); camera.z = max(0.f, camera.z); float fWaterCamDiff = max(0.f, camera.z - m_fTerrainWaterLevel); float fMaxDist = gEnv->p3DEngine->GetMaxViewDistance() / 1024.f; float P = (fWaterCamDiff) / 128 + max(0.f, (fWaterCamDiff) * 0.03f / fMaxDist); P *= m_fSkyBoxStretching; float D = (fWaterCamDiff) / 10.0f * fSkyBoxSize / 124.0f - /*P*/ 0 + 8; D = max(0.f, D); if (m_fTerrainWaterLevel > camera.z && SRendItem::m_RecurseLevel[rd->m_RP.m_nProcessThreadID] == 0) { P = (fWaterCamDiff); D = (fWaterCamDiff); } float fTexOffset; fTexOffset = 1.0f / max(pSky->m_SkyBox[1]->GetHeight(), 1); { // s SVF_P3F_C4B_T2F data[] = { { Vec3(-fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1.0, 1.f - 1.0) }, { Vec3(fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0.0, 1.f - 1.0) }, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -P), { {0} }, Vec2(1.0, 1.f - 0.5 - fTexOffset) }, { Vec3(fSkyBoxSize, -fSkyBoxSize, -P), { {0} }, Vec2(0.0, 1.f - 0.5 - fTexOffset) }, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -D), { {0} }, Vec2(1.0, 1.f - 0.5 - fTexOffset) }, { Vec3(fSkyBoxSize, -fSkyBoxSize, -D), { {0} }, Vec2(0.0, 1.f - 0.5 - fTexOffset) } }; ((CTexture*)(pSky->m_SkyBox[1]))->Apply(0, texStateID); CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 6, eptTriangleStrip); } { // e SVF_P3F_C4B_T2F data[] = { { Vec3(-fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1.0, 1.f - 0.0) }, { Vec3(-fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0.0, 1.f - 0.0) }, { Vec3(-fSkyBoxSize, fSkyBoxSize, -P), { {0} }, Vec2(1.0, 1.f - 0.5f + fTexOffset) }, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -P), { {0} }, Vec2(0.0, 1.f - 0.5f + fTexOffset) }, { Vec3(-fSkyBoxSize, fSkyBoxSize, -D), { {0} }, Vec2(1.0, 1.f - 0.5f + fTexOffset) }, { Vec3(-fSkyBoxSize, -fSkyBoxSize, -D), { {0} }, Vec2(0.0, 1.f - 0.5f + fTexOffset) } }; CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 6, eptTriangleStrip); } fTexOffset = 1.0f / max(pSky->m_SkyBox[0]->GetHeight(), 1); { // n SVF_P3F_C4B_T2F data[] = { { Vec3(fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1.0, 1.f - 1.0) }, { Vec3(-fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0.0, 1.f - 1.0) }, { Vec3(fSkyBoxSize, fSkyBoxSize, -P), { {0} }, Vec2(1.0, 1.f - 0.5 - fTexOffset) }, { Vec3(-fSkyBoxSize, fSkyBoxSize, -P), { {0} }, Vec2(0.0, 1.f - 0.5 - fTexOffset) }, { Vec3(fSkyBoxSize, fSkyBoxSize, -D), { {0} }, Vec2(1.0, 1.f - 0.5 - fTexOffset) }, { Vec3(-fSkyBoxSize, fSkyBoxSize, -D), { {0} }, Vec2(0.0, 1.f - 0.5 - fTexOffset) } }; ((CTexture*)(pSky->m_SkyBox[0]))->Apply(0, texStateID); CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 6, eptTriangleStrip); } { // w SVF_P3F_C4B_T2F data[] = { { Vec3(fSkyBoxSize, -fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(1.0, 1.f - 0.0) }, { Vec3(fSkyBoxSize, fSkyBoxSize, fSkyBoxSize), { {0} }, Vec2(0.0, 1.f - 0.0) }, { Vec3(fSkyBoxSize, -fSkyBoxSize, -P), { {0} }, Vec2(1.0, 1.f - 0.5f + fTexOffset) }, { Vec3(fSkyBoxSize, fSkyBoxSize, -P), { {0} }, Vec2(0.0, 1.f - 0.5f + fTexOffset) }, { Vec3(fSkyBoxSize, -fSkyBoxSize, -D), { {0} }, Vec2(1.0, 1.f - 0.5f + fTexOffset) }, { Vec3(fSkyBoxSize, fSkyBoxSize, -D), { {0} }, Vec2(0.0, 1.f - 0.5f + fTexOffset) } }; CVertexBuffer vertexBuffer(data, eVF_P3F_C4B_T2F); rd->DrawPrimitivesInternal(&vertexBuffer, 6, eptTriangleStrip); } } rd->FX_PopVP(); rd->FX_ResetPipe(); return true; } static void FillSkyTextureData(CTexture* pTexture, const void* pData, const uint32 width, const uint32 height, const uint32 pitch) { assert(pTexture && pTexture->GetWidth() == width && pTexture->GetHeight() == height); CDeviceTexture* pDevTex = pTexture->GetDevTexture(); assert(pDevTex); if (!pDevTex) { return; } gcpRendD3D->GetDeviceContext().UpdateSubresource(pDevTex->Get2DTexture(), 0, 0, pData, sizeof(CryHalf4) * width, sizeof(CryHalf4) * width * height); } bool CREHDRSky::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd(gcpRendD3D); #if !defined(_RELEASE) if (ef->m_eShaderType != eST_Sky) { CryWarning(VALIDATOR_MODULE_RENDERER, VALIDATOR_ERROR, "Incorrect shader set for sky"); return false; } #endif if (!rd->m_RP.m_pShaderResources || !rd->m_RP.m_pShaderResources->m_pSky) { return false; } SSkyInfo* pSky(rd->m_RP.m_pShaderResources->m_pSky); if (!pSky->m_SkyBox[0]) { return false; } assert(m_pRenderParams); if (!m_pRenderParams) { return false; } assert(m_pRenderParams->m_pSkyDomeMesh.get()); if (!m_pRenderParams->m_pSkyDomeMesh) { return false; } bool isNotZPass = (rd->m_RP.m_nBatchFilter & FB_Z) == 0; if (isNotZPass) { // re-create sky dome textures if necessary bool forceTextureUpdate(false); if (!CTexture::IsTextureExist(m_pSkyDomeTextureMie) || !CTexture::IsTextureExist(m_pSkyDomeTextureRayleigh)) { GenerateSkyDomeTextures(SSkyLightRenderParams::skyDomeTextureWidth, SSkyLightRenderParams::skyDomeTextureHeight); forceTextureUpdate = true; } // dyn tex data lost due to device reset? if (m_frameReset != rd->m_nFrameReset) { forceTextureUpdate = true; m_frameReset = rd->m_nFrameReset; } // update sky dome texture if new data is available if (m_skyDomeTextureLastTimeStamp != m_pRenderParams->m_skyDomeTextureTimeStamp || forceTextureUpdate) { FillSkyTextureData(m_pSkyDomeTextureMie, m_pRenderParams->m_pSkyDomeTextureDataMie, SSkyLightRenderParams::skyDomeTextureWidth, SSkyLightRenderParams::skyDomeTextureHeight, m_pRenderParams->m_skyDomeTexturePitch); FillSkyTextureData(m_pSkyDomeTextureRayleigh, m_pRenderParams->m_pSkyDomeTextureDataRayleigh, SSkyLightRenderParams::skyDomeTextureWidth, SSkyLightRenderParams::skyDomeTextureHeight, m_pRenderParams->m_skyDomeTexturePitch); // update time stamp of last update m_skyDomeTextureLastTimeStamp = m_pRenderParams->m_skyDomeTextureTimeStamp; } } // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (!nPasses) { return false; } ef->FXBeginPass(0); I3DEngine* p3DEngine(gEnv->p3DEngine); rd->FX_PushVP(); rd->m_NewViewport.fMinZ = 1.0f; rd->m_NewViewport.fMaxZ = 1.0f; rd->m_bViewportDirty = true; if (isNotZPass) { // shader constants -- set sky dome texture and texel size assert(m_pSkyDomeTextureMie && m_pSkyDomeTextureMie->GetWidth() == SSkyLightRenderParams::skyDomeTextureWidth && m_pSkyDomeTextureMie->GetHeight() == SSkyLightRenderParams::skyDomeTextureHeight); assert(m_pSkyDomeTextureRayleigh && m_pSkyDomeTextureRayleigh->GetWidth() == SSkyLightRenderParams::skyDomeTextureWidth && m_pSkyDomeTextureRayleigh->GetHeight() == SSkyLightRenderParams::skyDomeTextureHeight); Vec4 skyDomeTexSizeVec((float) SSkyLightRenderParams::skyDomeTextureWidth, (float) SSkyLightRenderParams::skyDomeTextureHeight, 0.0f, 0.0f); static CCryNameR Param1Name("SkyDome_TextureSize"); ef->FXSetPSFloat(Param1Name, &skyDomeTexSizeVec, 1); Vec4 skyDomeTexelSizeVec(1.0f / (float) SSkyLightRenderParams::skyDomeTextureWidth, 1.0f / (float) SSkyLightRenderParams::skyDomeTextureHeight, 0.0f, 0.0f); static CCryNameR Param2Name("SkyDome_TexelSize"); ef->FXSetPSFloat(Param2Name, &skyDomeTexelSizeVec, 1); // shader constants -- phase function constants static CCryNameR Param3Name("SkyDome_PartialMieInScatteringConst"); static CCryNameR Param4Name("SkyDome_PartialRayleighInScatteringConst"); static CCryNameR Param5Name("SkyDome_SunDirection"); static CCryNameR Param6Name("SkyDome_PhaseFunctionConstants"); ef->FXSetPSFloat(Param3Name, &m_pRenderParams->m_partialMieInScatteringConst, 1); ef->FXSetPSFloat(Param4Name, &m_pRenderParams->m_partialRayleighInScatteringConst, 1); ef->FXSetPSFloat(Param5Name, &m_pRenderParams->m_sunDirection, 1); ef->FXSetPSFloat(Param6Name, &m_pRenderParams->m_phaseFunctionConsts, 1); // shader constants -- night sky relevant constants Vec3 nightSkyHorizonCol; p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_HORIZON_COLOR, nightSkyHorizonCol); Vec3 nightSkyZenithCol; p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_ZENITH_COLOR, nightSkyZenithCol); float nightSkyZenithColShift(p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_ZENITH_SHIFT)); const float minNightSkyZenithGradient(-0.1f); static CCryNameR Param7Name("SkyDome_NightSkyColBase"); static CCryNameR Param8Name("SkyDome_NightSkyColDelta"); static CCryNameR Param9Name("SkyDome_NightSkyZenithColShift"); Vec4 nsColBase(nightSkyHorizonCol, 0); ef->FXSetPSFloat(Param7Name, &nsColBase, 1); Vec4 nsColDelta(nightSkyZenithCol - nightSkyHorizonCol, 0); ef->FXSetPSFloat(Param8Name, &nsColDelta, 1); Vec4 nsZenithColShift(1.0f / (nightSkyZenithColShift - minNightSkyZenithGradient), -minNightSkyZenithGradient / (nightSkyZenithColShift - minNightSkyZenithGradient), 0, 0); ef->FXSetPSFloat(Param9Name, &nsZenithColShift, 1); CREHDRSky::SetCommonMoonParams(ef, true); Vec3 nightMoonColor; p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_MOON_COLOR, nightMoonColor); Vec4 nsMoonColor(nightMoonColor, 0); static CCryNameR Param11Name("SkyDome_NightMoonColor"); ef->FXSetPSFloat(Param11Name, &nsMoonColor, 1); Vec3 nightMoonInnerCoronaColor; p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_MOON_INNERCORONA_COLOR, nightMoonInnerCoronaColor); float nightMoonInnerCoronaScale(1.0f + 1000.0f * p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_MOON_INNERCORONA_SCALE)); Vec4 nsMoonInnerCoronaColorScale(nightMoonInnerCoronaColor, nightMoonInnerCoronaScale); static CCryNameR Param12Name("SkyDome_NightMoonInnerCoronaColorScale"); ef->FXSetPSFloat(Param12Name, &nsMoonInnerCoronaColorScale, 1); Vec3 nightMoonOuterCoronaColor; p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, nightMoonOuterCoronaColor); float nightMoonOuterCoronaScale(1.0f + 1000.0f * p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_MOON_OUTERCORONA_SCALE)); Vec4 nsMoonOuterCoronaColorScale(nightMoonOuterCoronaColor, nightMoonOuterCoronaScale); static CCryNameR Param13Name("SkyDome_NightMoonOuterCoronaColorScale"); ef->FXSetPSFloat(Param13Name, &nsMoonOuterCoronaColorScale, 1); } HRESULT hr(S_OK); // commit all render changes // David S. workaround for Mali driver's bug if (isNotZPass && (gRenDev->GetFeatures() & RFT_HW_ARM_MALI)) { uint32 newState = rd->m_RP.m_CurState; newState |= GS_STENCIL; rd->FX_SetStencilState( STENC_FUNC(FSS_STENCFUNC_ALWAYS) | STENCOP_FAIL(FSS_STENCOP_KEEP) | STENCOP_ZFAIL(FSS_STENCOP_KEEP) | STENCOP_ZFAIL(FSS_STENCOP_KEEP), 1, 0xFFFFFFFF, 0xFFFFFFFF); rd->FX_SetState(newState); } rd->FX_Commit(); // set vertex declaration and streams of sky dome CRenderMesh* pSkyDomeMesh = static_cast<CRenderMesh*>(m_pRenderParams->m_pSkyDomeMesh.get()); hr = rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F); if (!FAILED(hr)) { // set vertex and index buffer pSkyDomeMesh->CheckUpdate(0); size_t vbOffset(0); size_t ibOffset(0); D3DBuffer* pVB = rd->m_DevBufMan.GetD3D(pSkyDomeMesh->_GetVBStream(VSF_GENERAL), &vbOffset); D3DBuffer* pIB = rd->m_DevBufMan.GetD3D(pSkyDomeMesh->_GetIBStream(), &ibOffset); assert(pVB); assert(pIB); if (!pVB || !pIB) { return false; } hr = rd->FX_SetVStream(0, pVB, vbOffset, pSkyDomeMesh->GetStreamStride(VSF_GENERAL)); hr = rd->FX_SetIStream(pIB, ibOffset, (sizeof(vtx_idx) == 2 ? Index16 : Index32)); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); // draw sky dome rd->FX_DrawIndexedPrimitive(eptTriangleList, 0, 0, pSkyDomeMesh->_GetNumVerts(), 0, pSkyDomeMesh->_GetNumInds()); } ef->FXEndPass(); ef->FXEnd(); if (m_pStars) { m_pStars->Render(m_moonTexId > 0 ? true : false); } rd->FX_PopVP(); gcpRendD3D->FX_ResetPipe(); return true; } void CStars::Render(bool bUseMoon) { CD3D9Renderer* rd(gcpRendD3D); I3DEngine* p3DEngine(gEnv->p3DEngine); float starIntensity(p3DEngine->GetGlobalParameter(E3DPARAM_NIGHSKY_STAR_INTENSITY)); if (m_pStarMesh && m_pShader && rd->m_RP.m_nPassGroupID == EFSLIST_GENERAL && (rd->m_RP.m_nBatchFilter & FB_GENERAL) && starIntensity > 1e-3f) { ////////////////////////////////////////////////////////////////////////// // set shader static CCryNameTSCRC shaderTech("Stars"); m_pShader->FXSetTechnique(shaderTech); uint32 nPasses(0); m_pShader->FXBegin(&nPasses, FEF_DONTSETTEXTURES | FEF_DONTSETSTATES); if (!nPasses) { return; } m_pShader->FXBeginPass(0); ////////////////////////////////////////////////////////////////////////// // setup params int vpX(0), vpY(0), vpWidth(0), vpHeight(0); rd->GetViewport(&vpX, &vpY, &vpWidth, &vpHeight); const float size = 5.0f * min(1.f, min(vpWidth / 1280.f, vpHeight / 720.f)); float flickerTime(gEnv->pTimer->GetCurrTime()); static CCryNameR vspnStarSize("StarSize"); Vec4 paramStarSize(size / (float)vpWidth, size / (float)vpHeight, 0, flickerTime * 0.5f); m_pShader->FXSetVSFloat(vspnStarSize, &paramStarSize, 1); static CCryNameR pspnStarIntensity("StarIntensity"); Vec4 paramStarIntensity(starIntensity* min(1.f, size), 0, 0, 0); m_pShader->FXSetPSFloat(pspnStarIntensity, &paramStarIntensity, 1); CREHDRSky::SetCommonMoonParams(m_pShader, bUseMoon); ////////////////////////////////////////////////////////////////////////// // commit & draw int32 nRenderState = GS_BLSRC_ONE | GS_BLDST_ONE; rd->FX_SetState(nRenderState); rd->FX_Commit(); if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3S_C4B_T2S))) { size_t offset(0); //void* pVB(m_pStarVB->GetStream(VSF_GENERAL, &offset)); //rd->FX_SetVStream(0, pVB, offset, m_VertexSize[m_pStarVB->m_vertexformat]); CRenderMesh* pStarMesh = static_cast<CRenderMesh*>(m_pStarMesh.get()); pStarMesh->CheckUpdate(0); D3DBuffer* pVB = rd->m_DevBufMan.GetD3D(pStarMesh->_GetVBStream(VSF_GENERAL), &offset); rd->FX_SetVStream(0, pVB, offset, pStarMesh->GetStreamStride(VSF_GENERAL)); rd->FX_SetIStream(0, 0, Index16); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); rd->FX_DrawPrimitive(eptTriangleList, 0, 6 * m_numStars); } m_pShader->FXEndPass(); m_pShader->FXEnd(); } } bool CREFogVolume::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd(gcpRendD3D); #if !defined(_RELEASE) if (ef->m_eShaderType != eST_PostProcess) { CryWarning(VALIDATOR_MODULE_RENDERER, VALIDATOR_ERROR, "Incorrect shader set for fog volume"); return false; } #endif // shader technique is multi-pass but it doesn't need to be rendered twice. if (rd->m_RP.m_nNumRendPasses > 1) { return false; } // rendered to volume texture if (CD3D9Renderer::CV_r_VolumetricFog != 0 && rd->m_RP.m_nPassGroupID == EFSLIST_FOG_VOLUME) { // calculate depth bounds of FogVolume. // reusing light depth bounds code from CDeferredShading::GetLightDepthBounds(). // This is not optimal for a box. Matrix34 temp = m_matWSInv.GetInverted(); AABB aabbInObj(1.0f); AABB aabbInWS = AABB::CreateTransformedAABB(temp, aabbInObj); float fRadius = aabbInWS.GetRadius(); Vec3 cameraFront = rd->GetViewParameters().vZ; cameraFront.Normalize(); Vec3 pBounds = cameraFront * fRadius; Vec3 pMax = m_center - pBounds; Vec3 pMin = m_center + pBounds; float fMinW, fMaxW; fMaxW = rd->GetViewParameters().WorldToCamZ(pMax); fMinW = rd->GetViewParameters().WorldToCamZ(pMin); fMinW = max(-fMinW, 0.000001f); fMaxW = max(-fMaxW, 0.000001f); // don't render when FogVolume is out of volume texture. Vec3 volumetricFogRaymarchEnd; gEnv->p3DEngine->GetGlobalParameter(E3DPARAM_VOLFOG2_CTRL_PARAMS, volumetricFogRaymarchEnd); if (fMinW > volumetricFogRaymarchEnd.x) { return false; } PROFILE_LABEL_SCOPE("FOG_VOLUME"); // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (0 == nPasses) { assert(0); return(false); } uint64 nFlagsShaderRTSave = rd->m_RP.m_FlagsShader_RT; rd->m_RP.m_FlagsShader_RT &= ~g_HWSR_MaskBit[HWSR_SAMPLE0]; if (m_affectsThisAreaOnly) { rd->m_RP.m_FlagsShader_RT |= g_HWSR_MaskBit[HWSR_SAMPLE0]; } // set volumetric fog injection pass ef->FXBeginPass(1); if (m_viewerInsideVolume) { rd->SetCullMode(R_CULL_FRONT); } else { rd->SetCullMode(R_CULL_BACK); } rd->FX_SetState(GS_BLSRC_ONE | GS_BLDST_ONE | GS_NODEPTHTEST); // set vs constants static CCryNameR invObjSpaceMatrixName("invObjSpaceMatrix"); ef->FXSetVSFloat(invObjSpaceMatrixName, (const Vec4*) &m_matWSInv.m00, 3); ef->FXSetPSFloat(invObjSpaceMatrixName, (const Vec4*) &m_matWSInv.m00, 3); const Vec4 cEyePosVec(m_eyePosInWS, !m_viewerInsideVolume ? 1 : 0); static CCryNameR eyePosInWSName("eyePosInWS"); ef->FXSetVSFloat(eyePosInWSName, &cEyePosVec, 1); const Vec4 cNearCutoffVec(m_nearCutoff, m_nearCutoff, m_nearCutoff, m_nearCutoff); static CCryNameR nearCutoffName("nearCutoff"); ef->FXSetVSFloat(nearCutoffName, &cNearCutoffVec, 1); // set ps constants const Vec4 cFogColVec(m_fogColor.r, m_fogColor.g, m_fogColor.b, 0); static CCryNameR fogColorName("fogColor"); ef->FXSetPSFloat(fogColorName, &cFogColVec, 1); float globalDensity = m_globalDensity * 0.1f;// scale density to volumetric fog. const Vec4 cGlobalDensityVec(globalDensity, 1.44269502f * globalDensity, m_noiseElapsedTime, 0); static CCryNameR globalDensityName("globalDensity"); ef->FXSetPSFloat(globalDensityName, &cGlobalDensityVec, 1); const Vec4 cDensityOffsetVec(m_densityOffset, m_densityOffset, m_densityOffset, m_densityOffset); static CCryNameR densityOffsetName("densityOffset"); ef->FXSetPSFloat(densityOffsetName, &cDensityOffsetVec, 1); uint32 nData = m_stencilRef + 1;// first ref value is reserved, see CDeferredShading::PrepareClipVolumeData function. const Vec4 cHeigthFallOffBasePointVec(m_heightFallOffBasePoint, *alias_cast<float*>(&nData)); static CCryNameR heightFallOffBasePointName("heightFallOffBasePoint"); ef->FXSetPSFloat(heightFallOffBasePointName, &cHeigthFallOffBasePointVec, 1); const Vec4 cHeightFallOffDirScaledVec(m_heightFallOffDirScaled * 0.015625f, 0); // scale fall off ramp to volumetric fog. static CCryNameR heightFallOffDirScaledName("heightFallOffDirScaled"); ef->FXSetPSFloat(heightFallOffDirScaledName, &cHeightFallOffDirScaledVec, 1); const Vec4 cOutsideSoftEdgesLerpVec(m_softEdgesLerp.x, m_softEdgesLerp.y, 0, 0); static CCryNameR outsideSoftEdgesLerpName("outsideSoftEdgesLerp"); ef->FXSetPSFloat(outsideSoftEdgesLerpName, &cOutsideSoftEdgesLerpVec, 1); const Vec4 cEyePosInWSVec(m_eyePosInWS, 0); ef->FXSetPSFloat(eyePosInWSName, &cEyePosInWSVec, 1); const Vec4 cEyePosInOSVec(m_eyePosInOS, 0); static CCryNameR eyePosInOSName("eyePosInOS"); ef->FXSetPSFloat(eyePosInOSName, &cEyePosInOSVec, 1); const Vec4 cEyePosInOSx2Vec(2.0f * m_eyePosInOS, 0); static CCryNameR eyePosInOSx2Name("eyePosInOSx2"); ef->FXSetPSFloat(eyePosInOSx2Name, &cEyePosInOSx2Vec, 1); float softEdgeLerp = (m_softEdgesLerp.x > 0.0f) ? m_softEdgesLerp.x : 0.0001f; const Vec4 cFogVolumePos(m_center, 1.0f / softEdgeLerp); static CCryNameR fogVolumePosName("fogVolumePos"); ef->FXSetPSFloat(fogVolumePosName, &cFogVolumePos, 1); float rampDist = m_rampParams.y - m_rampParams.x; rampDist = rampDist < 0.1f ? 0.1f : rampDist; float invRampDist = 1.0f / rampDist; const Vec4 cRampParams(invRampDist, -m_rampParams.x* invRampDist, m_rampParams.z, -m_rampParams.z + 1.0f); static CCryNameR rampParamsName("rampParams"); ef->FXSetPSFloat(rampParamsName, &cRampParams, 1); const float normalizeFactor = (1.0f / (1.0f + 0.5f)); const Vec4 cWindOffset(m_windOffset.x, m_windOffset.y, m_windOffset.z, m_noiseScale* normalizeFactor); static CCryNameR windOffsetName("windOffset"); ef->FXSetPSFloat(windOffsetName, &cWindOffset, 1); const Vec4 cNoiseFreq(m_noiseFreq.x, m_noiseFreq.y, m_noiseFreq.z, m_noiseOffset); static CCryNameR noiseFreqName("noiseFreq"); ef->FXSetPSFloat(noiseFreqName, &cNoiseFreq, 1); // find minimum and maximum affected slices const int slicesPerInstance = 28; const int depthMaxCount = CTexture::s_ptexVolumetricFogDensity->GetDepth(); static CCryNameR sliceBounds("sliceBounds"); Vec4 vSliceBounds(fMinW, fMaxW, slicesPerInstance, 0.0f); ef->FXSetGSFloat(sliceBounds, &vSliceBounds, 1); // commit all render changes rd->FX_Commit(); // set vertex declaration and streams of skydome if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F))) { // define bounding box geometry const uint32 c_numBBVertices(8); SVF_P3F_C4B_T2F bbVertices[ c_numBBVertices ] = { { Vec3(m_localAABB.min.x, m_localAABB.min.y, m_localAABB.min.z) }, { Vec3(m_localAABB.min.x, m_localAABB.max.y, m_localAABB.min.z) }, { Vec3(m_localAABB.max.x, m_localAABB.max.y, m_localAABB.min.z) }, { Vec3(m_localAABB.max.x, m_localAABB.min.y, m_localAABB.min.z) }, { Vec3(m_localAABB.min.x, m_localAABB.min.y, m_localAABB.max.z) }, { Vec3(m_localAABB.min.x, m_localAABB.max.y, m_localAABB.max.z) }, { Vec3(m_localAABB.max.x, m_localAABB.max.y, m_localAABB.max.z) }, { Vec3(m_localAABB.max.x, m_localAABB.min.y, m_localAABB.max.z) } }; const uint32 c_numBBIndices(36); static const uint16 bbIndices[ c_numBBIndices ] = { 0, 1, 2, 0, 2, 3, 7, 6, 5, 7, 5, 4, 3, 2, 6, 3, 6, 7, 4, 5, 1, 4, 1, 0, 1, 5, 6, 1, 6, 2, 4, 0, 3, 4, 3, 7 }; // copy vertices into dynamic VB TempDynVB<SVF_P3F_C4B_T2F>::CreateFillAndBind(bbVertices, c_numBBVertices, 0); // copy indices into dynamic IB TempDynIB16::CreateFillAndBind(bbIndices, c_numBBIndices); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); // use instanced draw for rendering multiple slices at once int instanceCount = (depthMaxCount / slicesPerInstance) + ((depthMaxCount % slicesPerInstance) != 0 ? 1 : 0); rd->FX_DrawIndexedPrimitive(eptTriangleList, 0, 0, instanceCount, 0, c_numBBIndices, true); } ef->FXEndPass(); ef->FXEnd(); rd->m_RP.m_FlagsShader_RT = nFlagsShaderRTSave; return true; } PROFILE_LABEL_SCOPE("FOG_VOLUME"); // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (0 == nPasses) { assert(0); return(false); } ef->FXBeginPass(0); if (m_viewerInsideVolume) { rd->SetCullMode(R_CULL_FRONT); int nState = GS_COLMASK_RGB | GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA; nState |= m_nearCutoff ? 0 : GS_NODEPTHTEST; rd->FX_SetState(nState); } else { rd->SetCullMode(R_CULL_BACK); rd->FX_SetState(GS_COLMASK_RGB | GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); } // set vs constants static CCryNameR invObjSpaceMatrixName("invObjSpaceMatrix"); ef->FXSetVSFloat(invObjSpaceMatrixName, (const Vec4*) &m_matWSInv.m00, 3); const Vec4 cEyePosVec(m_eyePosInWS, !m_viewerInsideVolume ? 1 : 0); static CCryNameR eyePosInWSName("eyePosInWS"); ef->FXSetVSFloat(eyePosInWSName, &cEyePosVec, 1); const Vec4 cEyePosInOSVec(m_eyePosInOS, 0); static CCryNameR eyePosInOSName("eyePosInOS"); ef->FXSetVSFloat(eyePosInOSName, &cEyePosInOSVec, 1); const Vec4 cNearCutoffVec(m_nearCutoff, m_nearCutoff, m_nearCutoff, m_nearCutoff); static CCryNameR nearCutoffName("nearCutoff"); ef->FXSetVSFloat(nearCutoffName, &cNearCutoffVec, 1); // set ps constants const Vec4 cFogColVec(m_fogColor.r, m_fogColor.g, m_fogColor.b, 0); static CCryNameR fogColorName("fogColor"); ef->FXSetPSFloat(fogColorName, &cFogColVec, 1); const Vec4 cGlobalDensityVec(m_globalDensity, 1.44269502f * m_globalDensity, 0, 0); static CCryNameR globalDensityName("globalDensity"); ef->FXSetPSFloat(globalDensityName, &cGlobalDensityVec, 1); const Vec4 cDensityOffsetVec(m_densityOffset, m_densityOffset, m_densityOffset, m_densityOffset); static CCryNameR densityOffsetName("densityOffset"); ef->FXSetPSFloat(densityOffsetName, &cDensityOffsetVec, 1); const Vec4 cHeigthFallOffBasePointVec(m_heightFallOffBasePoint, 0); static CCryNameR heightFallOffBasePointName("heightFallOffBasePoint"); ef->FXSetPSFloat(heightFallOffBasePointName, &cHeigthFallOffBasePointVec, 1); const Vec4 cHeightFallOffDirScaledVec(m_heightFallOffDirScaled, 0); static CCryNameR heightFallOffDirScaledName("heightFallOffDirScaled"); ef->FXSetPSFloat(heightFallOffDirScaledName, &cHeightFallOffDirScaledVec, 1); const Vec4 cOutsideSoftEdgesLerpVec(m_softEdgesLerp.x, m_softEdgesLerp.y, 0, 0); static CCryNameR outsideSoftEdgesLerpName("outsideSoftEdgesLerp"); ef->FXSetPSFloat(outsideSoftEdgesLerpName, &cOutsideSoftEdgesLerpVec, 1); const Vec4 cEyePosInWSVec(m_eyePosInWS, 0); ef->FXSetPSFloat(eyePosInWSName, &cEyePosInWSVec, 1); const Vec4 cEyePosInOSx2Vec(2.0f * m_eyePosInOS, 0); static CCryNameR eyePosInOSx2Name("eyePosInOSx2"); ef->FXSetPSFloat(eyePosInOSx2Name, &cEyePosInOSx2Vec, 1); // commit all render changes rd->FX_Commit(); // set vertex declaration and streams of skydome if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F))) { // define bounding box geometry const uint32 c_numBBVertices(8); SVF_P3F_C4B_T2F bbVertices[ c_numBBVertices ] = { { Vec3(m_localAABB.min.x, m_localAABB.min.y, m_localAABB.min.z) }, { Vec3(m_localAABB.min.x, m_localAABB.max.y, m_localAABB.min.z) }, { Vec3(m_localAABB.max.x, m_localAABB.max.y, m_localAABB.min.z) }, { Vec3(m_localAABB.max.x, m_localAABB.min.y, m_localAABB.min.z) }, { Vec3(m_localAABB.min.x, m_localAABB.min.y, m_localAABB.max.z) }, { Vec3(m_localAABB.min.x, m_localAABB.max.y, m_localAABB.max.z) }, { Vec3(m_localAABB.max.x, m_localAABB.max.y, m_localAABB.max.z) }, { Vec3(m_localAABB.max.x, m_localAABB.min.y, m_localAABB.max.z) } }; const uint32 c_numBBIndices(36); static const uint16 bbIndices[ c_numBBIndices ] = { 0, 1, 2, 0, 2, 3, 7, 6, 5, 7, 5, 4, 3, 2, 6, 3, 6, 7, 4, 5, 1, 4, 1, 0, 1, 5, 6, 1, 6, 2, 4, 0, 3, 4, 3, 7 }; // copy vertices into dynamic VB TempDynVB<SVF_P3F_C4B_T2F>::CreateFillAndBind(bbVertices, c_numBBVertices, 0); // copy indices into dynamic IB TempDynIB16::CreateFillAndBind(bbIndices, c_numBBIndices); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); // draw skydome rd->FX_DrawIndexedPrimitive(eptTriangleList, 0, 0, c_numBBVertices, 0, c_numBBIndices); } ef->FXEndPass(); ef->FXEnd(); return(true); } bool CREVolumeObject::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd(gcpRendD3D); I3DEngine* p3DEngine(gEnv->p3DEngine); uint32 nFlagsPS2 = rd->m_RP.m_PersFlags2; rd->m_RP.m_PersFlags2 &= ~(RBPF2_COMMIT_PF | RBPF2_COMMIT_CM); // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (!nPasses) { return false; } ef->FXBeginPass(0); if (m_nearPlaneIntersectsVolume) { rd->SetCullMode(R_CULL_FRONT); rd->FX_SetState(GS_COLMASK_RGB | GS_NODEPTHTEST | GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); } else { rd->SetCullMode(R_CULL_BACK); rd->FX_SetState(GS_COLMASK_RGB | GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); } // set vs constants static CCryNameR invObjSpaceMatrixName("invObjSpaceMatrix"); ef->FXSetVSFloat(invObjSpaceMatrixName, (const Vec4*) &m_matInv.m00, 3); const Vec4 cEyePosVec(m_eyePosInWS, 0); static CCryNameR eyePosInWSName("eyePosInWS"); ef->FXSetVSFloat(eyePosInWSName, &cEyePosVec, 1); const Vec4 cViewerOutsideVec(!m_viewerInsideVolume ? 1 : 0, m_nearPlaneIntersectsVolume ? 1 : 0, 0, 0); static CCryNameR viewerIsOutsideName("viewerIsOutside"); ef->FXSetVSFloat(viewerIsOutsideName, &cViewerOutsideVec, 1); const Vec4 cEyePosInOSVec(m_eyePosInOS, 0); static CCryNameR eyePosInOSName("eyePosInOS"); ef->FXSetVSFloat(eyePosInOSName, &cEyePosInOSVec, 1); // set ps constants const Vec4 cEyePosInWSVec(m_eyePosInWS, 0); ef->FXSetPSFloat(eyePosInWSName, &cEyePosInWSVec, 1); ColorF specColor(1, 1, 1, 1); ColorF diffColor(1, 1, 1, 1); CShaderResources* pRes(rd->m_RP.m_pShaderResources); if (pRes && pRes->HasLMConstants()) { specColor = pRes->GetColorValue(EFTT_SPECULAR); diffColor = pRes->GetColorValue(EFTT_DIFFUSE); } Vec3 cloudShadingMultipliers; p3DEngine->GetGlobalParameter(E3DPARAM_CLOUDSHADING_MULTIPLIERS, cloudShadingMultipliers); Vec3 brightColor(p3DEngine->GetSunColor() * cloudShadingMultipliers.x); brightColor = brightColor.CompMul(Vec3(specColor.r, specColor.g, specColor.b)); { static CCryNameR darkColorName("darkColor"); const Vec4 data(0, 0, 0, m_alpha); ef->FXSetPSFloat(darkColorName, &data, 1); } { static CCryNameR brightColorName("brightColor"); const Vec4 data(brightColor, m_alpha); ef->FXSetPSFloat(brightColorName, &data, 1); } const Vec4 cVolumeTraceStartPlane(m_volumeTraceStartPlane.n, m_volumeTraceStartPlane.d); static CCryNameR volumeTraceStartPlaneName("volumeTraceStartPlane"); ef->FXSetPSFloat(volumeTraceStartPlaneName, &cVolumeTraceStartPlane, 1); const Vec4 cScaleConsts(m_scale, 0, 0, 0); static CCryNameR scaleConstsName("scaleConsts"); ef->FXSetPSFloat(scaleConstsName, &cScaleConsts, 1); // TODO: optimize shader and remove need to pass inv obj space matrix ef->FXSetPSFloat(invObjSpaceMatrixName, (const Vec4*) &m_matInv.m00, 3); // commit all render changes rd->FX_Commit(); // set vertex declaration and streams if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F))) { CRenderMesh* pHullMesh = static_cast<CRenderMesh*>(m_pHullMesh.get()); // set vertex and index buffer pHullMesh->CheckUpdate(0); size_t vbOffset(0); size_t ibOffset(0); D3DBuffer* pVB = rd->m_DevBufMan.GetD3D(pHullMesh->_GetVBStream(VSF_GENERAL), &vbOffset); D3DBuffer* pIB = rd->m_DevBufMan.GetD3D(pHullMesh->_GetIBStream(), &ibOffset); assert(pVB); assert(pIB); if (!pVB || !pIB) { return false; } HRESULT hr(S_OK); hr = rd->FX_SetVStream(0, pVB, vbOffset, pHullMesh->GetStreamStride(VSF_GENERAL)); hr = rd->FX_SetIStream(pIB, ibOffset, (sizeof(vtx_idx) == 2 ? Index16 : Index32)); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); rd->FX_DrawIndexedPrimitive(pHullMesh->_GetPrimitiveType(), 0, 0, pHullMesh->_GetNumVerts(), 0, pHullMesh->_GetNumInds()); } ef->FXEndPass(); ef->FXEnd(); rd->FX_ResetPipe(); rd->m_RP.m_PersFlags2 = nFlagsPS2; return true; } #if !defined(EXCLUDE_DOCUMENTATION_PURPOSE) bool CREPrismObject::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd(gcpRendD3D); // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (!nPasses) { return false; } ef->FXBeginPass(0); // commit all render changes // rd->FX_Commit(); static SVF_P3F_C4B_T2F pScreenQuad[] = { { Vec3(0, 0, 0), { {0} }, Vec2(0, 0) }, { Vec3(0, 1, 0), { {0} }, Vec2(0, 1) }, { Vec3(1, 0, 0), { {0} }, Vec2(1, 0) }, { Vec3(1, 1, 0), { {0} }, Vec2(1, 1) }, }; pScreenQuad[0].xyz = Vec3(0, 0, 0); pScreenQuad[1].xyz = Vec3(0, 1, 0); pScreenQuad[2].xyz = Vec3(1, 0, 0); pScreenQuad[3].xyz = Vec3(1, 1, 0); CVertexBuffer strip(pScreenQuad, eVF_P3F_C4B_T2F); gcpRendD3D->DrawPrimitivesInternal(&strip, 4, eptTriangleStrip); ef->FXEndPass(); ef->FXEnd(); return true; } #endif // EXCLUDE_DOCUMENTATION_PURPOSE bool CREWaterVolume::mfDraw(CShader* ef, SShaderPass* sfm) { assert(m_pParams); if (!m_pParams) { return false; } CD3D9Renderer* rd(gcpRendD3D); IF (ef->m_eShaderType != eST_Water, 0) { #if !defined(_RELEASE) // CryWarning(VALIDATOR_MODULE_RENDERER, VALIDATOR_ERROR, "Incorrect shader set for water / water fog volume"); #endif return false; } //@NOTE: CV_r_watercaustics will be removed when the infinite ocean component feature toggle is removed. bool bCaustics = CRenderer::CV_r_watercaustics && CRenderer::CV_r_watervolumecaustics && m_pParams->m_caustics && (-m_pParams->m_fogPlane.d >= 1.0f); // unfortunately packing to RG8 limits us to heights over 1 meter, so we just disable if volume goes below. // Don't render caustics pass unless needed. if ((rd->m_RP.m_nBatchFilter & FB_WATER_CAUSTIC) && !bCaustics) { return false; } uint64 nFlagsShaderRTSave = gcpRendD3D->m_RP.m_FlagsShader_RT; rd->m_RP.m_FlagsShader_RT &= ~(g_HWSR_MaskBit[HWSR_SAMPLE0] | g_HWSR_MaskBit[HWSR_SAMPLE5]); const bool renderFogShadowWater = (CRenderer::CV_r_FogShadowsWater > 0) && (m_pParams->m_fogShadowing > 0.01f); Vec4 volFogShadowRange(0, 0, clamp_tpl(m_pParams->m_fogShadowing, 0.0f, 1.0f), 1.0f - clamp_tpl(m_pParams->m_fogShadowing, 0.0f, 1.0f)); #if defined(VOLUMETRIC_FOG_SHADOWS) const bool renderFogShadow = gcpRendD3D->m_bVolFogShadowsEnabled; { Vec3 volFogShadowRangeP; gEnv->p3DEngine->GetGlobalParameter(E3DPARAM_VOLFOG_SHADOW_RANGE, volFogShadowRangeP); volFogShadowRangeP.x = clamp_tpl(volFogShadowRangeP.x, 0.01f, 1.0f); volFogShadowRange.x = volFogShadowRangeP.x; volFogShadowRange.y = volFogShadowRangeP.y; } if (renderFogShadow) { gcpRendD3D->m_RP.m_FlagsShader_RT |= g_HWSR_MaskBit[HWSR_SAMPLE5]; } if (!renderFogShadowWater) // set up forward shadows in case they will not be set up below { rd->FX_SetupShadowsForTransp(); } #endif if (renderFogShadowWater) { rd->FX_SetupShadowsForTransp(); gcpRendD3D->m_RP.m_FlagsShader_RT |= g_HWSR_MaskBit[HWSR_SAMPLE0]; } Matrix44A origMatProj; Matrix44A origMatView; origMatProj.SetIdentity(); origMatView.SetIdentity(); if (!m_drawWaterSurface && m_pParams->m_viewerInsideVolume) { // set projection matrix for full screen quad origMatProj = rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matProj; Matrix44A* m = &rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matProj; mathMatrixOrthoOffCenterLH(m, -1, 1, -1, 1, -1, 1); if (SRendItem::m_RecurseLevel[rd->m_RP.m_nProcessThreadID] <= 0) { const SRenderTileInfo* rti = rd->GetRenderTileInfo(); if (rti->nGridSizeX > 1.f || rti->nGridSizeY > 1.f) { // shift and scale viewport m->m00 *= rti->nGridSizeX; m->m11 *= rti->nGridSizeY; m->m30 = -((rti->nGridSizeX - 1.f) - rti->nPosX * 2.0f); m->m31 = ((rti->nGridSizeY - 1.f) - rti->nPosY * 2.0f); } } // set view matrix to identity origMatView = rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matView; rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matView.SetIdentity(); } // render uint32 nPasses(0); ef->FXBegin(&nPasses, 0); if (0 == nPasses) { // reset matrices rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matView = origMatView; rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matProj = origMatProj; return false; } ef->FXBeginPass(0); // set ps constants if (!m_drawWaterSurface || m_drawFastPath && !m_pParams->m_viewerInsideVolume) { if (!m_pOceanParams) { // fog color & density const Vec3 col = m_pParams->m_fogColorAffectedBySun ? m_pParams->m_fogColor.CompMul(gEnv->p3DEngine->GetSunColor()) : m_pParams->m_fogColor; const Vec4 fogColorDensity(col, 1.44269502f * m_pParams->m_fogDensity); // log2(e) = 1.44269502 static CCryNameR Param1Name("cFogColorDensity"); ef->FXSetPSFloat(Param1Name, &fogColorDensity, 1); } else { // fog color & density Vec4 fogColorDensity(m_pOceanParams->m_fogColor.CompMul(gEnv->p3DEngine->GetSunColor()), 1.44269502f * m_pOceanParams->m_fogDensity); // log2(e) = 1.44269502 static CCryNameR Param1Name("cFogColorDensity"); ef->FXSetPSFloat(Param1Name, &fogColorDensity, 1); // fog color shallow & water level Vec4 fogColorShallowWaterLevel(m_pOceanParams->m_fogColorShallow.CompMul(gEnv->p3DEngine->GetSunColor()), -m_pParams->m_fogPlane.d); static CCryNameR Param2Name("cFogColorShallowWaterLevel"); ef->FXSetPSFloat(Param2Name, &fogColorShallowWaterLevel, 1); if (m_pParams->m_viewerInsideVolume) { // under water in-scattering constant term = exp2( -fogDensity * ( waterLevel - cameraPos.z) ) float c(expf(-m_pOceanParams->m_fogDensity * (-m_pParams->m_fogPlane.d - rd->GetCamera().GetPosition().z))); Vec4 underWaterInScatterConst(c, 0, 0, 0); static CCryNameR Param3Name("cUnderWaterInScatterConst"); ef->FXSetPSFloat(Param3Name, &underWaterInScatterConst, 1); } } Vec4 fogPlane(m_pParams->m_fogPlane.n.x, m_pParams->m_fogPlane.n.y, m_pParams->m_fogPlane.n.z, m_pParams->m_fogPlane.d); static CCryNameR Param4Name("cFogPlane"); ef->FXSetPSFloat(Param4Name, &fogPlane, 1); if (m_pParams->m_viewerInsideVolume) { Vec4 perpDist(m_pParams->m_fogPlane | rd->GetViewParameters().vOrigin, 0, 0, 0); static CCryNameR Param5Name("cPerpDist"); ef->FXSetPSFloat(Param5Name, &perpDist, 1); } } // Disable fog when inside volume or when not using fast path - could assign custom RT flag for this instead if (m_drawFastPath && m_pParams->m_viewerInsideVolume || !m_drawFastPath && m_drawWaterSurface) { // fog color & density const Vec4 fogColorDensity(0, 0, 0, 0); static CCryNameR Param1Name("cFogColorDensity"); ef->FXSetPSFloat(Param1Name, &fogColorDensity, 1); } { static CCryNameR pszParamBBoxMin("vBBoxMin"); static CCryNameR pszParamBBoxMax("vBBoxMax"); const Vec4 vBBoxMin(m_pParams->m_WSBBox.min, 1.0f); const Vec4 vBBoxMax(m_pParams->m_WSBBox.max, 1.0f); ef->FXSetPSFloat(pszParamBBoxMin, &vBBoxMin, 1); ef->FXSetPSFloat(pszParamBBoxMax, &vBBoxMax, 1); } // set vs constants Vec4 viewerColorToWaterPlane(m_pParams->m_viewerCloseToWaterPlane && m_pParams->m_viewerCloseToWaterVolume ? 0.0f : 1.0f, m_pParams->m_viewerCloseToWaterVolume ? 2.0f * 2.0f : 0.0f, 0.0f, 0.0f); static CCryNameR Param6Name("cViewerColorToWaterPlane"); ef->FXSetVSFloat(Param6Name, &viewerColorToWaterPlane, 1); if (bCaustics) { Vec4 pCausticsParams = Vec4(0.0f /* Not used */, m_pParams->m_causticIntensity, m_pParams->m_causticTiling, m_pParams->m_causticHeight); static CCryNameR m_pCausticParams("vCausticParams"); ef->FXSetPSFloat(m_pCausticParams, &pCausticsParams, 1); } static CCryNameR volFogShadowRangeN("volFogShadowRange"); ef->FXSetPSFloat(volFogShadowRangeN, &volFogShadowRange, 1); if (renderFogShadowWater) { //set world basis float maskRTWidth = float(rd->GetWidth()); float maskRTHeight = float(rd->GetHeight()); Vec4 vScreenScale(1.0f / maskRTWidth, 1.0f / maskRTHeight, 0.0f, 0.0f); Vec4r vWBasisX, vWBasisY, vWBasisZ, vCamPos; Vec4 vParamValue, vMag; CShadowUtils::ProjectScreenToWorldExpansionBasis(rd->m_IdentityMatrix, rd->GetCamera(), Vec2(rd->m_TemporalJitterClipSpace.x, rd->m_TemporalJitterClipSpace.y), maskRTWidth, maskRTHeight, vWBasisX, vWBasisY, vWBasisZ, vCamPos, true, NULL); Vec4 vWorldBasisX = vWBasisX; Vec4 vWorldBasisY = vWBasisY; Vec4 vWorldBasisZ = vWBasisZ; Vec4 vCameraPos = vCamPos; static CCryNameR m_pScreenScale("ScreenScale"); static CCryNameR m_pCamPos("vCamPos"); static CCryNameR m_pWBasisX("vWBasisX"); static CCryNameR m_pWBasisY("vWBasisY"); static CCryNameR m_pWBasisZ("vWBasisZ"); ef->FXSetPSFloat(m_pScreenScale, &vScreenScale, 1); ef->FXSetPSFloat(m_pCamPos, &vCameraPos, 1); ef->FXSetPSFloat(m_pWBasisX, &vWorldBasisX, 1); ef->FXSetPSFloat(m_pWBasisY, &vWorldBasisY, 1); ef->FXSetPSFloat(m_pWBasisZ, &vWorldBasisZ, 1); } #if defined(VOLUMETRIC_FOG_SHADOWS) if (renderFogShadow) { Vec3 volFogShadowDarkeningP; gEnv->p3DEngine->GetGlobalParameter(E3DPARAM_VOLFOG_SHADOW_DARKENING, volFogShadowDarkeningP); Vec4 volFogShadowDarkening(volFogShadowDarkeningP, 0); static CCryNameR volFogShadowDarkeningN("volFogShadowDarkening"); ef->FXSetPSFloat(volFogShadowDarkeningN, &volFogShadowDarkening, 1); const float aSun = (1.0f - clamp_tpl(volFogShadowDarkeningP.y, 0.0f, 1.0f)) * 1.0f; const float bSun = 1.0f - aSun; const float aAmb = (1.0f - clamp_tpl(volFogShadowDarkeningP.z, 0.0f, 1.0f)) * 0.4f; const float bAmb = 1.0f - aAmb; Vec4 volFogShadowDarkeningSunAmb(aSun, bSun, aAmb, bAmb); static CCryNameR volFogShadowDarkeningSunAmbN("volFogShadowDarkeningSunAmb"); ef->FXSetPSFloat(volFogShadowDarkeningSunAmbN, &volFogShadowDarkeningSunAmb, 1); } #endif if (m_drawWaterSurface || !m_pParams->m_viewerInsideVolume) { // copy vertices into dynamic VB TempDynVB<SVF_P3F_C4B_T2F>::CreateFillAndBind(m_pParams->m_pVertices, m_pParams->m_numVertices, 0); // copy indices into dynamic IB TempDynIB16::CreateFillAndBind(m_pParams->m_pIndices, m_pParams->m_numIndices); // set vertex declaration if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F))) { // commit all render changes rd->FX_Commit(); // draw eRenderPrimitiveType eType = eptTriangleList; if (CHWShader_D3D::s_pCurInstHS) { eType = ept3ControlPointPatchList; } rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); rd->FX_DrawIndexedPrimitive(eType, 0, 0, m_pParams->m_numVertices, 0, m_pParams->m_numIndices); } } else { // copy vertices into dynamic VB TempDynVB<SVF_P3F_T3F> vb(gcpRendD3D); vb.Allocate(4); SVF_P3F_T3F* pVB = vb.Lock(); Vec3 coords[8]; rd->GetViewParameters().CalcVerts(coords); pVB[0].p.x = -1; pVB[0].p.y = 1; pVB[0].p.z = 0.5f; pVB[0].st = coords[5] - coords[1]; pVB[1].p.x = 1; pVB[1].p.y = 1; pVB[1].p.z = 0.5f; pVB[1].st = coords[4] - coords[0]; pVB[2].p.x = -1; pVB[2].p.y = -1; pVB[2].p.z = 0.5f; pVB[2].st = coords[6] - coords[2]; pVB[3].p.x = 1; pVB[3].p.y = -1; pVB[3].p.z = 0.5f; pVB[3].st = coords[7] - coords[3]; vb.Unlock(); vb.Bind(0); vb.Release(); // set vertex declaration if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F_T3F))) { // commit all render changes rd->FX_Commit(); rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); rd->FX_DrawPrimitive(eptTriangleStrip, 0, 4); } // reset matrices rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matView = origMatView; rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_matProj = origMatProj; } ef->FXEndPass(); ef->FXEnd(); gcpRendD3D->m_RP.m_FlagsShader_RT = nFlagsShaderRTSave; return true; } void CREWaterOcean::Create(uint32 nVerticesCount, SVF_P3F_C4B_T2F* pVertices, uint32 nIndicesCount, const void* pIndices, uint32 nIndexSizeof) { if (!nVerticesCount || !pVertices || !nIndicesCount || !pIndices || (nIndexSizeof != 2 && nIndexSizeof != 4)) { return; } CD3D9Renderer* rd(gcpRendD3D); ReleaseOcean(); m_nVerticesCount = nVerticesCount; m_nIndicesCount = nIndicesCount; m_nIndexSizeof = nIndexSizeof; HRESULT hr(S_OK); ////////////////////////////////////////////////////////////////////////////////////////////////// // Create vertex buffer ////////////////////////////////////////////////////////////////////////////////////////////////// { D3DBuffer* pVertexBuffer = 0; D3D11_BUFFER_DESC BufDesc; SVF_P3F_C4B_T2F* dst = 0; uint32 size = nVerticesCount * sizeof(SVF_P3F_C4B_T2F); BufDesc.ByteWidth = size; BufDesc.Usage = D3D11_USAGE_DEFAULT; BufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; BufDesc.CPUAccessFlags = 0; BufDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA pInitData; pInitData.pSysMem = pVertices; pInitData.SysMemPitch = 0; pInitData.SysMemSlicePitch = 0; gcpRendD3D->m_DevMan.CreateD3D11Buffer(&BufDesc, &pInitData, &pVertexBuffer, "OceanMesh"); m_pVertices = pVertexBuffer; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Create index buffer ////////////////////////////////////////////////////////////////////////////////////////////////// { D3DBuffer* pIndexBuffer = 0; const uint32 size = nIndicesCount * m_nIndexSizeof; D3D11_BUFFER_DESC BufDesc; BufDesc.ByteWidth = size; BufDesc.Usage = D3D11_USAGE_DEFAULT; BufDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; BufDesc.CPUAccessFlags = 0; BufDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA pInitData; pInitData.pSysMem = pIndices; pInitData.SysMemPitch = 0; pInitData.SysMemSlicePitch = 0; gcpRendD3D->m_DevMan.CreateD3D11Buffer(&BufDesc, &pInitData, &pIndexBuffer, "OceanMesh"); m_pIndices = pIndexBuffer; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// void CREWaterOcean::FrameUpdate() { static bool bInitialize = true; if (bInitialize) { WaterSimMgr()->Create(1.0, 1.0f, 1.0f); bInitialize = false; } const int nGridSize = 64; // Update Vertex Texture if (!CTexture::IsTextureExist(CTexture::s_ptexWaterOcean)) { CTexture::s_ptexWaterOcean->Create2DTexture(nGridSize, nGridSize, 1, FT_DONT_RELEASE | FT_NOMIPS | FT_STAGE_UPLOAD, 0, eTF_R32G32B32A32F, eTF_R32G32B32A32F); } CTexture* pTexture = CTexture::s_ptexWaterOcean; // Copy data.. if (CTexture::IsTextureExist(pTexture)) { Vec4* pDispGrid = WaterSimMgr()->GetDisplaceGrid(); if (pDispGrid == nullptr) { return; } const auto oceanData = gEnv->p3DEngine->GetOceanAnimationParams(); const float fUpdateTime = 0.125f * gEnv->pTimer->GetCurrTime() * oceanData.fWavesSpeed; int nFrameID = gRenDev->GetFrameID(); void* pRawPtr = NULL; WaterSimMgr()->Update(nFrameID, fUpdateTime, false, pRawPtr); uint32 pitch = 4 * sizeof(f32) * nGridSize; uint32 width = nGridSize; uint32 height = nGridSize; STALL_PROFILER("update subresource") CDeviceTexture * pDevTex = pTexture->GetDevTexture(); pDevTex->UploadFromStagingResource(0, [=](void* pData, uint32 rowPitch, uint32 slicePitch) { cryMemcpy(pData, pDispGrid, 4 * width * height * sizeof(f32)); return true; }); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// void CREWaterOcean::ReleaseOcean() { ID3D11Buffer* pVertices = (ID3D11Buffer*)m_pVertices; ID3D11Buffer* pIndices = (ID3D11Buffer*)m_pIndices; gcpRendD3D->m_DevMan.ReleaseD3D11Buffer(pVertices); m_pVertices = nullptr; gcpRendD3D->m_DevMan.ReleaseD3D11Buffer(pIndices); m_pIndices = nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// bool CREWaterOcean::mfDraw(CShader* ef, SShaderPass* sfm) { if (!m_nVerticesCount || !m_nIndicesCount || !m_pVertices || !m_pIndices) { return false; } CD3D9Renderer* rd(gcpRendD3D); if (CTexture::s_ptexWaterOcean) { CTexture::s_ptexWaterOcean->SetFilterMode(FILTER_LINEAR); CTexture::s_ptexWaterOcean->SetClampingMode(0, 0, 1); CTexture::s_ptexWaterOcean->UpdateTexStates(); } if (CTexture::s_ptexWaterRipplesDDN) { CTexture::s_ptexWaterRipplesDDN->SetVertexTexture(true); CTexture::s_ptexWaterRipplesDDN->SetFilterMode(FILTER_LINEAR); CTexture::s_ptexWaterRipplesDDN->SetClampingMode(0, 0, 1); CTexture::s_ptexWaterRipplesDDN->UpdateTexStates(); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// uint64 nFlagsShaderRTprev = rd->m_RP.m_FlagsShader_RT; uint32 nFlagsPF2prev = rd->m_RP.m_PersFlags2; rd->m_RP.m_PersFlags2 &= ~(RBPF2_COMMIT_PF | RBPF2_COMMIT_CM); // render uint32 nPasses(0); // set streams HRESULT hr(S_OK); STexStageInfo pPrevTexState0 = CTexture::s_TexStages[0]; STexStageInfo pPrevTexState1 = CTexture::s_TexStages[1]; STexState pState(FILTER_BILINEAR, false); const int texStateID(CTexture::GetTexState(pState)); N3DEngineCommon::SOceanInfo& OceanInfo = gRenDev->m_p3DEngineCommon.m_OceanInfo; Vec4& pParams = OceanInfo.m_vMeshParams; uint32 nPrevStateOr = rd->m_RP.m_StateOr; uint32 nPrevStateAnd = rd->m_RP.m_StateAnd; ef->FXSetTechnique("Water"); ef->FXBegin(&nPasses, 0); if (0 == nPasses) { return false; } if (gRenDev->GetViewParameters().vOrigin.z > OceanInfo.m_fWaterLevel) { rd->m_RP.m_StateAnd |= GS_DEPTHFUNC_MASK; rd->m_RP.m_StateOr |= GS_DEPTHWRITE | GS_DEPTHFUNC_LEQUAL; } ef->FXBeginPass(0); if (CTexture::s_ptexWaterOcean) { CTexture::s_ptexWaterOcean->SetVertexTexture(true); CTexture::s_ptexWaterOcean->Apply(0, texStateID); CTexture::s_ptexWaterOcean->SetVertexTexture(false); } if (CTexture::s_ptexWaterRipplesDDN) { CTexture::s_ptexWaterRipplesDDN->SetVertexTexture(true); CTexture::s_ptexWaterRipplesDDN->Apply(1, texStateID); CTexture::s_ptexWaterRipplesDDN->SetVertexTexture(false); } hr = rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F); if (!FAILED(hr)) { // commit all render changes rd->FX_Commit(); hr = rd->FX_SetVStream(0, m_pVertices, 0, sizeof(SVF_P3F_C4B_T2F)); hr = rd->FX_SetIStream(m_pIndices, 0, (m_nIndexSizeof == 2 ? Index16 : Index32)); eRenderPrimitiveType eType = rd->m_bUseWaterTessHW ? eptTriangleList : eptTriangleStrip; #ifdef WATER_TESSELLATION_RENDERER if (CHWShader_D3D::s_pCurInstHS) { eType = ept3ControlPointPatchList; } #endif rd->GetPerInstanceConstantBufferPool().SetConstantBuffer(rd->m_RP.m_RIs[0][0]); rd->FX_DrawIndexedPrimitive(eType, 0, 0, m_nVerticesCount, 0, m_nIndicesCount); } ef->FXEndPass(); ef->FXEnd(); rd->m_RP.m_StateOr = nPrevStateOr; rd->m_RP.m_StateAnd = nPrevStateAnd; CTexture::s_TexStages[0] = pPrevTexState0; CTexture::s_TexStages[1] = pPrevTexState1; gcpRendD3D->FX_ResetPipe(); rd->m_RP.m_FlagsShader_RT = nFlagsShaderRTprev; rd->m_RP.m_PersFlags2 = nFlagsPF2prev; return true; } //========================================================================================= CREOcclusionQuery::~CREOcclusionQuery() { mfReset(); } void CREOcclusionQuery::mfReset() { ID3D11Query* pVizQuery = (ID3D11Query*)m_nOcclusionID; SAFE_RELEASE(pVizQuery); m_nOcclusionID = 0; m_nDrawFrame = 0; m_nCheckFrame = 0; m_nVisSamples = 0; m_bSucceeded = false; } uint32 CREOcclusionQuery::m_nQueriesPerFrameCounter = 0; uint32 CREOcclusionQuery::m_nReadResultNowCounter = 0; uint32 CREOcclusionQuery::m_nReadResultTryCounter = 0; bool CREOcclusionQuery::mfDraw(CShader* ef, SShaderPass* sfm) { PROFILE_FRAME(CREOcclusionQuery::mfDraw); CD3D9Renderer* r = gcpRendD3D; gRenDev->m_cEF.mfRefreshSystemShader("OcclusionTest", CShaderMan::s_ShaderOcclTest); CShader* pSh = CShaderMan::s_ShaderOcclTest; if (!pSh || pSh->m_HWTechniques.empty()) { return false; } if (!(r->m_Features & RFT_OCCLUSIONTEST)) { // If not supported m_nVisSamples = r->GetWidth() * r->GetHeight(); return true; } int w = r->GetWidth(); int h = r->GetHeight(); if (!m_nOcclusionID) { HRESULT hr; ID3D11Query* pVizQuery = NULL; D3D11_QUERY_DESC qdesc; qdesc.MiscFlags = 0; //D3D11_QUERY_MISC_PREDICATEHINT; qdesc.Query = D3D11_QUERY_OCCLUSION; hr = r->GetDevice().CreateQuery(&qdesc, &pVizQuery); if (pVizQuery) { m_nOcclusionID = (UINT_PTR)pVizQuery; } } int nFrame = r->GetFrameID(); if (!m_nDrawFrame) // only allow queries update, if finished already with previous query { // draw test box if (m_nOcclusionID) { D3DQuery* pVizQuery = (D3DQuery*)m_nOcclusionID; r->GetDeviceContext().Begin(pVizQuery); const t_arrDeferredMeshIndBuff& arrDeferredInds = r->GetDeferredUnitBoxIndexBuffer(); const t_arrDeferredMeshVertBuff& arrDeferredVerts = r->GetDeferredUnitBoxVertexBuffer(); //allocate vertices TempDynVB<SVF_P3F_C4B_T2F>::CreateFillAndBind(&arrDeferredVerts[0], arrDeferredVerts.size(), 0); //allocate indices TempDynIB16::CreateFillAndBind(&arrDeferredInds[0], arrDeferredInds.size()); Matrix44A origMatView = r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_matView; Matrix34 mat; mat.SetIdentity(); mat.SetScale(m_vBoxMax - m_vBoxMin, m_vBoxMin); const Matrix44 cTransPosed = Matrix44(mat).GetTransposed(); r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_matView = cTransPosed * r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_matView; uint32 nPasses; pSh->FXSetTechnique("General"); pSh->FXBegin(&nPasses, FEF_DONTSETTEXTURES | FEF_DONTSETSTATES); pSh->FXBeginPass(0); int nPersFlagsSave = r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_PersFlags; int nObjFlagsSave = r->m_RP.m_ObjFlags; CRenderObject* pCurObjectSave = r->m_RP.m_pCurObject; CShader* pShaderSave = r->m_RP.m_pShader; SShaderTechnique* pCurTechniqueSave = r->m_RP.m_pCurTechnique; if (r->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F) == S_OK) { r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_PersFlags &= ~RBPF_FP_DIRTY; r->m_RP.m_pCurObject = r->m_RP.m_pIdendityRenderObject; r->m_RP.m_pShader = pSh; r->m_RP.m_pCurTechnique = pSh->m_HWTechniques[0]; r->FX_SetState(GS_COLMASK_NONE | GS_DEPTHFUNC_LEQUAL); r->SetCullMode(R_CULL_NONE); r->FX_Commit(); r->FX_DrawIndexedPrimitive(eptTriangleList, 0, 0, arrDeferredVerts.size(), 0, arrDeferredInds.size()); } pSh->FXEndPass(); pSh->FXEnd(); r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_matView = origMatView; r->m_RP.m_TI[r->m_RP.m_nProcessThreadID].m_PersFlags = nPersFlagsSave; r->m_RP.m_ObjFlags = nObjFlagsSave; r->m_RP.m_pCurObject = pCurObjectSave; r->m_RP.m_pShader = pShaderSave; r->m_RP.m_pCurTechnique = pCurTechniqueSave; r->GetDeviceContext().End(pVizQuery); CREOcclusionQuery::m_nQueriesPerFrameCounter++; m_nDrawFrame = 1; } m_bSucceeded = false; // m_nDrawFrame = nFrame; } return true; } bool CREOcclusionQuery::mfReadResult_Now() { int nFrame = gcpRendD3D->GetFrameID(); ID3D11Query* pVizQuery = (ID3D11Query*)m_nOcclusionID; if (pVizQuery) { HRESULT hRes = S_FALSE; while (hRes == S_FALSE) { hRes = gcpRendD3D->GetDeviceContext().GetData(pVizQuery, (void*) &m_nVisSamples, sizeof(uint64), 0); } if (hRes == S_OK) { m_nDrawFrame = 0; m_nCheckFrame = nFrame; } } m_nReadResultNowCounter++; m_bSucceeded = (m_nCheckFrame == nFrame); return m_bSucceeded; } bool CREOcclusionQuery::mfReadResult_Try(uint32 nDefaultNumSamples) { return gRenDev->m_pRT->RC_OC_ReadResult_Try(nDefaultNumSamples, this); } bool CREOcclusionQuery::RT_ReadResult_Try(uint32 nDefaultNumSamples) { PROFILE_FRAME(CREOcclusionQuery::mfReadResult_Try); int nFrame = gcpRendD3D->GetFrameID(); ID3D11Query* pVizQuery = (ID3D11Query*)m_nOcclusionID; if (pVizQuery) { HRESULT hRes = S_FALSE; hRes = gcpRendD3D->GetDeviceContext().GetData(pVizQuery, (void*) &m_nVisSamples, sizeof(uint64), D3D11_ASYNC_GETDATA_DONOTFLUSH); if (hRes == S_OK) { m_nDrawFrame = 0; m_nCheckFrame = nFrame; } } m_nReadResultTryCounter++; #ifdef DO_RENDERLOG if (!m_nVisSamples) { if (CRenderer::CV_r_log) { gRenDev->Logv(SRendItem::m_RecurseLevel[gRenDev->m_RP.m_nProcessThreadID], "OcclusionQuery: Water is not visible\n"); } } else { if (CRenderer::CV_r_log) { gRenDev->Logv(SRendItem::m_RecurseLevel[gRenDev->m_RP.m_nProcessThreadID], "OcclusionQuery: Water is visible (%d samples)\n", m_nVisSamples); } } #endif m_bSucceeded = (m_nCheckFrame == nFrame); return m_bSucceeded; } //=================================================================================== static float sInterpolate(float& pprev, float& prev, float& next, float& nnext, float ppweight, float pweight, float nweight, float nnweight) { return pprev * ppweight + prev * pweight + next * nweight + nnext * nnweight; } static float sSpline(float x) { float fX = fabsf(x); if (fX > 2.0f) { return 0; } if (fX > 1.0f) { return (2.0f - fX) * (2.0f - fX) * (2.0f - fX) / 6.0f; } return 2.0f / 3.0f - fX * fX + 0.5f * fX * fX * fX; } void CRenderMesh::DrawImmediately() { CD3D9Renderer* rd = gcpRendD3D; HRESULT hr = rd->FX_SetVertexDeclaration(0, _GetVertexFormat()); if (FAILED(hr)) { CRY_ASSERT(!"CRenderMesh::DrawImmediately failed"); return; } // set vertex and index buffer CheckUpdate(0); size_t vbOffset(0); size_t ibOffset(0); D3DBuffer* pVB = rd->m_DevBufMan.GetD3D(_GetVBStream(VSF_GENERAL), &vbOffset); D3DBuffer* pIB = rd->m_DevBufMan.GetD3D(_GetIBStream(), &ibOffset); assert(pVB); assert(pIB); if (!pVB || !pIB) { assert(!"CRenderMesh::DrawImmediately failed"); return; } hr = rd->FX_SetVStream(0, pVB, vbOffset, GetStreamStride(VSF_GENERAL)); hr = rd->FX_SetIStream(pIB, ibOffset, (sizeof(vtx_idx) == 2 ? Index16 : Index32)); // draw indexed mesh rd->FX_DrawIndexedPrimitive(_GetPrimitiveType(), 0, 0, _GetNumVerts(), 0, _GetNumInds()); } //========================================================================================= bool CREParticle::mfPreDraw(SShaderPass* sl) { CD3D9Renderer* rd(gcpRendD3D); SRenderPipeline& rp(rd->m_RP); if (rp.m_RendNumVerts) { #if !defined(_RELEASE) if (!(rp.m_FlagsPerFlush & RBSI_EXTERN_VMEM_BUFFERS)) { __debugbreak(); } #endif assert(rp.m_pExternalVertexBuffer); assert(rp.m_pExternalIndexBuffer); // bind out external vertex/index buffer to use those directly, the client code has to set them up correctly rp.m_pExternalVertexBuffer->Bind(0, 0, rp.m_StreamStride); rp.m_pExternalIndexBuffer->Bind(0); // adjust the first index to render from as well as // other renderer stats rp.m_FirstIndex = rp.m_nExternalVertexBufferFirstIndex; rp.m_FirstVertex = rp.m_nExternalVertexBufferFirstVertex; rp.m_PS[rp.m_nProcessThreadID].m_DynMeshUpdateBytes += rp.m_StreamStride * rp.m_RendNumVerts; rp.m_PS[rp.m_nProcessThreadID].m_DynMeshUpdateBytes += rp.m_RendNumIndices * sizeof(uint16); // clear external video memory buffer flag rp.m_FlagsPerFlush &= ~RBSI_EXTERN_VMEM_BUFFERS; rp.m_nExternalVertexBufferFirstIndex = 0; rp.m_nExternalVertexBufferFirstVertex = 0; rp.m_pExternalVertexBuffer = NULL; rp.m_pExternalIndexBuffer = NULL; /* Confetti: David Srour * Following is a hack! For some reason, a stream remains in slot 1 which causes * a crash on iOS. * Either DX is smart enough not to use that slot or DX path cleans up slot 1 properly. * TODO: investigate further */ #ifdef CRY_USE_METAL rd->FX_SetVStream(1, NULL, 0, 0); #endif // Confetti end: David Srour } return true; } bool CREParticle::mfDraw(CShader* ef, SShaderPass* sl) { CD3D9Renderer* rd(gcpRendD3D); SRenderPipeline& rp(rd->m_RP); rd->FX_Commit(); if (!CHWShader_D3D::s_pCurInstVS && !CHWShader_D3D::s_pCurInstPS || CHWShader_D3D::s_pCurInstPS->m_bFallback || CHWShader_D3D::s_pCurInstVS->m_bFallback) { return false; } // rendered to volume texture if (rd->m_RP.m_nPassGroupID == EFSLIST_FOG_VOLUME) { if (CD3D9Renderer::CV_r_VolumetricFog != 0 && (rp.m_pCurTechnique && !(rp.m_pCurTechnique->m_Flags & FHF_USE_HULL_SHADER) && (rp.m_pCurTechnique->m_Flags & FHF_USE_GEOMETRY_SHADER))) { // TODO: calculate depth bounds of all patticles. // don't render when all particles are out of fog density texture. if (rp.m_RendNumIndices == 0) { // Draw a quad or octagon, with instanced sprite data int nInstanceVerts = (rp.m_ObjFlags & FOB_OCTAGONAL) ? 8 : 4; rd->FX_DrawPrimitive(eptTriangleStrip, rp.m_FirstVertex, rp.m_RendNumVerts, nInstanceVerts); } else { // Draw non-instanced tri list rd->FX_DrawIndexedPrimitive(eptTriangleList, rp.m_FirstVertex, 0, rp.m_RendNumVerts, rp.m_FirstIndex, rp.m_RendNumIndices); } return true; } return false; } if (rp.m_pCurTechnique && (rp.m_pCurTechnique->m_Flags & FHF_USE_HULL_SHADER)) { // Tessellated shader if (!CHWShader_D3D::s_pCurInstHS && !CHWShader_D3D::s_pCurInstDS || CHWShader_D3D::s_pCurInstHS->m_bFallback || CHWShader_D3D::s_pCurInstDS->m_bFallback) { return false; } if (rp.m_RendNumIndices == 0) { // Draw separated point sprites rd->FX_DrawPrimitive(ept1ControlPointPatchList, rp.m_FirstVertex, rp.m_RendNumVerts); } else { // Draw connected quads rd->FX_DrawIndexedPrimitive(ept4ControlPointPatchList, rp.m_FirstVertex, 0, rp.m_RendNumVerts, rp.m_FirstIndex, rp.m_RendNumIndices); } } else { if (rp.m_RendNumIndices == 0) { // Draw a quad or octagon, with instanced sprite data int nInstanceVerts = (rp.m_ObjFlags & FOB_OCTAGONAL) ? 8 : 4; rd->FX_DrawPrimitive(eptTriangleStrip, rp.m_FirstVertex, rp.m_RendNumVerts, nInstanceVerts); } else { // Draw non-instanced tri list rd->FX_DrawIndexedPrimitive(eptTriangleList, rp.m_FirstVertex, 0, rp.m_RendNumVerts, rp.m_FirstIndex, rp.m_RendNumIndices); } } return true; } //========================================================================================= bool CREParticleGPU::mfPreDraw(SShaderPass* sl) { // predraw is not called for customdraw/sky based render calls. return true; } bool CREParticleGPU::mfDraw(CShader* ef, SShaderPass* sl) { if (gRenDev->GetGPUParticleEngine() == 0) { return false; } gRenDev->GetGPUParticleEngine()->Render(m_instance, m_pass, m_shadowMode, m_cameraFOV, m_aspectRatio, m_isWireframeEnabled); return true; } //========================================================================================= bool CREHDRProcess::mfDraw(CShader* ef, SShaderPass* sfm) { CD3D9Renderer* rd = gcpRendD3D; if (!(rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_PersFlags & RBPF_HDR)) { return false; } assert(rd->m_RP.m_TI[rd->m_RP.m_nProcessThreadID].m_PersFlags & RBPF_HDR || rd->m_RP.m_CurState & GS_WIREFRAME); rd->FX_HDRPostProcessing(); return true; } bool CREBeam::mfDraw(CShader* ef, SShaderPass* sl) { CD3D9Renderer* rd = gcpRendD3D; int nThreadID = rd->m_RP.m_nProcessThreadID; if (SRendItem::m_RecurseLevel[nThreadID] != 0) { return false; } PROFILE_LABEL_SCOPE("LIGHT BEAM"); EShaderQuality nShaderQuality = (EShaderQuality)gcpRendD3D->EF_GetShaderQuality(eST_FX); ERenderQuality nRenderQuality = gRenDev->m_RP.m_eQuality; bool bLowSpecShafts = (nShaderQuality == eSQ_Low) || (nRenderQuality == eRQ_Low); STexState pState(FILTER_BILINEAR, true); const int texStateID(CTexture::GetTexState(pState)); STexState pStatePoint(FILTER_POINT, true); const int texStateIDPoint(CTexture::GetTexState(pStatePoint)); bool bViewerInsideCone = false; CTexture* pLowResRT = CTexture::s_ptexZTargetScaled2; // CTexture::s_ptexBackBufferScaled[1]; CTexture* pLowResRTDepth = CTexture::s_ptexDepthBufferQuarter; SDepthTexture D3dDepthSurface; SDepthTexture* pCurrDepthSurf = NULL; #if D3DRENDERRE_CPP_TRAIT_MFDRAW_SETDEPTHSURF // Depth surface nastiness if (CTexture::IsTextureExist(pLowResRTDepth)) { D3dDepthSurface.nWidth = pLowResRTDepth->GetWidth(); D3dDepthSurface.nHeight = pLowResRTDepth->GetHeight(); D3dDepthSurface.nFrameAccess = -1; D3dDepthSurface.bBusy = false; D3dDepthSurface.pTex = pLowResRTDepth; D3dDepthSurface.pSurf = pLowResRTDepth->GetDeviceDepthStencilSurf(); D3dDepthSurface.pTarget = pLowResRTDepth->GetDevTexture()->Get2DTexture(); pCurrDepthSurf = &D3dDepthSurface; } #endif CRenderObject* pObj = rd->m_RP.m_pCurObject; SRenderObjData* pOD = pObj->GetObjData(); uint16 nLightID = pOD->m_nLightID; SRenderLight* pDL = rd->EF_GetDeferredLightByID(nLightID); bool bCastsShadows = ((pDL->m_Flags & (DLF_CASTSHADOW_MAPS | DLF_PROJECT)) == (DLF_CASTSHADOW_MAPS | DLF_PROJECT)) ? true : false; const CRenderObject::SInstanceInfo& rInstInfo = pObj->m_II; Matrix34A objMatInv = rInstInfo.m_Matrix.GetInverted(); Matrix44A mLightProj, mLightView; CShadowUtils::GetCubemapFrustumForLight(pDL, 0, pDL->m_fLightFrustumAngle * 2.f, &mLightProj, &mLightView, true); Matrix44 projMat = mLightView * mLightProj; const CameraViewParameters& RCam = gRenDev->GetViewParameters(); float fLightAngle = pDL->m_fLightFrustumAngle; float fAngleCoeff = 1.0f / tan_tpl((90.0f - fLightAngle) * gf_PI / 180.0f); float fNear = pDL->m_fProjectorNearPlane; float fFar = pDL->m_fRadius; float fScaleNear = fNear * fAngleCoeff; float fScaleFar = fFar * fAngleCoeff; Vec3 vLightPos = pDL->m_Origin; Vec3 vAxis = rInstInfo.m_Matrix.GetColumn0(); float fSin, fCos; sincos_tpl(fLightAngle * gf_PI / 180.0f, &fSin, &fCos); Vec4 vLightParams = Vec4(fFar, fAngleCoeff, fNear, fFar); Vec4 vSphereParams = Vec4(vLightPos, fFar); Vec4 vConeParams = Vec4(vAxis, fCos); Vec4 pLightPos = Vec4(vLightPos, 1.0f); Vec4 cLightDiffuse = Vec4(pDL->m_Color.r, pDL->m_Color.g, pDL->m_Color.b, pDL->m_SpecMult); Vec3 vEye = RCam.vOrigin; Vec3 vCoords[9]; // Evaluate campos to near plane verts as a sphere. RCam.CalcVerts(vCoords); vCoords[4] = vEye; AABB camExtents(vCoords, 5); float fRadius = camExtents.GetRadius(); Vec3 vCentre = camExtents.GetCenter(); float fCosSq = fCos * fCos; Vec3 vVertToSphere = vCentre - vLightPos; Vec3 d = vVertToSphere + vAxis * (fRadius / fSin); float dSq = d.dot(d); float e = d.dot(vAxis); float eSq = e * e; if ((e > 0.0f) && (eSq >= (dSq * fCosSq))) { float fSinSq = fSin * fSin; dSq = vVertToSphere.dot(vVertToSphere); e = vVertToSphere.dot(vAxis); if ((e < (fFar + fRadius)) && (e > (fNear - fRadius))) // test capping planes { bViewerInsideCone = true; } } Vec4 cEyePosVec(vEye, !bViewerInsideCone ? 1 : 0); Vec4 vShadowCoords = Vec4(0.0f, 0.0f, 1.0f, 1.0f); CTexture* shadowTexture = nullptr; CTexture* projectedTexture = nullptr; if (bCastsShadows) { const ShadowMapFrustum& shadowFrustum = CShadowUtils::GetFirstFrustum(nLightID); if (shadowFrustum.bUseShadowsPool) { shadowTexture = CTexture::s_ptexRT_ShadowPool; float width = CTexture::s_ptexRT_ShadowPool->GetWidth(); float height = CTexture::s_ptexRT_ShadowPool->GetHeight(); vShadowCoords = Vec4(shadowFrustum.packX[0] / width, shadowFrustum.packY[0] / height, shadowFrustum.packWidth[0] / width, shadowFrustum.packHeight[0] / height); } } if (pDL->m_pLightImage) { projectedTexture = (CTexture*)pDL->m_pLightImage; } Vec4 sampleOffsets[5]; { const float tU = 1.0f / (float)pLowResRT->GetWidth(); const float tV = 1.0f / (float)pLowResRT->GetHeight(); sampleOffsets[0] = Vec4(0, 0, 0, 0); sampleOffsets[1] = Vec4(0, -tV, tU, tV); sampleOffsets[2] = Vec4(-tU, 0, -tU, tV); sampleOffsets[3] = Vec4(tU, 0, tU, -tV); sampleOffsets[4] = Vec4(0, tV, -tU, -tV); } Vec4 vMisc = Vec4(1.0f / (float)gcpRendD3D->m_nShadowPoolWidth, 1.0f / (float)gcpRendD3D->m_nShadowPoolHeight, 0.0f, 0.0f); const int ZPass = 2; // passes can be buggy, use manual ordering const int VolumetricPass = 1; const int FinalPass = 0; rd->m_RP.m_FlagsShader_RT &= ~(g_HWSR_MaskBit[HWSR_SAMPLE0] | g_HWSR_MaskBit[HWSR_SAMPLE1] | g_HWSR_MaskBit[HWSR_SAMPLE2] | g_HWSR_MaskBit[HWSR_SAMPLE3]); if (bCastsShadows) { rd->m_RP.m_FlagsShader_RT |= g_HWSR_MaskBit[HWSR_SAMPLE0]; } //Setup geometry const int nNumSides = BEAM_RE_CONE_SIDES; const uint32 c_numBBVertices(nNumSides * 2 + 2); SVF_P3F_C4B_T2F bbVertices[c_numBBVertices]; const uint32 c_numBBIndices((nNumSides) * 6 * 2); uint16 bbIndices[c_numBBIndices]; SetupGeometry(&bbVertices[0], &bbIndices[0], fAngleCoeff, fNear, fFar); // copy vertices into dynamic VB TempDynVB<SVF_P3F_C4B_T2F>::CreateFillAndBind(bbVertices, c_numBBVertices, 0); // copy indices into dynamic IB TempDynIB16::CreateFillAndBind(bbIndices, c_numBBIndices); uint32 nPasses = 0; ef->FXBegin(&nPasses, FEF_DONTSETSTATES); assert(nPasses == (ZPass + 1)); int nStartPass = (bViewerInsideCone || !pCurrDepthSurf) ? VolumetricPass : ZPass; for (int nCurPass = nStartPass; nCurPass > -1; nCurPass--) { ef->FXBeginPass(nCurPass); //set world basis float maskRTWidthL = pLowResRT->GetWidth(); float maskRTHeightL = pLowResRT->GetHeight(); float maskRTWidthH = rd->GetWidth(); float maskRTHeightH = rd->GetHeight(); Vec4 vScreenScale(1.0f / maskRTWidthL, 1.0f / maskRTHeightL, 1.0f / maskRTWidthH, 1.0f / maskRTHeightH); if (nCurPass == nStartPass && pLowResRT) { rd->FX_PushRenderTarget(0, pLowResRT, pCurrDepthSurf, -1, false, 1); rd->FX_SetColorDontCareActions(0, false, false); //Check gmem path for performance when using this pass. rd->FX_ClearTarget(pLowResRT, Clr_Transparent); rd->FX_ClearTarget(pCurrDepthSurf, CLEAR_ZBUFFER); } uint32 nState = (nCurPass == FinalPass) ? (GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA) : 0; if (bViewerInsideCone) { rd->SetCullMode(R_CULL_FRONT); } else { rd->SetCullMode(R_CULL_BACK); } if (bViewerInsideCone || !pCurrDepthSurf) { nState |= GS_NODEPTHTEST; } else { nState |= (nCurPass == ZPass) ? (GS_DEPTHWRITE | GS_COLMASK_NONE) : 0; } rd->FX_SetState(nState); // set vs constants if (nCurPass == VolumetricPass) { ef->FXSetVSFloat(m_eyePosInWSName, &cEyePosVec, 1); ef->FXSetPSFloat(m_eyePosInWSName, &cEyePosVec, 1); ef->FXSetPSFloat(m_projMatrixName, (const Vec4*)&projMat.m00, 4); ef->FXSetPSFloat(m_shadowCoordsName, (const Vec4*)&vShadowCoords, 1); ef->FXSetPSFloat(m_lightParamsName, &vLightParams, 1); ef->FXSetPSFloat(m_sphereParamsName, &vSphereParams, 1); ef->FXSetPSFloat(m_coneParamsName, &vConeParams, 1); ef->FXSetPSFloat(m_lightPosName, &pLightPos, 1); ef->FXSetPSFloat(m_miscOffsetsName, &vMisc, 1); } else if (nCurPass == FinalPass) { ef->FXSetPSFloat(m_sampleOffsetsName, &sampleOffsets[0], 5); } ef->FXSetPSFloat(m_lightDiffuseName, &cLightDiffuse, 1); ef->FXSetPSFloat(m_screenScaleName, &vScreenScale, 1); if (nCurPass == FinalPass && pLowResRT) { pLowResRT->Apply(7, texStateID); } if (projectedTexture) { projectedTexture->Apply(5, texStateID); } if (bCastsShadows && shadowTexture) { shadowTexture->Apply(6, texStateID); // bilinear is a hack, but looks better } //pShadowTex->Apply(6, texStateIDPoint); rd->m_RP.m_nCommitFlags |= FC_MATERIAL_PARAMS; // commit all render changes rd->FX_Commit(); // set vertex declaration and streams of skydome if (!FAILED(rd->FX_SetVertexDeclaration(0, eVF_P3F_C4B_T2F))) { // draw skydome rd->FX_DrawIndexedPrimitive(eptTriangleList, 0, 0, c_numBBVertices, 0, c_numBBIndices); } if ((nCurPass == VolumetricPass) && pLowResRT) { rd->FX_PopRenderTarget(0); } } return true; } bool CREGameEffect::mfDraw(CShader* ef, SShaderPass* sfm) { CRY_ASSERT_MESSAGE(gRenDev->m_pRT->IsRenderThread(), "Trying to render from wrong thread"); CRY_ASSERT(ef); CRY_ASSERT(sfm); if (m_pImpl) { #ifndef _RELEASE _smart_ptr<IMaterial> pMaterial = (gRenDev->m_RP.m_pCurObject) ? (gRenDev->m_RP.m_pCurObject->m_pCurrMaterial) : NULL; const char* pEffectName = (pMaterial) ? (PathUtil::GetFileName(pMaterial->GetName())) : "GameEffectRenderElement"; PROFILE_LABEL_SCOPE(pEffectName); #endif uint32 passCount = 0; bool successFlag = true; // Begin drawing ef->FXBegin(&passCount, 0); if (passCount > 0) { // Begin pass ef->FXBeginPass(0); // Draw element successFlag = m_pImpl->mfDraw(ef, sfm, gRenDev->m_RP.m_pCurObject); // End pass ef->FXEndPass(); } // End drawing ef->FXEnd(); return successFlag; } return false; } #if defined(USE_GEOM_CACHES) // Each call of CREGeomCache::mfDraw render *all* meshes that share the same material in the geom cache. See CGeomCacheRenderNode::Render bool CREGeomCache::mfDraw(CShader* ef, SShaderPass* sfm) { PROFILE_FRAME(CREGeomCache::mfDraw); const uint numMeshes = m_meshRenderData.size(); CD3D9Renderer* const pRenderer = gcpRendD3D; SRenderPipeline& rRP = pRenderer->m_RP; SThreadInfo& threadInfo = rRP.m_TI[rRP.m_nProcessThreadID]; CRenderObject* const pRenderObject = rRP.m_pCurObject; Matrix34A matrix = pRenderObject->m_II.m_Matrix; CHWShader_D3D* const pCurVS = (CHWShader_D3D*)sfm->m_VShader; const bool bIsShadowPass = (threadInfo.m_PersFlags & RBPF_SHADOWGEN) != 0; const CCamera& camera = bIsShadowPass ? rRP.m_ShadowInfo.m_pCurShadowFrustum->FrustumPlanes[rRP.m_ShadowInfo.m_nOmniLightSide] : gRenDev->GetCamera(); Matrix44A prevMatrix; CMotionBlur::GetPrevObjToWorldMat(rRP.m_pCurObject, prevMatrix); const uint64 oldFlagsShader_RT = rRP.m_FlagsShader_RT; uint64 flagsShader_RT = rRP.m_FlagsShader_RT; const int oldFlagsPerFlush = rRP.m_FlagsPerFlush; bool bResetVertexDecl = false; for (uint nMesh = 0; nMesh < numMeshes; ++nMesh) { const SMeshRenderData& meshData = m_meshRenderData[nMesh]; CRenderMesh* const pRenderMesh = static_cast<CRenderMesh*>(meshData.m_pRenderMesh.get()); const uint numInstances = meshData.m_instances.size(); if (pRenderMesh && numInstances > 0) { PROFILE_LABEL_SHADER(pRenderMesh->GetSourceName() ? pRenderMesh->GetSourceName() : "Unknown mesh-resource name"); const CRenderMesh* const pVertexContainer = pRenderMesh->_GetVertexContainer(); if (!pVertexContainer->_HasVBStream(VSF_GENERAL) || !pRenderMesh->_HasIBStream()) { // Should never happen. Video buffer is missing continue; } const bool bHasVelocityStream = pRenderMesh->_HasVBStream(VSF_VERTEX_VELOCITY); const bool bIsMotionBlurPass = (rRP.m_PersFlags2 & RBPF2_MOTIONBLURPASS) != 0; pRenderMesh->BindStreamsToRenderPipeline(); rRP.m_RendNumVerts = pRenderMesh->_GetNumVerts(); if (ef->m_HWTechniques.Num() && pRenderMesh->CanRender()) { const TRenderChunkArray& chunks = pRenderMesh->GetChunks(); const uint numChunks = chunks.size(); for (uint i = 0; i < numChunks; ++i) { const CRenderChunk& chunk = chunks[i]; if (chunk.m_nMatID != m_materialId) { continue; } rRP.m_FirstIndex = chunk.nFirstIndexId; rRP.m_RendNumIndices = chunk.nNumIndices; #if defined(HW_INSTANCING_ENABLED) && D3DRENDERRE_CPP_TRAIT_MFDRAW_USEINSTANCING const bool bUseInstancing = (CRenderer::CV_r_geominstancing != 0) && (numInstances > CRenderer::CV_r_GeomCacheInstanceThreshold); #else const bool bUseInstancing = false; #endif TempDynInstVB instVB(gcpRendD3D); uint numInstancesToDraw = 0; byte* __restrict pInstanceMatricesVB = NULL; // Note: Geom cache instancing is a horrible mess at the moment, because it re-uses // FX_DrawInstances which supports both constant based and attribute based instancing // and all platforms. // // This only sets up the data structures for D3D11 attribute based // instancing. Need to clean this up later and ideally use constant based instancing. const uint64 lastFlagsShader_RT = rRP.m_FlagsShader_RT; rRP.m_FlagsShader_RT = flagsShader_RT | (bUseInstancing ? g_HWSR_MaskBit[HWSR_INSTANCING_ATTR] : 0); if (lastFlagsShader_RT != rRP.m_FlagsShader_RT) { pCurVS->mfSet(bUseInstancing ? HWSF_INSTANCED : 0); } CHWShader_D3D::SHWSInstance* pVPInst = pCurVS->m_pCurInst; int32 nUsedAttr = 3, nInstAttrMask = 0; byte Attributes[32]; if (bUseInstancing) { pVPInst->GetInstancingAttribInfo(Attributes, nUsedAttr, nInstAttrMask); instVB.Allocate(numInstances, nUsedAttr * INST_PARAM_SIZE); pInstanceMatricesVB = (byte*)(instVB.Lock()); } const uint32 nStride = nUsedAttr * sizeof(float[4]); // Fill the stream 3 for per-instance data byte* pWalkData = pInstanceMatricesVB; for (uint nInstance = 0; nInstance < numInstances; ++nInstance) { const SMeshInstance& instance = meshData.m_instances[nInstance]; Matrix34A pieceMatrix = matrix * instance.m_matrix; AABB pieceWorldAABB; pieceWorldAABB.SetTransformedAABB(pieceMatrix, instance.m_aabb); if (!camera.IsAABBVisible_F(pieceWorldAABB)) { continue; } // Needs to be in this scope, because it's used by FX_DrawIndexedMesh Matrix44A prevPieceMatrix = prevMatrix * instance.m_prevMatrix; if (bIsMotionBlurPass) { const float fThreshold = 0.01f; if (bUseInstancing || (rRP.m_nBatchFilter & FB_Z) || !Matrix34::IsEquivalent(pieceMatrix, Matrix34(prevPieceMatrix), fThreshold) || bHasVelocityStream) { rRP.m_FlagsPerFlush |= RBSI_CUSTOM_PREVMATRIX; rRP.m_pPrevMatrix = &prevPieceMatrix; } else { // Don't draw pieces without any motion in motion blur pass continue; } } if (!bUseInstancing) { pRenderer->GetPerInstanceConstantBufferPool().UpdateConstantBuffer([&](void* mappedData) { *reinterpret_cast<Matrix34A*>(mappedData) = pieceMatrix; }, threadInfo.m_RealTime); pRenderObject->m_II.m_Matrix = pieceMatrix; pCurVS->UpdatePerInstanceConstantBuffer(); // Check if instancing messed with vertex declaration if (bResetVertexDecl) { pRenderer->FX_SetVertexDeclaration(rRP.m_FlagsStreams_Decl, rRP.m_CurVFormat); bResetVertexDecl = false; } pRenderer->FX_DrawIndexedMesh(pRenderMesh->_GetPrimitiveType()); } else { *reinterpret_cast<Matrix34A*>(pWalkData) = pieceMatrix; if (pVPInst->m_nParams_Inst >= 0) { SCGParamsGroup& Group = CGParamManager::s_Groups[pVPInst->m_nParams_Inst]; pCurVS->UpdatePerInstanceConstants(eHWSC_Vertex, Group.pParams, Group.nParams, pWalkData); } pWalkData += nStride; ++numInstancesToDraw; } } if (bUseInstancing) { instVB.Unlock(); instVB.Bind(3, nUsedAttr * INST_PARAM_SIZE); instVB.Release(); pCurVS->UpdatePerInstanceConstantBuffer(); pRenderer->FX_DrawInstances(ef, sfm, 0, 0, numInstancesToDraw - 1, nUsedAttr, pInstanceMatricesVB, nInstAttrMask, Attributes, 0); bResetVertexDecl = true; } } } } } // Reset matrix to original value for cases when render object gets reused pRenderObject->m_II.m_Matrix = matrix; rRP.m_FlagsShader_RT = oldFlagsShader_RT; rRP.m_FlagsPerFlush = oldFlagsPerFlush; return true; } #endif
36.582609
246
0.604975
[ "mesh", "geometry", "render", "object" ]
0e67daeffdaa857243a548d70e40dbbc9c30597c
2,257
cpp
C++
engine/src/common/pixelboost/animation/timeline/tween.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
6
2015-04-21T11:30:52.000Z
2020-04-29T00:10:04.000Z
engine/src/common/pixelboost/animation/timeline/tween.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
engine/src/common/pixelboost/animation/timeline/tween.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
#include "pixelboost/animation/timeline/tween.h" #include "pixelboost/debug/log.h" #include "pixelboost/graphics/message/color.h" #include "pixelboost/logic/message/transform.h" #include "pixelboost/logic/scene.h" using namespace pb; TimelineTweenPosition::TimelineTweenPosition(Entity* entity, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(entity, length, from, to, easing) { } TimelineTweenPosition::TimelineTweenPosition(Scene* scene, Uid entityId, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(scene, entityId, length, from, to, easing) { } void TimelineTweenPosition::OnTweenChanged(glm::vec3 value) { _Scene->SendMessage(_EntityId, SetPositionMessage(value)); } TimelineTweenRotate::TimelineTweenRotate(Entity* entity, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(entity, length, from, to, easing) { } TimelineTweenRotate::TimelineTweenRotate(Scene* scene, Uid entityId, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(scene, entityId, length, from, to, easing) { } void TimelineTweenRotate::OnTweenChanged(glm::vec3 value) { _Scene->SendMessage(_EntityId, SetRotationMessage(value)); } TimelineTweenScale::TimelineTweenScale(Entity* entity, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(entity, length, from, to, easing) { } TimelineTweenScale::TimelineTweenScale(Scene* scene, Uid entityId, float length, glm::vec3 from, glm::vec3 to, Easing easing) : TimelineTween(scene, entityId, length, from, to, easing) { } void TimelineTweenScale::OnTweenChanged(glm::vec3 value) { _Scene->SendMessage(_EntityId, SetScaleMessage(value)); } TimelineTweenColor::TimelineTweenColor(Entity* entity, float length, glm::vec4 from, glm::vec4 to, Easing easing) : TimelineTween(entity, length, from, to, easing) { } TimelineTweenColor::TimelineTweenColor(Scene* scene, Uid entityId, float length, glm::vec4 from, glm::vec4 to, Easing easing) : TimelineTween(scene, entityId, length, from, to, easing) { } void TimelineTweenColor::OnTweenChanged(glm::vec4 value) { _Scene->SendMessage(_EntityId, SetColorMessage(value)); }
29.697368
131
0.743022
[ "transform" ]
0e76fe2572abb4302d58f5bfb0788e8c5e468ee7
1,982
hpp
C++
cpp_jatko/2020_04_08/2020_04_08_assignment_1/henkilo.hpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
cpp_jatko/2020_04_08/2020_04_08_assignment_1/henkilo.hpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
cpp_jatko/2020_04_08/2020_04_08_assignment_1/henkilo.hpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> class Address { private: std::string street_address{}; std::string postal_code{}; std::string city{}; public: Address(); Address(const std::string&, const std::string&, const std::string&); ~Address(); const std::string getStreetAddress(); void setStreetAddress(const std::string&); const std::string getPostalCode(); void setPostalCode(const std::string&); const std::string getCity(); void setCity(const std::string&); const void printInfo(); }; class Person { private: std::string name; int age; Address address{}; public: Person(); Person(const std::string&, const int&); Person(const std::string&, const int&, const Address&); Person(const Person&); ~Person(); const std::string getName(); void setName(const std::string&); const int getAge(); void setAge(const int&); const Address getAddress(); void setAddress(const Address&); const void printPersonInfo(); }; class Student : public Person { private: std::string studentNumber; std::vector<std::string> completedCourses{}; int academicCredit; public: std::vector<std::string> getCompletedCourses(); void addCourse(const std::string&); const int getAcademicCredit(); void setAcademicCredit(const int); void addAcademicCredit(const int); const std::string getStudentNumber(); void setStudentNumber(const std::string&); void printInfo(); Student(); Student(const std::string&, const int&, const std::string&, const int&); Student(const Student&); ~Student(); }; class Teacher : public Person { private: std::string academicField; std::vector<std::string> courses{}; public: std::vector<std::string> getCourses(); void addCourse(const std::string&); void removeCourse(const std::string&); const std::string& getAcademicField(); void setAcademicField(const std::string&); void printInfo(); Teacher(); Teacher(const std::string&, const int&, const std::string&); Teacher(const Teacher&); ~Teacher(); };
20.22449
73
0.711403
[ "vector" ]
0e77e50b468e82625c9b76291fcb0a0b8caf8529
1,513
hpp
C++
indexer/altitude_loader.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
1
2022-02-18T17:26:50.000Z
2022-02-18T17:26:50.000Z
indexer/altitude_loader.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
indexer/altitude_loader.hpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
#pragma once #include "indexer/feature_altitude.hpp" #include "coding/memory_region.hpp" #include "geometry/point_with_altitude.hpp" #include <memory> #include <string> #include <vector> #include "3party/succinct/elias_fano.hpp" #include "3party/succinct/rs_bit_vector.hpp" class MwmValue; namespace feature { class AltitudeLoaderBase { public: explicit AltitudeLoaderBase(MwmValue const & mwmValue); /// \returns altitude of feature with |featureId|. All items of the returned vector are valid /// or the returned vector is empty. geometry::Altitudes GetAltitudes(uint32_t featureId, size_t pointCount); bool HasAltitudes() const; private: std::unique_ptr<CopiedMemoryRegion> m_altitudeAvailabilityRegion; std::unique_ptr<CopiedMemoryRegion> m_featureTableRegion; succinct::rs_bit_vector m_altitudeAvailability; succinct::elias_fano m_featureTable; std::unique_ptr<FilesContainerR::TReader> m_reader; AltitudeHeader m_header; std::string m_countryFileName; }; class AltitudeLoaderCached : public AltitudeLoaderBase { public: explicit AltitudeLoaderCached(MwmValue const & mwmValue) : AltitudeLoaderBase(mwmValue) { } /// \returns altitude of feature with |featureId|. All items of the returned vector are valid /// or the returned vector is empty. geometry::Altitudes const & GetAltitudes(uint32_t featureId, size_t pointCount); void ClearCache() { m_cache.clear(); } private: std::map<uint32_t, geometry::Altitudes> m_cache; }; } // namespace feature
25.216667
95
0.773298
[ "geometry", "vector" ]
0e7adfd5512c53dd7135d88a82281863bb8926dd
11,241
cc
C++
chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/webui/md_downloads/downloads_list_tracker_unittest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/md_downloads/downloads_list_tracker.h" #include <limits.h> #include <stdint.h> #include <memory> #include <vector> #include "base/files/file_path.h" #include "base/stl_util.h" #include "base/time/time.h" #include "chrome/browser/download/download_item_model.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/mock_download_item.h" #include "content/public/test/mock_download_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using content::DownloadItem; using content::MockDownloadItem; using DownloadVector = std::vector<DownloadItem*>; using testing::_; using testing::Return; namespace { uint64_t GetId(const base::Value& value) { const base::DictionaryValue* dict; CHECK(value.GetAsDictionary(&dict)); int id; CHECK(dict->GetInteger("id", &id)); CHECK_GE(id, 0); return static_cast<uint64_t>(id); } std::vector<uint64_t> GetIds(const base::Value& value) { std::vector<uint64_t> ids; const base::ListValue* list; if (value.GetAsList(&list)) { for (const auto& list_item : *list) ids.push_back(GetId(*list_item)); } else { ids.push_back(GetId(value)); } return ids; } int GetIndex(const base::Value* value) { CHECK(value); int index; CHECK(value->GetAsInteger(&index)); return index; } bool ShouldShowItem(const DownloadItem& item) { DownloadItemModel model(const_cast<DownloadItem*>(&item)); return model.ShouldShowInShelf(); } } // namespace // A test version of DownloadsListTracker. class TestDownloadsListTracker : public DownloadsListTracker { public: TestDownloadsListTracker(content::DownloadManager* manager, content::WebUI* web_ui) : DownloadsListTracker(manager, web_ui, base::Bind(&ShouldShowItem)) {} ~TestDownloadsListTracker() override {} using DownloadsListTracker::IsIncognito; using DownloadsListTracker::GetItemForTesting; using DownloadsListTracker::SetChunkSizeForTesting; protected: std::unique_ptr<base::DictionaryValue> CreateDownloadItemValue( content::DownloadItem* item) const override { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); CHECK_LE(item->GetId(), static_cast<uint64_t>(INT_MAX)); dict->SetInteger("id", item->GetId()); return dict; } }; // A fixture to test DownloadsListTracker. class DownloadsListTrackerTest : public testing::Test { public: DownloadsListTrackerTest() {} ~DownloadsListTrackerTest() override { for (auto* mock_item : mock_items_) testing::Mock::VerifyAndClear(mock_item); STLDeleteElements(&mock_items_); } // testing::Test: void SetUp() override { ON_CALL(manager_, GetBrowserContext()).WillByDefault(Return(&profile_)); ON_CALL(manager_, GetAllDownloads(_)).WillByDefault( testing::Invoke(this, &DownloadsListTrackerTest::GetAllDownloads)); } MockDownloadItem* CreateMock(uint64_t id, const base::Time& started) { MockDownloadItem* new_item = new testing::NiceMock<MockDownloadItem>(); mock_items_.push_back(new_item); ON_CALL(*new_item, GetId()).WillByDefault(Return(id)); ON_CALL(*new_item, GetStartTime()).WillByDefault(Return(started)); return new_item; } MockDownloadItem* CreateNextItem() { return CreateMock(mock_items_.size(), base::Time::UnixEpoch() + base::TimeDelta::FromHours(mock_items_.size())); } void CreateTracker() { tracker_.reset(new TestDownloadsListTracker(manager(), web_ui())); } TestingProfile* profile() { return &profile_; } content::DownloadManager* manager() { return &manager_; } content::TestWebUI* web_ui() { return &web_ui_; } TestDownloadsListTracker* tracker() { return tracker_.get(); } private: void GetAllDownloads(DownloadVector* result) { for (auto* mock_item : mock_items_) result->push_back(mock_item); } // NOTE: The initialization order of these members matters. content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; testing::NiceMock<content::MockDownloadManager> manager_; content::TestWebUI web_ui_; std::unique_ptr<TestDownloadsListTracker> tracker_; std::vector<MockDownloadItem*> mock_items_; }; TEST_F(DownloadsListTrackerTest, SetSearchTerms) { CreateTracker(); const base::ListValue empty_terms; EXPECT_FALSE(tracker()->SetSearchTerms(empty_terms)); base::ListValue search_terms; search_terms.AppendString("search"); EXPECT_TRUE(tracker()->SetSearchTerms(search_terms)); EXPECT_FALSE(tracker()->SetSearchTerms(search_terms)); EXPECT_TRUE(tracker()->SetSearchTerms(empty_terms)); // Notifying the page is left up to the handler in this case. EXPECT_TRUE(web_ui()->call_data().empty()); } TEST_F(DownloadsListTrackerTest, StartCallsInsertItems) { DownloadItem* first_item = CreateNextItem(); CreateTracker(); ASSERT_TRUE(tracker()->GetItemForTesting(0)); EXPECT_TRUE(web_ui()->call_data().empty()); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(0, GetIndex(web_ui()->call_data()[0]->arg1())); std::vector<uint64_t> ids = GetIds(*web_ui()->call_data()[0]->arg2()); ASSERT_FALSE(ids.empty()); EXPECT_EQ(first_item->GetId(), ids[0]); } // The page is in a loading state until it gets an insertItems call. Ensure that // happens even without downloads. TEST_F(DownloadsListTrackerTest, EmptyGetAllItemsStillCallsInsertItems) { CreateTracker(); ASSERT_FALSE(tracker()->GetItemForTesting(0)); ASSERT_TRUE(web_ui()->call_data().empty()); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); ASSERT_TRUE(web_ui()->call_data()[0]->arg2()); EXPECT_TRUE(GetIds(*web_ui()->call_data()[0]->arg2()).empty()); } TEST_F(DownloadsListTrackerTest, OnDownloadCreatedCallsInsertItems) { CreateTracker(); tracker()->StartAndSendChunk(); web_ui()->ClearTrackedCalls(); ASSERT_FALSE(tracker()->GetItemForTesting(0)); DownloadItem* first_item = CreateNextItem(); tracker()->OnDownloadCreated(manager(), first_item); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(0, GetIndex(web_ui()->call_data()[0]->arg1())); std::vector<uint64_t> ids = GetIds(*web_ui()->call_data()[0]->arg2()); ASSERT_FALSE(ids.empty()); EXPECT_EQ(first_item->GetId(), ids[0]); } TEST_F(DownloadsListTrackerTest, OnDownloadRemovedCallsRemoveItem) { DownloadItem* first_item = CreateNextItem(); CreateTracker(); tracker()->StartAndSendChunk(); web_ui()->ClearTrackedCalls(); EXPECT_TRUE(tracker()->GetItemForTesting(0)); tracker()->OnDownloadRemoved(manager(), first_item); EXPECT_FALSE(tracker()->GetItemForTesting(0)); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.removeItem", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(0, GetIndex(web_ui()->call_data()[0]->arg1())); } TEST_F(DownloadsListTrackerTest, OnDownloadUpdatedCallsRemoveItem) { DownloadItem* first_item = CreateNextItem(); CreateTracker(); tracker()->StartAndSendChunk(); web_ui()->ClearTrackedCalls(); EXPECT_TRUE(tracker()->GetItemForTesting(0)); DownloadItemModel(first_item).SetShouldShowInShelf(false); tracker()->OnDownloadUpdated(manager(), first_item); EXPECT_FALSE(tracker()->GetItemForTesting(0)); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.removeItem", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(0, GetIndex(web_ui()->call_data()[0]->arg1())); } TEST_F(DownloadsListTrackerTest, StartExcludesHiddenItems) { DownloadItem* first_item = CreateNextItem(); DownloadItemModel(first_item).SetShouldShowInShelf(false); CreateTracker(); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_TRUE(GetIds(*web_ui()->call_data()[0]->arg2()).empty()); } TEST_F(DownloadsListTrackerTest, Incognito) { testing::NiceMock<content::MockDownloadManager> incognito_manager; ON_CALL(incognito_manager, GetBrowserContext()).WillByDefault(Return( TestingProfile::Builder().BuildIncognito(profile()))); MockDownloadItem item; EXPECT_CALL(item, GetId()).WillRepeatedly(Return(0)); ON_CALL(incognito_manager, GetDownload(0)).WillByDefault(Return(&item)); TestDownloadsListTracker tracker(&incognito_manager, web_ui()); EXPECT_TRUE(tracker.IsIncognito(item)); } TEST_F(DownloadsListTrackerTest, OnlySendSomeItems) { CreateNextItem(); CreateNextItem(); CreateNextItem(); CreateNextItem(); CreateNextItem(); CreateTracker(); tracker()->SetChunkSizeForTesting(3); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(0, GetIndex(web_ui()->call_data()[0]->arg1())); EXPECT_EQ(3u, GetIds(*web_ui()->call_data()[0]->arg2()).size()); tracker()->StartAndSendChunk(); ASSERT_GE(2u, web_ui()->call_data().size()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[1]->function_name()); EXPECT_EQ(3, GetIndex(web_ui()->call_data()[1]->arg1())); EXPECT_EQ(2u, GetIds(*web_ui()->call_data()[1]->arg2()).size()); } TEST_F(DownloadsListTrackerTest, IgnoreUnsentItemUpdates) { DownloadItem* unsent_item = CreateNextItem(); CreateNextItem(); CreateTracker(); tracker()->SetChunkSizeForTesting(1); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(1u, GetIds(*web_ui()->call_data()[0]->arg2()).size()); tracker()->OnDownloadUpdated(manager(), unsent_item); EXPECT_EQ(1u, web_ui()->call_data().size()); } TEST_F(DownloadsListTrackerTest, IgnoreUnsentItemRemovals) { DownloadItem* unsent_item = CreateNextItem(); CreateNextItem(); CreateTracker(); tracker()->SetChunkSizeForTesting(1); tracker()->StartAndSendChunk(); ASSERT_FALSE(web_ui()->call_data().empty()); EXPECT_EQ("downloads.Manager.insertItems", web_ui()->call_data()[0]->function_name()); EXPECT_EQ(1u, GetIds(*web_ui()->call_data()[0]->arg2()).size()); DownloadItemModel(unsent_item).SetShouldShowInShelf(false); tracker()->OnDownloadUpdated(manager(), unsent_item); EXPECT_EQ(1u, web_ui()->call_data().size()); DownloadItemModel(unsent_item).SetShouldShowInShelf(true); tracker()->OnDownloadUpdated(manager(), unsent_item); EXPECT_EQ(1u, web_ui()->call_data().size()); }
31.311978
80
0.722089
[ "vector", "model" ]
0e7e6d56ec3f3ab166bdd2691f831781fcc23266
3,039
cc
C++
src/tools/fs_tool_main.cc
ishine/deepx_core
a71fa4b5fec5cf5d83da04cbb9ee437d0c8b6e05
[ "BSD-2-Clause" ]
309
2021-03-24T03:00:19.000Z
2022-03-31T16:17:46.000Z
src/tools/fs_tool_main.cc
kiminh/deepx_core
928d248ef26c9a5b48e34ff6a66761f94cd4be72
[ "BSD-2-Clause" ]
4
2021-03-30T01:46:32.000Z
2021-04-06T12:22:18.000Z
src/tools/fs_tool_main.cc
kiminh/deepx_core
928d248ef26c9a5b48e34ff6a66761f94cd4be72
[ "BSD-2-Clause" ]
45
2021-03-29T06:12:17.000Z
2022-03-04T05:19:46.000Z
// Copyright 2019 the deepx authors. // Author: Yafei Zhang (kimmyzhang@tencent.com) // #include <deepx_core/common/stream.h> #include <deepx_core/dx_log.h> #include <gflags/gflags.h> #include <iostream> #include <string> namespace deepx_core { namespace { void ShowHelp() { std::cout << "Usage:" << std::endl; std::cout << " text [file]" << std::endl; std::cout << " testwr [file]" << std::endl; std::cout << " ls [path]" << std::endl; std::cout << " lsr [path]" << std::endl; } int real_main(int argc, char** argv) { if (argc < 3) { ShowHelp(); return 1; } std::string action = argv[1]; std::string path = argv[2]; if (action == "text") { AutoInputFileStream is; if (!is.Open(path)) { DXERROR("Failed to open: %s.", path.c_str()); return 1; } std::string line; while (GetLine(is, line)) { std::cout << line << std::endl; } } else if (action == "testwr") { AutoOutputFileStream os; if (!os.Open(path)) { DXERROR("Failed to open: %s.", path.c_str()); return 1; } for (int i = 0; i < 100; ++i) { std::string s = "This is the string " + std::to_string(i) + "."; os << s; } os.Close(); AutoInputFileStream is; if (!is.Open(path)) { DXERROR("Failed to open: %s.", path.c_str()); return 1; } for (;;) { std::string s; is >> s; if (!is) { break; } std::cout << s << std::endl; } is.Close(); } else if (action == "ls" || action == "lsr") { AutoFileSystem fs; if (!fs.Open(path)) { DXERROR("Failed to open: %s.", path.c_str()); return 1; } std::vector<std::pair<FilePath, FileStat>> children; if (action == "ls") { if (!fs.List(path, false, &children)) { DXERROR("Failed to list: %s.", path.c_str()); return 1; } } else { if (!fs.ListRecursive(path, false, &children)) { DXERROR("Failed to list: %s.", path.c_str()); return 1; } } for (const auto& entry : children) { const FileStat& stat = entry.second; if (stat.IsDir()) { std::cout << "dir "; } else if (stat.IsRegFile()) { std::cout << "reg "; } else if (stat.IsSymLink()) { std::cout << "sym "; } else if (stat.IsOther()) { std::cout << "??? "; } std::cout.width(12); std::cout << stat.GetFileSize(); std::cout << " "; std::cout << entry.first.str(); std::cout << std::endl; } } else { ShowHelp(); return 1; } return 0; } int main(int argc, char** argv) { google::SetUsageMessage("Usage: [Options]"); #if HAVE_COMPILE_FLAGS_H == 1 google::SetVersionString("\n\n" #include "compile_flags.h" ); #endif google::ParseCommandLineFlags(&argc, &argv, true); int ret = real_main(argc, argv); google::ShutDownCommandLineFlags(); return ret; } } // namespace } // namespace deepx_core int main(int argc, char** argv) { return deepx_core::main(argc, argv); }
23.742188
72
0.537019
[ "vector" ]
0e841dfa00c301f332c1067377c05aba683af997
4,349
cpp
C++
src/libs/icon/Icon.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/libs/icon/Icon.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/libs/icon/Icon.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * Stephan Aßmus <superstippi@gmx.de> */ #include "Icon.h" #include <new> #include <stdio.h> #include "PathContainer.h" #include "Shape.h" #include "Style.h" #include "StyleContainer.h" using std::nothrow; #ifdef ICON_O_MATIC IconListener::IconListener() {} IconListener::~IconListener() {} #endif // #pragma mark - // constructor Icon::Icon() : fStyles(new (nothrow) StyleContainer()), fPaths(new (nothrow) PathContainer(true)), fShapes(new (nothrow) ShapeContainer()) #ifdef ICON_O_MATIC , fListeners(2) #endif { #ifdef ICON_O_MATIC if (fShapes) fShapes->AddListener(this); #endif } // constructor Icon::Icon(const Icon& other) : fStyles(new (nothrow) StyleContainer()), fPaths(new (nothrow) PathContainer(true)), fShapes(new (nothrow) ShapeContainer()) #ifdef ICON_O_MATIC , fListeners(2) #endif { if (!fStyles || !fPaths || !fShapes) return; #ifdef ICON_O_MATIC fShapes->AddListener(this); #endif int32 styleCount = other.fStyles->CountStyles(); for (int32 i = 0; i < styleCount; i++) { Style* style = other.fStyles->StyleAtFast(i); Style* clone = new (nothrow) Style(*style); if (!clone || !fStyles->AddStyle(clone)) { delete clone; return; } } int32 pathCount = other.fPaths->CountPaths(); for (int32 i = 0; i < pathCount; i++) { VectorPath* path = other.fPaths->PathAtFast(i); VectorPath* clone = new (nothrow) VectorPath(*path); if (!clone || !fPaths->AddPath(clone)) { delete clone; return; } } int32 shapeCount = other.fShapes->CountShapes(); for (int32 i = 0; i < shapeCount; i++) { Shape* shape = other.fShapes->ShapeAtFast(i); Shape* clone = new (nothrow) Shape(*shape); if (!clone || !fShapes->AddShape(clone)) { delete clone; return; } // the cloned shape references styles and paths in // the "other" icon, replace them with "local" styles // and paths int32 styleIndex = other.fStyles->IndexOf(shape->Style()); clone->SetStyle(fStyles->StyleAt(styleIndex)); clone->Paths()->MakeEmpty(); pathCount = shape->Paths()->CountPaths(); for (int32 j = 0; j < pathCount; j++) { VectorPath* remote = shape->Paths()->PathAtFast(j); int32 index = other.fPaths->IndexOf(remote); VectorPath* local = fPaths->PathAt(index); if (!local) { printf("failed to match remote and " "local paths while cloning icon\n"); continue; } if (!clone->Paths()->AddPath(local)) { return; } } } } // destructor Icon::~Icon() { if (fShapes) { fShapes->MakeEmpty(); #ifdef ICON_O_MATIC fShapes->RemoveListener(this); #endif delete fShapes; } delete fPaths; delete fStyles; } // InitCheck status_t Icon::InitCheck() const { return fStyles && fPaths && fShapes ? B_OK : B_NO_MEMORY; } #ifdef ICON_O_MATIC // ShapeAdded void Icon::ShapeAdded(Shape* shape, int32 index) { shape->AddObserver(this); _NotifyAreaInvalidated(shape->Bounds(true)); } // ShapeRemoved void Icon::ShapeRemoved(Shape* shape) { shape->RemoveObserver(this); _NotifyAreaInvalidated(shape->Bounds(true)); } // ObjectChanged void Icon::ObjectChanged(const Observable* object) { const Shape* shape = dynamic_cast<const Shape*>(object); if (shape) { BRect area = shape->LastBounds(); area = area | shape->Bounds(true); area.InsetBy(-1, -1); _NotifyAreaInvalidated(area); } } // AddListener bool Icon::AddListener(IconListener* listener) { if (listener && !fListeners.HasItem((void*)listener)) { if (fListeners.AddItem((void*)listener)) { listener->AreaInvalidated(BRect(0, 0, 63, 63)); return true; } } return false; } // RemoveListener bool Icon::RemoveListener(IconListener* listener) { return fListeners.RemoveItem((void*)listener); } #endif // ICON_O_MATIC // Clone Icon* Icon::Clone() const { return new (nothrow) Icon(*this); } // MakeEmpty void Icon::MakeEmpty() { fShapes->MakeEmpty(); fPaths->MakeEmpty(); fStyles->MakeEmpty(); } // #pragma mark - #ifdef ICON_O_MATIC // _NotifyAreaInvalidated void Icon::_NotifyAreaInvalidated(const BRect& area) const { BList listeners(fListeners); int32 count = listeners.CountItems(); for (int32 i = 0; i < count; i++) { IconListener* listener = (IconListener*)listeners.ItemAtFast(i); listener->AreaInvalidated(area); } } #endif // ICON_O_MATIC
19.949541
60
0.680846
[ "object", "shape" ]
0e847361147281f1a52afdd92d6498a419667ef1
568
hpp
C++
c++/libcryptopals/include/cryptopals/xor.hpp
porkfactor/matasano
9e583ab0f040d7163dec2820b95e251123b2fab2
[ "BSD-2-Clause" ]
null
null
null
c++/libcryptopals/include/cryptopals/xor.hpp
porkfactor/matasano
9e583ab0f040d7163dec2820b95e251123b2fab2
[ "BSD-2-Clause" ]
null
null
null
c++/libcryptopals/include/cryptopals/xor.hpp
porkfactor/matasano
9e583ab0f040d7163dec2820b95e251123b2fab2
[ "BSD-2-Clause" ]
null
null
null
#ifndef INCLUDE_CRYPTOPALS_XOR_HPP_ #define INCLUDE_CRYPTOPALS_XOR_HPP_ #include <vector> namespace porkfactor { namespace matasano { template<typename T> std::vector<T> buffer_xor(std::vector<T> const &m, std::vector<T> const &key) { typename std::vector<T>::size_type sz = m.size(); std::vector<T> rv(sz); for(typename std::vector<T>::size_type i = 0; i < sz; i++) { rv[i] = m[i] ^ key[i % key.size()]; } return rv; } } } #endif
21.037037
85
0.526408
[ "vector" ]
0e8798e35ed8f1b1a44e459513c1f1e8ec39464e
27,946
cpp
C++
DemoApps/Vulkan/TexturingArrays/source/TexturingArrays.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
3
2019-01-19T20:21:24.000Z
2021-08-10T02:11:32.000Z
DemoApps/Vulkan/TexturingArrays/source/TexturingArrays.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/Vulkan/TexturingArrays/source/TexturingArrays.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
1
2021-08-10T02:11:33.000Z
2021-08-10T02:11:33.000Z
/* * Vulkan Example - Texture arrays and instanced rendering * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ // Based on a example called 'Texture Arrays' by Sascha Willems from https://github.com/SaschaWillems/Vulkan // Recreated as a DemoFramework freestyle window sample by Freescale (2016) #include "TexturingArrays.hpp" #include <FslBase/Log/Log.hpp> #include <FslBase/Exceptions.hpp> #include <FslGraphics/Bitmap/Bitmap.hpp> #include <FslGraphics/Texture/Texture.hpp> #include <FslUtil/Vulkan1_0/Exceptions.hpp> #include <FslUtil/Vulkan1_0/Util/ConvertUtil.hpp> #include <FslUtil/Vulkan1_0/Util/CommandBufferUtil.hpp> #include <RapidVulkan/Check.hpp> #include <RapidVulkan/Memory.hpp> #include <array> #include <cstring> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> using namespace RapidVulkan; namespace Fsl { using namespace Vulkan; using namespace Vulkan::ConvertUtil; using namespace Willems; namespace { const uint32_t VERTEX_BUFFER_BIND_ID = 0; } TexturingArrays::TexturingArrays(const DemoAppConfig& config) : VulkanWillemsDemoApp(config) , m_descriptorSet(VK_NULL_HANDLE) { m_zoom = -15.0f; m_rotationSpeed = 0.25f; m_rotation = { -15.0f, 35.0f, 0.0f }; m_enableTextOverlay = true; m_title = "Vulkan Example - Texture arrays"; } TexturingArrays::~TexturingArrays() { } // This ensures the flow is the same as in the original sample void TexturingArrays::Prepare() { VulkanWillemsDemoApp::Prepare(); SetupVertexDescriptions(); LoadTextures(); GenerateQuad(); PrepareUniformBuffers(); SetupDescriptorSetLayout(); PreparePipelines(); SetupDescriptorPool(); SetupDescriptorSet(); BuildCommandBuffers(); } void TexturingArrays::BuildCommandBuffers() { const auto screenExtent = Convert(GetScreenExtent()); VkCommandBufferBeginInfo cmdBufInfo{}; cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufInfo.pNext = nullptr; VkClearValue clearValues[2]; clearValues[0].color = m_defaultClearColor; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBeginInfo{}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.pNext = nullptr; renderPassBeginInfo.renderPass = m_renderPass.Get(); renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent = screenExtent; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (std::size_t i = 0; i < m_drawCmdBuffers.Size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = m_frameBuffers[i].Get(); m_drawCmdBuffers.Begin(i, cmdBufInfo); { vkCmdBeginRenderPass(m_drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport{}; viewport.width = static_cast<float>(screenExtent.width); viewport.height = static_cast<float>(screenExtent.height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; vkCmdSetViewport(m_drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor{}; scissor.offset.x = 0; scissor.offset.y = 0; scissor.extent = screenExtent; vkCmdSetScissor(m_drawCmdBuffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(m_drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout.Get(), 0, 1, &m_descriptorSet, 0, nullptr); VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(m_drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, m_meshes.Quad.GetVertices().GetBufferPointer(), offsets); vkCmdBindIndexBuffer(m_drawCmdBuffers[i], m_meshes.Quad.GetIndices().GetBuffer(), 0, VK_INDEX_TYPE_UINT32); vkCmdBindPipeline(m_drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelines.Solid.Get()); vkCmdDrawIndexed(m_drawCmdBuffers[i], m_meshes.Quad.GetIndexCount(), m_textureArray.GetLayers(), 0, 0, 0); vkCmdEndRenderPass(m_drawCmdBuffers[i]); } m_drawCmdBuffers.End(i); } } void TexturingArrays::OnViewChanged() { UpdateUniformBufferMatrices(); } void TexturingArrays::Update(const DemoTime& demoTime) { } void TexturingArrays::Draw(const DemoTime& demoTime) { if (!TryPrepareFrame()) return; m_submitInfo.commandBufferCount = 1; m_submitInfo.pCommandBuffers = m_drawCmdBuffers.GetPointer(m_currentBufferIndex); m_deviceQueue.Submit(1, &m_submitInfo, VK_NULL_HANDLE); SubmitFrame(); } void TexturingArrays::SetupVertexDescriptions() { // Binding description m_vertices.BindingDescriptions.resize(1); m_vertices.BindingDescriptions[0].binding = VERTEX_BUFFER_BIND_ID; m_vertices.BindingDescriptions[0].stride = sizeof(Vertex); m_vertices.BindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // Attribute descriptions // Describes memory layout and shader positions m_vertices.AttributeDescriptions.resize(2); // Location 0 : Position m_vertices.AttributeDescriptions[0].location = 0; m_vertices.AttributeDescriptions[0].binding = VERTEX_BUFFER_BIND_ID; m_vertices.AttributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; m_vertices.AttributeDescriptions[0].offset = 0; // Location 1 : Texture coordinates m_vertices.AttributeDescriptions[1].location = 1; m_vertices.AttributeDescriptions[1].binding = VERTEX_BUFFER_BIND_ID; m_vertices.AttributeDescriptions[1].format = VK_FORMAT_R32G32_SFLOAT; m_vertices.AttributeDescriptions[1].offset = sizeof(float) * 3; m_vertices.InputState.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; m_vertices.InputState.pNext = nullptr; m_vertices.InputState.vertexBindingDescriptionCount = static_cast<uint32_t>(m_vertices.BindingDescriptions.size()); m_vertices.InputState.pVertexBindingDescriptions = m_vertices.BindingDescriptions.data(); m_vertices.InputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(m_vertices.AttributeDescriptions.size()); m_vertices.InputState.pVertexAttributeDescriptions = m_vertices.AttributeDescriptions.data(); } void TexturingArrays::LoadTextures() { if (m_deviceActiveFeatures.textureCompressionBC) { //m_textureArray = m_textureLoader->LoadTextureArray("textures/texturearray_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK); m_textureArray = LoadTextureArray("textures/texturearray_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK); } else if (m_deviceActiveFeatures.textureCompressionETC2) { m_textureArray = LoadTextureArray("textures/texturearray_etc2.ktx", VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK); } else throw NotSupportedException("No supported texture compression available"); } VulkanTexture TexturingArrays::LoadTextureArray(const std::string& filename, const VkFormat format) { auto pixelFormat = ConvertUtil::Convert(format); auto textureArray = GetContentManager()->ReadTexture(filename, pixelFormat); auto texExtent = textureArray.GetExtent(); texExtent.Depth = 1; //textureArray.width = tex2DArray.dimensions().x; //textureArray.height = tex2DArray.dimensions().y; //layerCount = tex2DArray.layers(); // Create a host-visible staging buffer that contains the raw image data VkBufferCreateInfo bufferCreateInfo{}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = nullptr; bufferCreateInfo.size = textureArray.GetByteSize(); // This buffer is used as a transfer source for the buffer copy bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Buffer stagingBuffer(m_device.Get(), bufferCreateInfo); // Get memory requirements for the staging buffer (alignment, memory type bits) VkMemoryRequirements memReqs = stagingBuffer.GetBufferMemoryRequirements(); VkMemoryAllocateInfo memAllocInfo{}; memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memAllocInfo.pNext = nullptr; memAllocInfo.allocationSize = memReqs.size; // Get memory type index for a host visible buffer memAllocInfo.memoryTypeIndex = m_vulkanDevice.GetMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); Memory stagingMemory(m_device.Get(), memAllocInfo); RAPIDVULKAN_CHECK(vkBindBufferMemory(m_device.Get(), stagingBuffer.Get(), stagingMemory.Get(), 0)); // Copy texture data into staging buffer void* pData = nullptr; stagingMemory.MapMemory(0, memReqs.size, 0, &pData); { if (pData == nullptr) throw std::runtime_error("failed to map memory"); RawTexture rawTexture; Texture::ScopedDirectAccess directAccess(textureArray, rawTexture); std::memcpy(pData, rawTexture.GetContent(), rawTexture.GetContentByteSize()); } stagingMemory.UnmapMemory(); // Setup buffer copy regions for array layers std::vector<VkBufferImageCopy> bufferCopyRegions; // Check if all array layers have the same dimensions bool sameDims = true; // NOTE: the Texture class does not support multiple layers of different sizes //for (uint32_t layer = 0; layer < textureArray.GetLayers(); ++layer) //{ // if (tex2DArray[layer].dimensions().x != textureArray.width || tex2DArray[layer].dimensions().y != textureArray.height) // { // sameDims = false; // break; // } //} // If all layers of the texture array have the same dimensions, we only need to do one copy if (sameDims) { VkBufferImageCopy bufferCopyRegion = {}; bufferCopyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; bufferCopyRegion.imageSubresource.mipLevel = 0; bufferCopyRegion.imageSubresource.baseArrayLayer = 0; bufferCopyRegion.imageSubresource.layerCount = textureArray.GetLayers(); bufferCopyRegion.imageExtent = Convert(texExtent); bufferCopyRegion.bufferOffset = 0; bufferCopyRegions.push_back(bufferCopyRegion); } else { // If dimensions differ, copy layer by layer and pass offsets for (uint32_t layer = 0; layer < textureArray.GetLayers(); ++layer) { // FIX: texture does not currently support different layer sizes //const auto blobExtent = textureArray.GetExtent(0, layer); const auto blobExtent = textureArray.GetExtent(0); const auto blobRecord = textureArray.GetTextureBlob(0, 0, layer); VkBufferImageCopy bufferCopyRegion{}; bufferCopyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; bufferCopyRegion.imageSubresource.mipLevel = 0; bufferCopyRegion.imageSubresource.baseArrayLayer = layer; bufferCopyRegion.imageSubresource.layerCount = 1; bufferCopyRegion.imageExtent.width = blobExtent.Width; bufferCopyRegion.imageExtent.height = blobExtent.Height; bufferCopyRegion.imageExtent.depth = 1; bufferCopyRegion.bufferOffset = blobRecord.Offset; bufferCopyRegions.push_back(bufferCopyRegion); } } // Create optimal tiled target image VkImageCreateInfo imageCreateInfo{}; imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.pNext = nullptr; imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = format; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = textureArray.GetLayers(); imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT; imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageCreateInfo.extent = Convert(texExtent); imageCreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; Image texImage(m_device.Get(), imageCreateInfo); memReqs = texImage.GetImageMemoryRequirements(); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = m_vulkanDevice.GetMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Memory texMemory(m_device.Get(), memAllocInfo); RAPIDVULKAN_CHECK(vkBindImageMemory(m_device.Get(), texImage.Get(), texMemory.Get(), 0)); const VkImageLayout texImageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; { CommandBuffer copyCmd = CreateCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); // Image barrier for optimal image (target) // Set initial layout for all array layers (faces) of the optimal (target) tiled texture VkImageSubresourceRange subresourceRange{}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = 1; subresourceRange.layerCount = textureArray.GetLayers(); CommandBufferUtil::SetImageLayout(copyCmd.Get(), texImage.Get(), VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange); // Copy the cube map faces from the staging buffer to the optimal tiled image vkCmdCopyBufferToImage(copyCmd.Get(), stagingBuffer.Get(), texImage.Get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<uint32_t>(bufferCopyRegions.size()), bufferCopyRegions.data()); // Change texture image layout to shader read after all faces have been copied CommandBufferUtil::SetImageLayout(copyCmd.Get(), texImage.Get(), VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, texImageLayout, subresourceRange); FlushCommandBuffer(copyCmd, m_deviceQueue.Queue, true); } // Create sampler VkSamplerCreateInfo sampler{}; sampler.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; sampler.pNext = nullptr; sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; sampler.addressModeV = sampler.addressModeU; sampler.addressModeW = sampler.addressModeU; sampler.mipLodBias = 0.0f; sampler.maxAnisotropy = m_deviceActiveFeatures.samplerAnisotropy ? 8.0f : 1.0f; sampler.compareOp = VK_COMPARE_OP_NEVER; sampler.minLod = 0.0f; sampler.maxLod = 0.0f; sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; Sampler texSampler(m_device.Get(), sampler); // Create image view VkImageViewCreateInfo view{}; view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view.pNext = nullptr; view.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; view.format = format; view.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }; view.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; view.subresourceRange.layerCount = textureArray.GetLayers(); view.image = texImage.Get(); ImageView texImageView(m_device.Get(), view); VkDescriptorImageInfo texDescriptor{}; texDescriptor.sampler = texSampler.Get(); texDescriptor.imageView = texImageView.Get(); texDescriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; // Transfer ownership to the texture object (move) return VulkanTexture(std::move(texSampler), std::move(texImage), texImageLayout, std::move(texMemory), std::move(texImageView), texExtent, textureArray.GetLevels(), textureArray.GetLayers(), texDescriptor); } void TexturingArrays::GenerateQuad() { const float dim = 2.5f; std::vector<Vertex> vertexBuffer = { { { dim, dim, 0.0f }, { 1.0f, 1.0f } }, { { -dim, dim, 0.0f }, { 0.0f, 1.0f } }, { { -dim, -dim, 0.0f }, { 0.0f, 0.0f } }, { { dim, -dim, 0.0f }, { 1.0f, 0.0f } } }; MeshLoader::MeshBufferInfo meshVertexInfo; CreateBuffer(meshVertexInfo.Buffer, meshVertexInfo.Memory, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexBuffer.size() * sizeof(Vertex), vertexBuffer.data()); // Setup indices const std::vector<uint32_t> indexBuffer = { 0, 1, 2, 2, 3, 0 }; MeshLoader::MeshBufferInfo meshIndexInfo; CreateBuffer(meshIndexInfo.Buffer, meshIndexInfo.Memory, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, indexBuffer.size() * sizeof(uint32_t), indexBuffer.data()); std::vector<MeshLoader::MeshDescriptor> meshDescriptors; meshDescriptors.push_back(MeshLoader::MeshDescriptor(static_cast<uint32_t>(vertexBuffer.size()), 0, static_cast<uint32_t>(indexBuffer.size()))); m_meshes.Quad.Reset(std::move(meshDescriptors), std::move(meshVertexInfo), std::move(meshIndexInfo), static_cast<uint32_t>(indexBuffer.size()), glm::vec3(dim)); } void TexturingArrays::PrepareUniformBuffers() { const auto layerCount = m_textureArray.GetLayers(); m_uboVS.Instance.resize(layerCount); const uint32_t uboSize = sizeof(m_uboVS.Matrices) + (layerCount * sizeof(UboInstanceData)); // Vertex shader uniform buffer block CreateBuffer(m_uniformData.VertexShader.Buffer, m_uniformData.VertexShader.Memory, m_uniformData.VertexShader.Descriptor, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uboSize, &m_uboVS); // Array indices and model matrices are fixed const float offset = -1.5f; float center = (layerCount*offset) / 2; for (uint32_t i = 0; i < layerCount; ++i) { // Instance model matrix m_uboVS.Instance[i].Model = glm::translate(glm::mat4(), glm::vec3(0.0f, i * offset - center, 0.0f)); m_uboVS.Instance[i].Model = glm::rotate(m_uboVS.Instance[i].Model, glm::radians(60.0f), glm::vec3(1.0f, 0.0f, 0.0f)); // Instance texture array index m_uboVS.Instance[i].ArrayIndex.x = static_cast<float>(i); } // Update instanced part of the uniform buffer void* pData = nullptr; uint32_t dataOffset = sizeof(m_uboVS.Matrices); uint32_t dataSize = layerCount * sizeof(UboInstanceData); m_uniformData.VertexShader.Memory.MapMemory(dataOffset, dataSize, 0, &pData); { if (pData == nullptr) throw std::runtime_error("vkMapMemory returned nullptr"); std::memcpy(pData, m_uboVS.Instance.data(), dataSize); } m_uniformData.VertexShader.Memory.UnmapMemory(); UpdateUniformBufferMatrices(); } void TexturingArrays::UpdateUniformBufferMatrices() { const auto screenExtent = GetScreenExtent(); // Only updates the uniform buffer block part containing the global matrices // Projection const float aspect = static_cast<float>(screenExtent.Width) / static_cast<float>(screenExtent.Height); m_uboVS.Matrices.Projection = glm::perspective(glm::radians(60.0f), aspect, 0.001f, 256.0f); // View m_uboVS.Matrices.View = glm::translate(glm::mat4(), glm::vec3(0.0f, -1.0f, m_zoom)); m_uboVS.Matrices.View = glm::rotate(m_uboVS.Matrices.View, glm::radians(m_rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); m_uboVS.Matrices.View = glm::rotate(m_uboVS.Matrices.View, glm::radians(m_rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); m_uboVS.Matrices.View = glm::rotate(m_uboVS.Matrices.View, glm::radians(m_rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); // Only update the matrices part of the uniform buffer { void* pData = nullptr; m_uniformData.VertexShader.Memory.MapMemory(0, sizeof(m_uboVS.Matrices), 0, &pData); std::memcpy(pData, &m_uboVS.Matrices, sizeof(m_uboVS.Matrices)); m_uniformData.VertexShader.Memory.UnmapMemory(); } } void TexturingArrays::SetupDescriptorSetLayout() { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings(2); // Binding 0 : Vertex shader uniform buffer setLayoutBindings[0].binding = 0; setLayoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; setLayoutBindings[0].descriptorCount = 1; setLayoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // Binding 1 : Fragment shader image sampler (texture array) setLayoutBindings[1].binding = 1; setLayoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; setLayoutBindings[1].descriptorCount = 1; setLayoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutCreateInfo descriptorLayout{}; descriptorLayout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorLayout.pNext = nullptr; descriptorLayout.bindingCount = static_cast<uint32_t>(setLayoutBindings.size()); descriptorLayout.pBindings = setLayoutBindings.data(); m_descriptorSetLayout.Reset(m_device.Get(), descriptorLayout); VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.pNext = nullptr; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = m_descriptorSetLayout.GetPointer(); m_pipelineLayout.Reset(m_device.Get(), pipelineLayoutCreateInfo); } void TexturingArrays::PreparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState{}; inputAssemblyState.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyState.flags = 0; inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyState.primitiveRestartEnable = VK_FALSE; VkPipelineRasterizationStateCreateInfo rasterizationState{}; rasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizationState.flags = 0; rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; rasterizationState.cullMode = VK_CULL_MODE_NONE; rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationState.depthClampEnable = VK_FALSE; rasterizationState.lineWidth = 1.0f; VkPipelineColorBlendAttachmentState blendAttachmentState{}; blendAttachmentState.blendEnable = VK_FALSE; blendAttachmentState.colorWriteMask = 0xf; VkPipelineColorBlendStateCreateInfo colorBlendState{}; colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendState.pNext = nullptr; colorBlendState.attachmentCount = 1; colorBlendState.pAttachments = &blendAttachmentState; VkPipelineDepthStencilStateCreateInfo depthStencilState{}; depthStencilState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencilState.depthTestEnable = VK_TRUE; depthStencilState.depthWriteEnable = VK_TRUE; depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; depthStencilState.front.compareOp = VK_COMPARE_OP_ALWAYS; depthStencilState.back.compareOp = VK_COMPARE_OP_ALWAYS; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.flags = 0; viewportState.viewportCount = 1; viewportState.scissorCount = 1; VkPipelineMultisampleStateCreateInfo multisampleState{}; multisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleState.flags = 0; multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState{}; dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamicState.flags = 0; dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStateEnables.size()); dynamicState.pDynamicStates = dynamicStateEnables.data(); // Instacing pipeline // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages{}; shaderStages[0] = LoadShader("shaders/instancing.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = LoadShader("shaders/instancing.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.pNext = nullptr; pipelineCreateInfo.flags = 0; pipelineCreateInfo.layout = m_pipelineLayout.Get(); pipelineCreateInfo.renderPass = m_renderPass.Get(); pipelineCreateInfo.pVertexInputState = &m_vertices.InputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); m_pipelines.Solid.Reset(m_device.Get(), m_pipelineCache.Get(), pipelineCreateInfo); } void TexturingArrays::SetupDescriptorPool() { std::vector<VkDescriptorPoolSize> poolSizes(2); poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[0].descriptorCount = 1; poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[1].descriptorCount = 1; VkDescriptorPoolCreateInfo descriptorPoolInfo{}; descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPoolInfo.pNext = nullptr; descriptorPoolInfo.maxSets = 2; descriptorPoolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); descriptorPoolInfo.pPoolSizes = poolSizes.data(); m_descriptorPool.Reset(m_device.Get(), descriptorPoolInfo); } void TexturingArrays::SetupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.descriptorPool = m_descriptorPool.Get(); allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = m_descriptorSetLayout.GetPointer(); RAPIDVULKAN_CHECK(vkAllocateDescriptorSets(m_device.Get(), &allocInfo, &m_descriptorSet)); std::vector<VkWriteDescriptorSet> writeDescriptorSets(2); // Binding 0 : Vertex shader uniform buffer writeDescriptorSets[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSets[0].pNext = nullptr; writeDescriptorSets[0].dstSet = m_descriptorSet; writeDescriptorSets[0].dstBinding = 0; writeDescriptorSets[0].descriptorCount = 1; writeDescriptorSets[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescriptorSets[0].pBufferInfo = &m_uniformData.VertexShader.Descriptor; // Binding 1 : Fragment shader cubemap sampler writeDescriptorSets[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSets[1].pNext = nullptr; writeDescriptorSets[1].dstSet = m_descriptorSet; writeDescriptorSets[1].dstBinding = 1; writeDescriptorSets[1].descriptorCount = 1; writeDescriptorSets[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSets[1].pImageInfo = m_textureArray.GetImageDescriptorPointer(); vkUpdateDescriptorSets(m_device.Get(), static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr); } }
41.218289
164
0.744471
[ "object", "vector", "model", "solid" ]
0e8c94e59f260102fc767b0555520e61d8b0e78e
2,170
cc
C++
cinn/frontend/decomposer/activation_test.cc
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
null
null
null
cinn/frontend/decomposer/activation_test.cc
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
null
null
null
cinn/frontend/decomposer/activation_test.cc
SunNy820828449/CINN
6384f730867132508c2c60f5ff2aae12959143d7
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021 CINN Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cinn/frontend/decomposer/test_helper.h" namespace cinn::frontend { TEST(Decomposer, relu) { NetBuilder builder("relu"); auto x = builder.CreateInput(Float(32), {20, 10}); auto out = builder.relu(x); auto relu_cpu = [](const std::vector<size_t>& lengths, const std::vector<void*>& ptrs) { size_t n = lengths[0]; float* x = static_cast<float*>(ptrs[0]); float* out = static_cast<float*>(ptrs[1]); for (size_t i = 0; i < n; ++i) { float tmp_0 = x[i]; out[i] = tmp_0 > 0 ? tmp_0 : 0; } }; std::vector<std::string> input_names = {x.id().data()}; std::vector<std::string> output_names = {out->id}; RunAndCheck<float>(builder, input_names, output_names, relu_cpu); } TEST(Decomposer, relu_grad) { NetBuilder builder("relu_grad"); auto dout = builder.CreateInput(Float(32), {20, 10}); auto out = builder.CreateInput(Float(32), {20, 10}); auto dx = builder.relu_grad(dout, out); auto relu_grad_cpu = [](const std::vector<size_t>& lengths, const std::vector<void*>& ptrs) { size_t n = lengths[0]; float* dout = static_cast<float*>(ptrs[0]); float* out = static_cast<float*>(ptrs[1]); float* dx = static_cast<float*>(ptrs[2]); for (size_t i = 0; i < n; ++i) { dx[i] = out[i] > 0 ? dout[i] : 0; } }; std::vector<std::string> input_names = {dout.id().data(), out.id().data()}; std::vector<std::string> output_names = {dx->id}; RunAndCheck<float>(builder, input_names, output_names, relu_grad_cpu); } } // namespace cinn::frontend
35.57377
95
0.654378
[ "vector" ]
0e9371f640d94682cfda47af7fbf3fc4fbe62823
5,600
cc
C++
chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h" #include <memory> #include <utility> #include "base/values.h" #include "chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/device_info_sync_service_factory.h" #include "chrome/common/extensions/api/signed_in_devices.h" #include "components/sync_device_info/device_info_sync_service.h" #include "components/sync_device_info/device_info_tracker.h" #include "components/sync_device_info/local_device_info_provider.h" #include "extensions/browser/extension_prefs.h" using base::DictionaryValue; using syncer::DeviceInfo; using syncer::DeviceInfoTracker; using syncer::LocalDeviceInfoProvider; namespace extensions { static const char kPrefStringForIdMapping[] = "id_mapping_dictioanry"; // Gets the dictionary that stores the id mapping. The dictionary is stored // in the |ExtensionPrefs|. const base::DictionaryValue* GetIdMappingDictionary( ExtensionPrefs* extension_prefs, const std::string& extension_id) { const base::DictionaryValue* out_value = NULL; if (!extension_prefs->ReadPrefAsDictionary( extension_id, kPrefStringForIdMapping, &out_value) || out_value == NULL) { // Looks like this is the first call to get the dictionary. Let us create // a dictionary and set it in to |extension_prefs|. std::unique_ptr<base::DictionaryValue> dictionary( new base::DictionaryValue()); out_value = dictionary.get(); extension_prefs->UpdateExtensionPref(extension_id, kPrefStringForIdMapping, std::move(dictionary)); } return out_value; } // Helper routine to get all signed in devices. The helper takes in // the pointers for |DeviceInfoTracker| and |Extensionprefs|. This // makes it easier to test by passing mock values for these pointers. std::vector<std::unique_ptr<DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, DeviceInfoTracker* device_tracker, ExtensionPrefs* extension_prefs) { DCHECK(device_tracker); std::vector<std::unique_ptr<DeviceInfo>> devices = device_tracker->GetAllDeviceInfo(); const base::DictionaryValue* mapping_dictionary = GetIdMappingDictionary( extension_prefs, extension_id); CHECK(mapping_dictionary); // |mapping_dictionary| is const. So make an editable copy. std::unique_ptr<base::DictionaryValue> editable_mapping_dictionary( mapping_dictionary->DeepCopy()); CreateMappingForUnmappedDevices(devices, editable_mapping_dictionary.get()); // Write into |ExtensionPrefs| which will get persisted in disk. extension_prefs->UpdateExtensionPref(extension_id, kPrefStringForIdMapping, std::move(editable_mapping_dictionary)); return devices; } std::vector<std::unique_ptr<DeviceInfo>> GetAllSignedInDevices( const std::string& extension_id, Profile* profile) { // Get the device tracker and extension prefs pointers // and call the helper. DeviceInfoTracker* device_tracker = DeviceInfoSyncServiceFactory::GetForProfile(profile) ->GetDeviceInfoTracker(); DCHECK(device_tracker); if (!device_tracker->IsSyncing()) { // Devices are not sync'ing. return std::vector<std::unique_ptr<DeviceInfo>>(); } ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile); return GetAllSignedInDevices(extension_id, device_tracker, extension_prefs); } std::unique_ptr<DeviceInfo> GetLocalDeviceInfo(const std::string& extension_id, Profile* profile) { syncer::DeviceInfoSyncService* service = DeviceInfoSyncServiceFactory::GetForProfile(profile); if (!service) { return nullptr; } const LocalDeviceInfoProvider* local_device_info_provider = service->GetLocalDeviceInfoProvider(); DCHECK(local_device_info_provider); const DeviceInfo* local_device = local_device_info_provider->GetLocalDeviceInfo(); if (!local_device) return nullptr; // TODO(karandeepb): Can't we just return a copy of |local_device|, without // having to look it up by GUID? return GetDeviceInfoForClientId(local_device->guid(), extension_id, profile); } ExtensionFunction::ResponseAction SignedInDevicesGetFunction::Run() { std::unique_ptr<api::signed_in_devices::Get::Params> params( api::signed_in_devices::Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); bool is_local = params->is_local.get() ? *params->is_local : false; Profile* profile = Profile::FromBrowserContext(browser_context()); if (is_local) { std::unique_ptr<DeviceInfo> device = GetLocalDeviceInfo(extension_id(), profile); std::unique_ptr<base::ListValue> result(new base::ListValue()); if (device.get()) { result->Append(device->ToValue()); } return RespondNow( OneArgument(base::Value::FromUniquePtrValue(std::move(result)))); } std::vector<std::unique_ptr<DeviceInfo>> devices = GetAllSignedInDevices(extension_id(), profile); std::unique_ptr<base::ListValue> result(new base::ListValue()); for (const std::unique_ptr<DeviceInfo>& device : devices) result->Append(device->ToValue()); return RespondNow( OneArgument(base::Value::FromUniquePtrValue(std::move(result)))); } } // namespace extensions
37.086093
82
0.735893
[ "vector" ]
0e943133ad1040333914fb2ac88dbef5f319ebba
52,388
cc
C++
src/gui/dictionary_tool/dictionary_tool.cc
janasle/mozc
1ddec765e033d22079627dc14a06a204134e1b28
[ "BSD-3-Clause" ]
1
2022-03-08T07:35:49.000Z
2022-03-08T07:35:49.000Z
src/gui/dictionary_tool/dictionary_tool.cc
kirameister/mozc
18b2b32b4d3fe585d38134606773239781b6be82
[ "BSD-3-Clause" ]
null
null
null
src/gui/dictionary_tool/dictionary_tool.cc
kirameister/mozc
18b2b32b4d3fe585d38134606773239781b6be82
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2010-2021, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "gui/dictionary_tool/dictionary_tool.h" #include <cstdint> #if defined(OS_ANDROID) || defined(OS_WASM) #error "This platform is not supported." #endif // OS_ANDROID || OS_WASM #include <QtCore/QTimer> #include <QtGui/QtGui> #include <QtWidgets/QFileDialog> #include <QtWidgets/QInputDialog> #include <QtWidgets/QMenu> #include <QtWidgets/QMessageBox> #include <QtWidgets/QProgressDialog> #include <QtWidgets/QShortcut> #ifdef OS_WIN #include <Windows.h> #endif // OS_WIN #include <algorithm> #include <functional> #include <memory> #include <string> #include <vector> #include "base/file_stream.h" #include "base/logging.h" #include "base/run_level.h" #include "base/util.h" #include "client/client.h" #include "data_manager/pos_list_provider.h" #include "dictionary/user_dictionary_importer.h" #include "dictionary/user_dictionary_session.h" #include "dictionary/user_dictionary_storage.h" #include "dictionary/user_dictionary_util.h" #include "gui/base/encoding_util.h" #include "gui/base/msime_user_dictionary_importer.h" #include "gui/base/util.h" #include "gui/config_dialog/combobox_delegate.h" #include "gui/dictionary_tool/find_dialog.h" #include "gui/dictionary_tool/import_dialog.h" #include "protocol/user_dictionary_storage.pb.h" #include "absl/memory/memory.h" #ifdef OS_WIN #include "gui/base/win_util.h" #endif // OS_WIN namespace mozc { namespace gui { namespace { using ::mozc::user_dictionary::UserDictionary; using ::mozc::user_dictionary::UserDictionaryCommandStatus; using ::mozc::user_dictionary::UserDictionarySession; using ::mozc::user_dictionary::UserDictionaryStorage; inline QString QUtf8(const char str[]) { return QString::fromUtf8(str); } inline QString QUtf8(const std::string &str) { return QString::fromUtf8(str.c_str()); } // set longer timeout because it takes longer time // to reload all user dictionary. const int kSessionTimeout = 100000; int GetTableHeight(QTableWidget *widget) { // Dragon Hack: // Here we use "龍" to calc font size, as it looks almsot square const QRect rect = QFontMetrics(widget->font()).boundingRect(QUtf8("龍")); return static_cast<int>(rect.height() * 1.4); } QProgressDialog *CreateProgressDialog(QString message, QWidget *parent, int size) { QProgressDialog *progress = new QProgressDialog(message, QLatin1String(""), 0, size, parent); CHECK(progress); progress->setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); progress->setWindowModality(Qt::WindowModal); // This cancel button is invisible to users. // We don't accept any cancel operation QPushButton *cancel_button = new QPushButton; CHECK(cancel_button); progress->setAutoClose(true); progress->setCancelButton(cancel_button); progress->setFixedSize(QSize(400, 100)); cancel_button->setVisible(false); return progress; } // Use QTextStream to read UTF16 text -- we can't use ifstream, // since ifstream cannot handle Wide character. class UTF16TextLineIterator : public UserDictionaryImporter::TextLineIteratorInterface { public: UTF16TextLineIterator(UserDictionaryImporter::EncodingType encoding_type, const std::string &filename, const QString &message, QWidget *parent) : stream_(new QTextStream) { CHECK_EQ(UserDictionaryImporter::UTF16, encoding_type); file_.setFileName(QString::fromUtf8(filename.c_str())); if (!file_.open(QIODevice::ReadOnly)) { LOG(ERROR) << "Cannot open: " << filename; } stream_->setDevice(&file_); stream_->setCodec("UTF-16"); progress_.reset(CreateProgressDialog(message, parent, file_.size())); } bool IsAvailable() const override { return file_.error() == QFile::NoError; } bool Next(std::string *line) override { if (stream_->atEnd()) { return false; } // Can't use ReadLine as ReadLine doesn't support CR only text. QChar ch; QString output_line; while (!stream_->atEnd()) { *stream_ >> ch; if (output_line.isEmpty() && ch == QLatin1Char('\n')) { // no harm to skip empty line continue; } if (ch == QLatin1Char('\n') || ch == QLatin1Char('\r')) { break; } else { output_line += ch; } } progress_->setValue(file_.pos()); *line = output_line.toUtf8().data(); return true; } void Reset() override { file_.seek(0); stream_ = absl::make_unique<QTextStream>(); stream_->setDevice(&file_); stream_->setCodec("UTF-16"); } private: QFile file_; std::unique_ptr<QTextStream> stream_; std::unique_ptr<QProgressDialog> progress_; }; class MultiByteTextLineIterator : public UserDictionaryImporter::TextLineIteratorInterface { public: MultiByteTextLineIterator(UserDictionaryImporter::EncodingType encoding_type, const std::string &filename, const QString &message, QWidget *parent) : encoding_type_(encoding_type), ifs_(new InputFileStream(filename.c_str())), first_line_(true) { const std::streampos begin = ifs_->tellg(); ifs_->seekg(0, std::ios::end); const size_t size = static_cast<size_t>(ifs_->tellg() - begin); ifs_->seekg(0, std::ios::beg); progress_.reset(CreateProgressDialog(message, parent, size)); } bool IsAvailable() const override { // This means that neither failbit nor badbit is set. // TODO(yukawa): Consider to remove |ifs_->eof()|. Furthermore, we should // replace IsAvailable() with something easier to understand, e.g., // Done() or HasNext(). return ifs_->good() || ifs_->eof(); } bool Next(std::string *line) override { if (!ifs_->good()) { return false; } // Can't use getline as getline doesn't support CR only text. char ch; std::string output_line; while (ifs_->good()) { ifs_->get(ch); if (output_line.empty() && ch == '\n') { continue; } if (ch == '\n' || ch == '\r') { break; } else { output_line += ch; } } progress_->setValue(ifs_->tellg()); *line = output_line; // We can't use QTextCodec as QTextCodec is not enabled by default. // We won't enable it as it increases the binary size. if (encoding_type_ == UserDictionaryImporter::SHIFT_JIS) { const std::string input = *line; EncodingUtil::SJISToUTF8(input, line); } // strip UTF8 BOM if (first_line_ && encoding_type_ == UserDictionaryImporter::UTF8) { mozc::Util::StripUTF8BOM(line); } mozc::Util::ChopReturns(line); first_line_ = false; return true; } void Reset() override { // Clear state bit (eofbit, failbit, badbit). ifs_->clear(); ifs_->seekg(0, std::ios_base::beg); first_line_ = true; } private: UserDictionaryImporter::EncodingType encoding_type_; std::unique_ptr<InputFileStream> ifs_; std::unique_ptr<QProgressDialog> progress_; bool first_line_; }; UserDictionaryImporter::TextLineIteratorInterface *CreateTextLineIterator( UserDictionaryImporter::EncodingType encoding_type, const std::string &filename, QWidget *parent) { if (encoding_type == UserDictionaryImporter::ENCODING_AUTO_DETECT) { encoding_type = UserDictionaryImporter::GuessFileEncodingType(filename); } if (encoding_type == UserDictionaryImporter::NUM_ENCODINGS) { LOG(ERROR) << "GuessFileEncodingType() returns UNKNOWN encoding."; // set default encoding #ifdef OS_WIN encoding_type = UserDictionaryImporter::SHIFT_JIS; #else encoding_type = UserDictionaryImporter::UTF16; #endif } VLOG(1) << "Setting Encoding to: " << static_cast<int>(encoding_type); const QString message = QObject::tr("Importing new words..."); switch (encoding_type) { case UserDictionaryImporter::UTF8: case UserDictionaryImporter::SHIFT_JIS: return new MultiByteTextLineIterator(encoding_type, filename, message, parent); break; case UserDictionaryImporter::UTF16: return new UTF16TextLineIterator(encoding_type, filename, message, parent); break; default: return nullptr; } return nullptr; } } // namespace DictionaryTool::DictionaryTool(QWidget *parent) : QMainWindow(parent), import_dialog_(nullptr), find_dialog_(nullptr), session_(new UserDictionarySession( UserDictionaryUtil::GetUserDictionaryFileName())), current_dic_id_(0), modified_(false), monitoring_user_edit_(false), window_title_(GuiUtil::ProductName()), dic_menu_(new QMenu), new_action_(nullptr), rename_action_(nullptr), delete_action_(nullptr), find_action_(nullptr), import_create_action_(nullptr), import_append_action_(nullptr), export_action_(nullptr), import_default_ime_action_(nullptr), client_(client::ClientFactory::NewClient()), is_available_(true), max_entry_size_(mozc::UserDictionaryStorage::max_entry_size()), pos_list_provider_(new POSListProvider()) { setupUi(this); // Create and set up ImportDialog object. import_dialog_ = new ImportDialog(this); // Create and set up FindDialog object. find_dialog_ = new FindDialog(this, dic_content_); client_->set_timeout(kSessionTimeout); if (session_->Load() != UserDictionaryCommandStatus::USER_DICTIONARY_COMMAND_SUCCESS) { LOG(WARNING) << "UserDictionarySession::Load() failed"; } if (!session_->mutable_storage()->Lock()) { QMessageBox::information( this, window_title_, tr("Another process is accessing the user dictionary file.")); is_available_ = false; return; } #ifndef ENABLE_CLOUD_SYNC if (session_->mutable_storage() ->ConvertSyncDictionariesToNormalDictionaries()) { LOG(INFO) << "Syncable dictionaries are converted to normal dictionaries"; session_->mutable_storage()->Save(); } #endif // !ENABLE_CLOUD_SYNC // main window #ifndef OS_LINUX // For some reason setCentralWidget crashes the dictionary_tool on Linux // TODO(taku): investigate the cause of the crashes setCentralWidget(splitter_); #endif setContextMenuPolicy(Qt::NoContextMenu); // toolbar toolbar_->setFloatable(false); toolbar_->setMovable(false); dic_menu_button_ = new QPushButton(tr("Tools"), this); dic_menu_button_->setFlat(true); new_word_button_ = new QPushButton(tr("Add"), this); new_word_button_->setFlat(true); delete_word_button_ = new QPushButton(tr("Remove"), this); delete_word_button_->setFlat(true); toolbar_->addWidget(dic_menu_button_); toolbar_->addWidget(new_word_button_); toolbar_->addWidget(delete_word_button_); // Cosmetic tweaks for Mac. #ifdef __APPLE__ dic_list_->setAttribute(Qt::WA_MacShowFocusRect, false); dic_list_->setAutoFillBackground(true); dic_list_->setFrameStyle(QFrame::NoFrame); dic_content_->setFrameStyle(QFrame::NoFrame); dic_content_->setShowGrid(false); #endif dic_content_->setWordWrap(false); dic_content_->verticalHeader()->hide(); dic_content_->horizontalHeader()->setStretchLastSection(true); dic_content_->horizontalHeader()->setSortIndicatorShown(true); dic_content_->horizontalHeader()->setHighlightSections(false); dic_content_->setAlternatingRowColors(true); // We fix the row height so that paint() is executed faster. // This changes allows DictionaryTool handle about 1M words. dic_content_->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); dic_content_->verticalHeader()->setDefaultSectionSize( GetTableHeight(dic_content_)); // Get a list of POS and set a custom delagate that holds the list. std::vector<std::string> tmp_pos_vec; pos_list_provider_->GetPOSList(&tmp_pos_vec); QStringList pos_list; for (size_t i = 0; i < tmp_pos_vec.size(); ++i) { pos_list.append(QUtf8(tmp_pos_vec[i])); } ComboBoxDelegate *delegate = new ComboBoxDelegate; delegate->SetItemList(pos_list); dic_content_->setItemDelegateForColumn(2, delegate); if (!pos_list.isEmpty()) { default_pos_ = pos_list[0]; } else { LOG(WARNING) << "No POS is given."; } // Set up the main table widget for dictionary contents. dic_content_->setColumnCount(4); QStringList header_labels; header_labels << tr("Reading") << tr("Word") << tr("Category") << tr("Comment"); dic_content_->setHorizontalHeaderLabels(header_labels); #ifdef __APPLE__ // This is a workaround for MacOSX. // QKeysequence::Delete doesn't work on Mac, // so we set the key sequence directly. QShortcut *shortcut1 = new QShortcut(QKeySequence(Qt::Key_Backspace), dic_content_); // Qt::CTRL = Command key // Command+Backspace = delete QShortcut *shortcut2 = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Backspace), dic_content_); connect(shortcut1, SIGNAL(activated()), this, SLOT(DeleteWord())); connect(shortcut2, SIGNAL(activated()), this, SLOT(DeleteWord())); #else QShortcut *shortcut = new QShortcut(QKeySequence(QKeySequence::Delete), dic_content_); connect(shortcut, SIGNAL(activated()), this, SLOT(DeleteWord())); #endif dic_content_->setContextMenuPolicy(Qt::CustomContextMenu); connect(dic_content_, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(OnContextMenuRequestedForContent(const QPoint &))); connect(dic_content_->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(OnHeaderClicked(int))); dic_list_->setContextMenuPolicy(Qt::CustomContextMenu); connect(dic_list_, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(OnContextMenuRequestedForList(const QPoint &))); // Set up the menu for dictionary related operations. new_action_ = dic_menu_->addAction(tr("New dictionary...")); rename_action_ = dic_menu_->addAction(tr("Rename dictionary...")); delete_action_ = dic_menu_->addAction(tr("Delete dictionary")); find_action_ = dic_menu_->addAction(tr("Find...")); dic_menu_->addSeparator(); import_create_action_ = dic_menu_->addAction(tr("Import as new dictionary...")); import_append_action_ = dic_menu_->addAction(tr("Import to current dictionary...")); export_action_ = dic_menu_->addAction(tr("Export current dictionary...")); // add Import from MS-IME's dictionary #ifdef OS_WIN dic_menu_->addSeparator(); import_default_ime_action_ = dic_menu_->addAction( tr("Import from %1's user dictionary...").arg("Microsoft IME")); #endif // OS_WIN dic_menu_button_->setMenu(dic_menu_); connect(new_action_, SIGNAL(triggered()), this, SLOT(CreateDictionary())); connect(rename_action_, SIGNAL(triggered()), this, SLOT(RenameDictionary())); connect(delete_action_, SIGNAL(triggered()), this, SLOT(DeleteDictionary())); connect(find_action_, SIGNAL(triggered()), find_dialog_, SLOT(show())); connect(import_create_action_, SIGNAL(triggered()), this, SLOT(ImportAndCreateDictionary())); connect(import_append_action_, SIGNAL(triggered()), this, SLOT(ImportAndAppendDictionary())); connect(export_action_, SIGNAL(triggered()), this, SLOT(ExportDictionary())); #ifdef OS_WIN connect(import_default_ime_action_, SIGNAL(triggered()), this, SLOT(ImportFromDefaultIME())); #endif // OS_WIN // Signals and slots to connect buttons to actions. connect(new_word_button_, SIGNAL(clicked()), this, SLOT(AddWord())); connect(delete_word_button_, SIGNAL(clicked()), this, SLOT(DeleteWord())); // When empty area of Dictionary Table is clicked, // insert a new word. This is only enabled on Mac connect(dic_content_, SIGNAL(emptyAreaClicked()), this, SLOT(AddWord())); // Signals and slots to update state of objects on the window in // response to change of selection/data of items. connect(dic_list_, SIGNAL(itemSelectionChanged()), this, SLOT(OnDictionarySelectionChanged())); // Initialize the list widget for a list of dictionaries. InitDictionaryList(); if (dic_list_->count() != 0) { dic_list_->setCurrentRow(0); } else { // Make sure that the table widget is initialized when there is no // dictionary. OnDictionarySelectionChanged(); } // Adjust the splitter. splitter_->setSizes(QList<int>() << static_cast<int>(width() * 0.25) << static_cast<int>(width() * 0.75)); // adjust column width dic_content_->setColumnWidth(0, static_cast<int>(width() * 0.18)); dic_content_->setColumnWidth(1, static_cast<int>(width() * 0.18)); dic_content_->setColumnWidth(2, static_cast<int>(width() * 0.18)); sort_state_.sorted = false; // If this is the first time for the user dictionary is used, create // a default dictionary. if (!session_->mutable_storage()->Exists()) { CreateDictionaryHelper(tr("User Dictionary 1")); } // for Mac-like style #ifdef __APPLE__ setUnifiedTitleAndToolBarOnMac(true); #endif StartMonitoringUserEdit(); UpdateUIStatus(); GuiUtil::ReplaceWidgetLabels(this); qApp->installEventFilter(this); } DictionaryTool::~DictionaryTool() {} void DictionaryTool::closeEvent(QCloseEvent *event) { // QEvent::ApplicationDeactivate is not emitted here. // Change the focus so that the last incomplete itmes on // TableView is submitted to the model dic_menu_button_->setFocus(Qt::MouseFocusReason); SyncToStorage(); SaveAndReloadServer(); if (session_->mutable_storage()->GetLastError() == mozc::UserDictionaryStorage::TOO_BIG_FILE_BYTES) { QMessageBox::warning( this, window_title_, tr("Making dangerously large user dictionary file. " "If the dictionary file turns out to be larger than 256Mbyte, " "the dictionary loader skips to handle all the words to prevent " "the converter from being halted.")); } } void DictionaryTool::OnDeactivate() { SyncToStorage(); SaveAndReloadServer(); } bool DictionaryTool::eventFilter(QObject *obj, QEvent *event) { // When application focus leaves, reload the server so // that new dictionary can be loaded. // This is an approximation of dynamic relading. // // We cannot call OnDeactivate() inside event filter, // as pending changes are not correctly synced to the disk. // Seems that all pending changes are committed to the UI // AFTER DictionaryTool receives ApplicationDeactivate event. // Here we delayed the execution of OnDeactivate() using QTimer. // This is an workaround for http://b/2190275. // TODO(taku): Find out a better way. if (event->type() == QEvent::ApplicationDeactivate) { const int kDelayOnDeactivateTime = 200; QTimer::singleShot(kDelayOnDeactivateTime, this, SLOT(OnDeactivate())); } return QWidget::eventFilter(obj, event); } void DictionaryTool::OnDictionarySelectionChanged() { SyncToStorage(); DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { current_dic_id_ = 0; StopMonitoringUserEdit(); dic_content_->clearContents(); dic_content_->setRowCount(0); dic_content_->setEnabled(false); StartMonitoringUserEdit(); new_word_button_->setEnabled(false); delete_word_button_->setEnabled(false); rename_action_->setEnabled(false); delete_action_->setEnabled(false); import_append_action_->setEnabled(false); export_action_->setEnabled(false); } else { current_dic_id_ = dic_info.id; max_entry_size_ = mozc::UserDictionaryStorage::max_entry_size(); SetupDicContentEditor(dic_info); } } void DictionaryTool::SetupDicContentEditor(const DictionaryInfo &dic_info) { UserDictionary *dic = session_->mutable_storage()->GetUserDictionary(dic_info.id); if (dic == nullptr) { LOG(ERROR) << "Failed to load the dictionary: " << dic_info.id; ReportError(); return; } // Update the main table widget for dictionary contents. StopMonitoringUserEdit(); rename_action_->setEnabled(true); delete_action_->setEnabled(true); import_append_action_->setEnabled(true); export_action_->setEnabled(true); setUpdatesEnabled(false); dic_content_->clearContents(); dic_content_->setRowCount(dic->entries_size()); { std::unique_ptr<QProgressDialog> progress(CreateProgressDialog( tr("Updating the current view data..."), this, dic->entries_size())); for (size_t i = 0; i < dic->entries_size(); ++i) { const UserDictionary::Entry &entry = dic->entries(i); dic_content_->setItem(i, 0, new QTableWidgetItem(QUtf8(entry.key()))); dic_content_->setItem(i, 1, new QTableWidgetItem(QUtf8(entry.value()))); dic_content_->setItem( i, 2, new QTableWidgetItem( QUtf8(UserDictionaryUtil::GetStringPosType(entry.pos())))); dic_content_->setItem(i, 3, new QTableWidgetItem(QUtf8(entry.comment()))); progress->setValue(i); } } setUpdatesEnabled(true); dic_content_->repaint(); dic_content_->setEnabled(true); StartMonitoringUserEdit(); // Update state of other GUI components. UpdateUIStatus(); const bool dictionary_is_full = dic_content_->rowCount() >= max_entry_size_; new_word_button_->setEnabled(!dictionary_is_full); modified_ = false; } void DictionaryTool::CreateDictionary() { const int max_size = static_cast<int>(mozc::UserDictionaryStorage::max_dictionary_size()); if (dic_list_->count() >= max_size) { QMessageBox::critical( this, window_title_, tr("You can't have more than %1 dictionaries.").arg(max_size)); return; } const QString dic_name = PromptForDictionaryName( QLatin1String(""), tr("Name of the new dictionary")); if (dic_name.isEmpty()) { return; // canceld by user } SyncToStorage(); CreateDictionaryHelper(dic_name); } void DictionaryTool::DeleteDictionary() { DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { QMessageBox::information(this, window_title_, tr("No dictionary is selected.")); return; } if (QMessageBox::question( this, window_title_, tr("Do you want to delete %1?").arg(dic_info.item->text()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { return; } if (!session_->mutable_storage()->DeleteDictionary(dic_info.id)) { LOG(ERROR) << "Failed to delete the dictionary."; ReportError(); return; } modified_ = false; QListWidgetItem *item = dic_list_->takeItem(dic_info.row); delete item; UpdateUIStatus(); } void DictionaryTool::RenameDictionary() { DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { QMessageBox::information(this, window_title_, tr("No dictionary is selected.")); return; } const QString dic_name = PromptForDictionaryName( dic_info.item->text(), tr("New name of the dictionary")); if (dic_name.isEmpty()) { return; } if (!session_->mutable_storage()->RenameDictionary(dic_info.id, dic_name.toStdString())) { LOG(ERROR) << "Failed to rename the dictionary."; ReportError(); return; } dic_info.item->setText(dic_name); UpdateUIStatus(); } void DictionaryTool::ImportAndCreateDictionary() { const int max_size = static_cast<int>(mozc::UserDictionaryStorage::max_dictionary_size()); if (dic_list_->count() >= max_size) { QMessageBox::critical( this, window_title_, tr("You can't have more than %1 dictionaries.").arg(max_size)); return; } // Get necessary information from the user. if (import_dialog_->ExecInCreateMode() != QDialog::Accepted) { LOG(WARNING) << "Cancele by the user."; return; } ImportHelper(0, // dic_id == 0 means that "CreateNewDictonary" mode import_dialog_->dic_name().toStdString(), import_dialog_->file_name().toStdString(), import_dialog_->ime_type(), import_dialog_->encoding_type()); } void DictionaryTool::ImportAndAppendDictionary() { DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { LOG(WARNING) << "No dictionary to import is selected"; QMessageBox::information(this, window_title_, tr("No dictionary is selected.")); return; } if (dic_content_->rowCount() >= max_entry_size_) { QMessageBox::critical(this, window_title_, tr("You can't have more than %1 " "words in one dictionary.") .arg(max_entry_size_)); return; } if (import_dialog_->ExecInAppendMode() != QDialog::Accepted) { LOG(WARNING) << "Cancele by the user."; return; } ImportHelper(dic_info.id, dic_info.item->text().toStdString(), import_dialog_->file_name().toStdString(), import_dialog_->ime_type(), import_dialog_->encoding_type()); } void DictionaryTool::ReportImportError(UserDictionaryImporter::ErrorType error, const std::string &dic_name, int added_entries_size) { switch (error) { case UserDictionaryImporter::IMPORT_NO_ERROR: QMessageBox::information(this, window_title_, tr("%1 entries are imported to %2.") .arg(added_entries_size) .arg(QUtf8(dic_name))); break; case UserDictionaryImporter::IMPORT_NOT_SUPPORTED: QMessageBox::information(this, window_title_, tr("You have imported a file in an invalid or " "unsupported file format.\n\n" "Please check the file format. " "ATOK11 or older format is not supported by " "%1.").arg(GuiUtil::ProductName())); break; case UserDictionaryImporter::IMPORT_TOO_MANY_WORDS: QMessageBox::information( this, window_title_, tr("%1 doesn't have enough space to import all words in " "the file. First %2 entries " "are imported.") .arg(QUtf8(dic_name)) .arg(added_entries_size)); break; case UserDictionaryImporter::IMPORT_INVALID_ENTRIES: QMessageBox::information( this, window_title_, tr("%1 entries are imported to %2.\n\nSome imported " "words were not recognized by %3. " "Please check the original import file.") .arg(added_entries_size) .arg(QUtf8(dic_name)) .arg(window_title_)); break; case UserDictionaryImporter::IMPORT_FATAL: QMessageBox::critical(this, window_title_, tr("Failed to open user dictionary")); break; default: break; } } void DictionaryTool::ImportHelper( uint64_t dic_id, const std::string &dic_name, const std::string &file_name, UserDictionaryImporter::IMEType ime_type, UserDictionaryImporter::EncodingType encoding_type) { if (!IsReadableToImport(file_name)) { LOG(ERROR) << "File is not readable to import."; QMessageBox::critical(this, window_title_, tr("Can't open %1.").arg(QUtf8(file_name))); return; } if (dic_id == 0 && !session_->mutable_storage()->CreateDictionary(dic_name, &dic_id)) { LOG(ERROR) << "Failed to create the dictionary."; ReportError(); return; } UserDictionary *dic = session_->mutable_storage()->GetUserDictionary(dic_id); if (dic == nullptr) { LOG(ERROR) << "Cannot find dictionary id: " << dic_id; ReportError(); return; } if (dic->name() != dic_name) { LOG(ERROR) << "Dictionary name is inconsistent"; ReportError(); return; } // Everything looks Okey so far. Now starting import operation. SyncToStorage(); // Open dictionary std::unique_ptr<UserDictionaryImporter::TextLineIteratorInterface> iter( CreateTextLineIterator(encoding_type, file_name, this)); if (iter == nullptr) { LOG(ERROR) << "CreateTextLineIterator returns nullptr"; return; } const int old_size = dic->entries_size(); const UserDictionaryImporter::ErrorType error = UserDictionaryImporter::ImportFromTextLineIterator(ime_type, iter.get(), dic); const int added_entries_size = dic->entries_size() - old_size; // Update window state. InitDictionaryList(); for (int row = 0; row < dic_list_->count(); ++row) { if (dic_id == dic_list_->item(row)->data(Qt::UserRole).toULongLong()) { dic_list_->setCurrentRow(row); } } UpdateUIStatus(); ReportImportError(error, dic_name, added_entries_size); } void DictionaryTool::ImportFromDefaultIME() { #ifdef OS_WIN if (RunLevel::IsElevatedByUAC()) { // MS-IME's dictionary importer doesn't work if the current // process is already elevated by UAC. If user disables UAC< // it's not the case. Here we simply remove the MS-IME import function // if dictionary tool is UAC-elevated QMessageBox::warning(this, window_title_, tr("Microsoft IME dictionary import function doesn't " "work on UAC-elevated process.")); return; } DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { LOG(WARNING) << "No dictionary to import is selected"; QMessageBox::information(this, window_title_, tr("No dictionary is selected.")); return; } const QMessageBox::StandardButton answer = QMessageBox::information( this, window_title_, tr("All user-registered words in %1 " "are migrated into the " "current dictionary.") .arg("Microsoft IME"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (answer != QMessageBox::Ok) { LOG(WARNING) << "Cancele by the user."; return; } SyncToStorage(); UserDictionary *dic = session_->mutable_storage()->GetUserDictionary(dic_info.id); DCHECK(dic); const int old_size = dic->entries_size(); const std::string dic_name = dic_info.item->text().toStdString(); UserDictionaryImporter::ErrorType error = UserDictionaryImporter::IMPORT_NOT_SUPPORTED; { std::unique_ptr<UserDictionaryImporter::InputIteratorInterface> iter( MSIMEUserDictionarImporter::Create()); if (iter) { error = UserDictionaryImporter::ImportFromIterator(iter.get(), dic); } } const int added_entries_size = dic->entries_size() - old_size; OnDictionarySelectionChanged(); UpdateUIStatus(); ReportImportError(error, dic_name, added_entries_size); #endif } void DictionaryTool::ExportDictionary() { DictionaryInfo dic_info = current_dictionary(); if (dic_info.item == nullptr) { LOG(WARNING) << "No dictionary to export is selected"; QMessageBox::information(this, window_title_, tr("No dictionary is selected.")); return; } const std::string file_name = QFileDialog::getSaveFileName(this, tr("Export dictionary"), QDir::homePath(), tr("Text Files (*.txt);;All Files (*)")) .toStdString(); if (file_name.empty()) { return; } if (!IsWritableToExport(file_name)) { LOG(ERROR) << "File is not writable to export."; QMessageBox::critical(this, window_title_, tr("Can't open %1.").arg(QUtf8(file_name))); return; } SyncToStorage(); if (!session_->mutable_storage()->ExportDictionary(dic_info.id, file_name)) { LOG(ERROR) << "Failed to export the dictionary."; ReportError(); return; } QMessageBox::information(this, window_title_, tr("Dictionary export finished.")); } void DictionaryTool::AddWord() { const int row = dic_content_->rowCount(); if (row >= max_entry_size_) { QMessageBox::information( this, window_title_, tr("You can't have more than %1 words in one dictionary.") .arg(max_entry_size_)); return; } dic_content_->insertRow(row); dic_content_->setItem(row, 0, new QTableWidgetItem(QLatin1String(""))); dic_content_->setItem(row, 1, new QTableWidgetItem(QLatin1String(""))); dic_content_->setItem(row, 2, new QTableWidgetItem(default_pos_)); dic_content_->setItem(row, 3, new QTableWidgetItem(QLatin1String(""))); if (row + 1 >= max_entry_size_) { new_word_button_->setEnabled(false); } QTableWidgetItem *item = dic_content_->item(row, 0); dic_content_->setCurrentItem(item); dic_content_->editItem(item); UpdateUIStatus(); } void DictionaryTool::GetSortedSelectedRows(std::vector<int> *rows) const { DCHECK(rows); rows->clear(); const QList<QTableWidgetItem *> items = dic_content_->selectedItems(); if (items.empty()) { return; } rows->reserve(items.count()); for (int i = 0; i < items.size(); ++i) { rows->push_back(items[i]->row()); } std::sort(rows->begin(), rows->end(), std::greater<int>()); std::vector<int>::const_iterator end = std::unique(rows->begin(), rows->end()); rows->resize(end - rows->begin()); } QListWidgetItem *DictionaryTool::GetFirstSelectedDictionary() const { QList<QListWidgetItem *> selected_dicts = dic_list_->selectedItems(); if (selected_dicts.isEmpty()) { LOG(WARNING) << "No current dictionary."; return nullptr; } if (selected_dicts.size() > 1) { LOG(WARNING) << "Multiple items are selected."; } return selected_dicts[0]; } void DictionaryTool::DeleteWord() { std::vector<int> rows; GetSortedSelectedRows(&rows); if (rows.empty()) { return; } QString message; if (rows.size() == 1) { message = tr("Do you want to delete this word?"); } else { message = tr("Do you want to delete the selected words?"); } if (QMessageBox::question(this, window_title_, message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { return; } setUpdatesEnabled(false); { std::unique_ptr<QProgressDialog> progress(CreateProgressDialog( tr("Deleting the selected words..."), this, rows.size())); for (size_t i = 0; i < rows.size(); ++i) { dic_content_->removeRow(rows[i]); progress->setValue(i); } } setUpdatesEnabled(true); dic_content_->setEnabled(true); if (dic_content_->rowCount() < max_entry_size_) { new_word_button_->setEnabled(true); } UpdateUIStatus(); dic_content_->repaint(); modified_ = true; } void DictionaryTool::EditPOS(const std::string &pos) { const QList<QTableWidgetItem *> items = dic_content_->selectedItems(); if (items.empty()) { return; } const QString new_pos = QString::fromUtf8(pos.c_str()); setUpdatesEnabled(false); for (int i = 0; i < items.size(); ++i) { const int row = items[i]->row(); dic_content_->setItem(row, 2, new QTableWidgetItem(new_pos)); } setUpdatesEnabled(true); dic_content_->setEnabled(true); } void DictionaryTool::MoveTo(int dictionary_row) { UserDictionary *target_dict = nullptr; { const QListWidgetItem *selected_dict = GetFirstSelectedDictionary(); if (selected_dict == nullptr) { return; } QListWidgetItem *target_dict_item = dic_list_->item(dictionary_row); DCHECK(target_dict_item); if (target_dict_item == selected_dict) { LOG(WARNING) << "Target dictionary is the current dictionary."; return; } target_dict = session_->mutable_storage()->GetUserDictionary( target_dict_item->data(Qt::UserRole).toULongLong()); } std::vector<int> rows; GetSortedSelectedRows(&rows); if (rows.empty()) { return; } const size_t target_max_entry_size = mozc::UserDictionaryStorage::max_entry_size(); if (target_dict->entries_size() + rows.size() > target_max_entry_size) { QMessageBox::critical(this, window_title_, tr("Cannot move all the selected items.\n" "The target dictionary can have maximum " "%1 entries.") .arg(target_max_entry_size)); return; } setUpdatesEnabled(false); { // add |rows.size()| items and remove |rows.size()| items const int progress_max = rows.size() * 2; std::unique_ptr<QProgressDialog> progress(CreateProgressDialog( tr("Moving the selected words..."), this, progress_max)); int progress_index = 0; if (target_dict) { for (size_t i = 0; i < rows.size(); ++i) { UserDictionary::Entry *entry = target_dict->add_entries(); const int row = rows[i]; entry->set_key(dic_content_->item(row, 0)->text().toStdString()); entry->set_value(dic_content_->item(row, 1)->text().toStdString()); entry->set_pos(UserDictionaryUtil::ToPosType( dic_content_->item(row, 2)->text().toStdString().c_str())); entry->set_comment(dic_content_->item(row, 3)->text().toStdString()); UserDictionaryUtil::SanitizeEntry(entry); progress->setValue(progress_index); ++progress_index; } } for (size_t i = 0; i < rows.size(); ++i) { dic_content_->removeRow(rows[i]); progress->setValue(progress_index); ++progress_index; } } setUpdatesEnabled(true); dic_content_->setEnabled(true); UpdateUIStatus(); dic_content_->repaint(); modified_ = true; } void DictionaryTool::EditComment() { const QList<QTableWidgetItem *> items = dic_content_->selectedItems(); if (items.empty()) { return; } bool ok = false; const QString new_comment = QInputDialog::getText( this, window_title_, tr("New comment"), QLineEdit::Normal, QLatin1String(""), &ok, Qt::WindowTitleHint | Qt::WindowSystemMenuHint); if (!ok) { return; } setUpdatesEnabled(false); for (int i = 0; i < items.size(); ++i) { const int row = items[i]->row(); dic_content_->setItem(row, 3, new QTableWidgetItem(new_comment)); } setUpdatesEnabled(true); dic_content_->setEnabled(true); } void DictionaryTool::CloseWindow() { // move the focus to the close button to submit all incomplete inputs in // the word cells. http://b/211766 // This is reuqired for MacOSX new_word_button_->setFocus(); this->close(); } void DictionaryTool::OnItemChanged(QTableWidgetItem *item) { if (item->column() == 0 && !item->text().isEmpty() && !UserDictionaryUtil::IsValidReading(item->text().toStdString())) { QMessageBox::critical( this, window_title_, tr("An invalid character is included in the reading.")); } UpdateUIStatus(); sort_state_.sorted = false; modified_ = true; } void DictionaryTool::OnHeaderClicked(int logicalIndex) { if (sort_state_.sorted && sort_state_.column == logicalIndex && sort_state_.order == Qt::AscendingOrder) { dic_content_->sortItems(logicalIndex, Qt::DescendingOrder); sort_state_.order = Qt::DescendingOrder; } else { dic_content_->sortItems(logicalIndex, Qt::AscendingOrder); sort_state_.sorted = true; sort_state_.column = logicalIndex; sort_state_.order = Qt::AscendingOrder; } modified_ = true; } void DictionaryTool::OnContextMenuRequestedForContent(const QPoint &pos) { QTableWidgetItem *item = dic_content_->itemAt(pos); // When the mouse pointer is not on an item of the table widget, we // don't show context menu. if (item == nullptr) { return; } QMenu *menu = new QMenu(this); QAction *add_action = menu->addAction(tr("Add a word")); // Count the number of selected words and create delete menu with an // appropriate text. const QList<QTableWidgetItem *> items = dic_content_->selectedItems(); QString delete_menu_text = tr("Delete this word"); QString move_to_menu_text = tr("Move this word to"); if (!items.empty()) { const int first_row = items[0]->row(); for (int i = 1; i < items.size(); ++i) { if (items[i]->row() != first_row) { // More than one words are selected. delete_menu_text = tr("Delete the selected words"); move_to_menu_text = tr("Move the selected words to"); break; } } } std::vector<std::pair<int, QAction *> > change_dictionary_actions; // "Move to" is available only when we have 2 or more dictionaries. if (dic_list_->count() > 1) { QMenu *move_to = menu->addMenu(move_to_menu_text); change_dictionary_actions.reserve(dic_list_->count() - 1); { const QListWidgetItem *selected_dict = GetFirstSelectedDictionary(); if (selected_dict != nullptr) { for (size_t i = 0; i < dic_list_->count(); ++i) { QListWidgetItem *item = dic_list_->item(i); DCHECK(item); if (item == selected_dict) { // Do not add the current dictionary into the "Move to" list. continue; } change_dictionary_actions.push_back( std::make_pair(i, move_to->addAction(item->text()))); } } } } QAction *delete_action = menu->addAction(delete_menu_text); menu->addSeparator(); QMenu *change_category_to = menu->addMenu(tr("Change category to")); std::vector<std::string> pos_list; pos_list_provider_->GetPOSList(&pos_list); std::vector<QAction *> change_pos_actions(pos_list.size()); for (size_t i = 0; i < pos_list.size(); ++i) { change_pos_actions[i] = change_category_to->addAction(QString::fromUtf8(pos_list[i].c_str())); } QAction *edit_comment_action = menu->addAction(tr("Edit comment")); QAction *selected_action = menu->exec(QCursor::pos()); if (selected_action == add_action) { AddWord(); } else if (selected_action == delete_action) { DeleteWord(); } else if (selected_action == edit_comment_action) { EditComment(); } else { bool found = false; for (int i = 0; i < change_pos_actions.size(); ++i) { if (selected_action == change_pos_actions[i]) { EditPOS(pos_list[i]); found = true; break; } } if (!found) { for (int i = 0; i < change_dictionary_actions.size(); ++i) { if (selected_action == change_dictionary_actions[i].second) { MoveTo(change_dictionary_actions[i].first); found = true; break; } } } } } void DictionaryTool::OnContextMenuRequestedForList(const QPoint &pos) { QListWidgetItem *item = dic_list_->itemAt(pos); if (item == nullptr) { return; } QMenu *menu = new QMenu(this); QAction *rename_action = menu->addAction(tr("Rename...")); QAction *delete_action = menu->addAction(tr("Delete")); QAction *import_action = menu->addAction(tr("Import to this dictionary...")); QAction *export_action = menu->addAction(tr("Export this dictionary...")); QAction *selected_action = menu->exec(QCursor::pos()); if ((rename_action != nullptr) && (selected_action == rename_action)) { RenameDictionary(); } else if ((delete_action != nullptr) && (selected_action == delete_action)) { DeleteDictionary(); } else if ((import_action != nullptr) && (selected_action == import_action)) { ImportAndAppendDictionary(); } else if ((export_action != nullptr) && (selected_action == export_action)) { ExportDictionary(); } } DictionaryTool::DictionaryInfo DictionaryTool::current_dictionary() const { DictionaryInfo retval = {-1, 0, nullptr}; QListWidgetItem *selected_dict = GetFirstSelectedDictionary(); if (selected_dict == nullptr) { return retval; } retval.row = dic_list_->row(selected_dict); retval.id = selected_dict->data(Qt::UserRole).toULongLong(); retval.item = selected_dict; return retval; } void DictionaryTool::SyncToStorage() { if (current_dic_id_ == 0 || !modified_) { return; } UserDictionary *dic = session_->mutable_storage()->GetUserDictionary(current_dic_id_); if (dic == nullptr) { LOG(ERROR) << "No save dictionary: " << current_dic_id_; return; } dic->clear_entries(); for (int i = 0; i < dic_content_->rowCount(); ++i) { UserDictionary::Entry *entry = dic->add_entries(); entry->set_key(dic_content_->item(i, 0)->text().toStdString()); entry->set_value(dic_content_->item(i, 1)->text().toStdString()); entry->set_pos(UserDictionaryUtil::ToPosType( dic_content_->item(i, 2)->text().toStdString().c_str())); entry->set_comment(dic_content_->item(i, 3)->text().toStdString()); UserDictionaryUtil::SanitizeEntry(entry); } modified_ = false; } void DictionaryTool::CreateDictionaryHelper(const QString &dic_name) { uint64_t new_dic_id = 0; if (!session_->mutable_storage()->CreateDictionary(dic_name.toStdString(), &new_dic_id)) { LOG(ERROR) << "Failed to create a new dictionary."; ReportError(); return; } QListWidgetItem *item = new QListWidgetItem(dic_list_); DCHECK(item); item->setText(dic_name); item->setData(Qt::UserRole, QVariant(static_cast<qulonglong>(new_dic_id))); dic_list_->setCurrentRow(dic_list_->row(item)); AddWord(); } bool DictionaryTool::InitDictionaryList() { dic_list_->clear(); const UserDictionaryStorage &storage = session_->storage(); for (size_t i = 0; i < storage.dictionaries_size(); ++i) { QListWidgetItem *item = new QListWidgetItem(dic_list_); DCHECK(item); item->setText(storage.dictionaries(i).name().c_str()); item->setData( Qt::UserRole, QVariant(static_cast<qulonglong>(storage.dictionaries(i).id()))); } UpdateUIStatus(); return true; } QString DictionaryTool::PromptForDictionaryName(const QString &text, const QString &label) { bool ok = false; QString dic_name; do { dic_name = QInputDialog::getText( this, window_title_, label, QLineEdit::Normal, text, &ok, // To disable context help on Windows. Qt::WindowTitleHint | Qt::WindowSystemMenuHint); } while (ok && dic_name.isEmpty()); if (!ok) { LOG(WARNING) << "Canceled by the user."; return ""; } return dic_name; } void DictionaryTool::ReportError() { switch (session_->mutable_storage()->GetLastError()) { case mozc::UserDictionaryStorage::INVALID_CHARACTERS_IN_DICTIONARY_NAME: LOG(ERROR) << "Dictionary name contains an invalid character."; QMessageBox::critical( this, window_title_, tr("An invalid character is included in the dictionary name.")); break; case mozc::UserDictionaryStorage::EMPTY_DICTIONARY_NAME: LOG(ERROR) << "Dictionary name is empty."; QMessageBox::critical(this, window_title_, tr("Dictionary name is empty.")); break; case mozc::UserDictionaryStorage::TOO_LONG_DICTIONARY_NAME: LOG(ERROR) << "Dictionary name is too long."; QMessageBox::critical(this, window_title_, tr("Dictionary name is too long.")); break; case mozc::UserDictionaryStorage::DUPLICATED_DICTIONARY_NAME: LOG(ERROR) << "duplicated dictionary name"; QMessageBox::critical(this, window_title_, tr("Dictionary already exists.")); break; default: LOG(ERROR) << "A fatal error occurred"; QMessageBox::critical(this, window_title_, tr("A fatal error occurred.")); break; } } void DictionaryTool::StartMonitoringUserEdit() { if (monitoring_user_edit_) { return; } connect(dic_content_, SIGNAL(itemChanged(QTableWidgetItem *)), this, SLOT(OnItemChanged(QTableWidgetItem *))); monitoring_user_edit_ = true; } void DictionaryTool::StopMonitoringUserEdit() { if (!monitoring_user_edit_) { return; } disconnect(dic_content_, SIGNAL(itemChanged(QTableWidgetItem *)), this, SLOT(OnItemChanged(QTableWidgetItem *))); monitoring_user_edit_ = false; } void DictionaryTool::SaveAndReloadServer() { if (!session_->mutable_storage()->Save() && session_->mutable_storage()->GetLastError() == mozc::UserDictionaryStorage::SYNC_FAILURE) { LOG(ERROR) << "Cannot save dictionary"; return; } // If server is not running, we don't need to // execute Reload command. if (!client_->PingServer()) { LOG(WARNING) << "Server is not running. Do nothing"; return; } // Update server version if need be. if (!client_->CheckVersionOrRestartServer()) { LOG(ERROR) << "CheckVersionOrRestartServer failed"; return; } // We don't show any dialog even when an error happens, since // dictionary serialization is finished correctly. if (!client_->Reload()) { LOG(ERROR) << "Reload command failed"; } } bool DictionaryTool::IsReadableToImport(const std::string &file_name) { QFileInfo file_info(QUtf8(file_name)); return file_info.isFile() && file_info.isReadable(); } bool DictionaryTool::IsWritableToExport(const std::string &file_name) { QFileInfo file_info(QUtf8(file_name)); if (file_info.exists()) { return file_info.isFile() && file_info.isWritable(); } else { QFileInfo dir_info(file_info.dir().absolutePath()); // This preprocessor conditional is a workaround for a problem // that export fails on Windows. #ifdef OS_WIN return dir_info.isExecutable(); #else return dir_info.isExecutable() && dir_info.isWritable(); #endif } } void DictionaryTool::UpdateUIStatus() { const bool is_enable_new_dic = dic_list_->count() < session_->mutable_storage()->max_dictionary_size(); new_action_->setEnabled(is_enable_new_dic); import_create_action_->setEnabled(is_enable_new_dic); delete_action_->setEnabled(dic_list_->count() > 0); import_append_action_->setEnabled(dic_list_->count() > 0); #ifdef OS_WIN import_default_ime_action_->setEnabled(dic_list_->count() > 0); #endif const bool is_enable_new_word = dic_list_->count() > 0 && dic_content_->rowCount() < max_entry_size_; new_word_button_->setEnabled(is_enable_new_word); delete_word_button_->setEnabled(dic_content_->rowCount() > 0); const DictionaryInfo dic_info = current_dictionary(); if (dic_info.item != nullptr) { statusbar_message_ = QString(tr("%1: %2 entries")) .arg(dic_info.item->text()) .arg(dic_content_->rowCount()); } else { statusbar_message_.clear(); } statusbar_->showMessage(statusbar_message_); } } // namespace gui } // namespace mozc
32.722049
80
0.670822
[ "object", "vector", "model" ]
0e995539fa41ad1d87df7ba4bd8d801346f96251
3,676
hpp
C++
libs/glm/irls.hpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
1
2015-10-21T14:22:12.000Z
2015-10-21T14:22:12.000Z
libs/glm/irls.hpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2019-05-26T20:52:31.000Z
2019-05-28T16:19:49.000Z
libs/glm/irls.hpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2016-11-06T14:58:37.000Z
2019-05-26T14:03:13.000Z
#ifndef __IRLS_H__ #define __IRLS_H__ #include <armadillo> #include <glm/glm_info.hpp> #include <glm/models/glm_model.hpp> /** * Maximum number of iterations in the IRLS algorithm. */ static const int IRLS_MAX_ITERS = 25; /** * Smallest change in likelihood before terminating the IRLS algorithm. */ static double IRLS_TOLERANCE = 10e-8; /** * Sets the weights of missing observations to zero, so that * the will not influence the regression. * * @param missing Missing individuals are indicated by 1. * @param w Vector of weights, missing entries will be replaced by 0. */ void set_missing_to_zero(const arma::uvec &missing, arma::vec &w); /** * Compute the chisquare cdf for a vector of chi square variables. * * @param x Vector of chi square values. * @param df Degrees of freedom. * * @return Vector of corresponding p-values. */ arma::vec chi_square_cdf(const arma::vec &x, unsigned int df); /** * Solves the weighted least square problem: * * W*X*W*b = X*W*y * * The algorithm uses the singular value decomposition, to * compute the solution b: * * b = V * S^-1 * U^t sqrt( w ) * y * * where wX = U S V^t * * @param X The design matrix. * @param y The right hand side. * @param w The weight for each observation. * @param fast_inversion If true use less robust but faster inversion. * * @return The vector b that minimizes the weighted least squares problem. */ arma::vec weighted_least_squares(const arma::mat &X, const arma::vec &y, const arma::vec &w, bool fast_inversion = false); /** * Compute the adjusted dependent variates in the Iteratively reweighted * least squares algorithm. * * @param eta The linearized parameter. * @param mu The mean value parameter. * @param mu_eta The derivative of mu with respect to eta. * @param y The observations. * * @return The adjusted dependent variates. */ arma::vec compute_z(const arma::vec &eta, const arma::vec &mu, const arma::vec &mu_eta, const arma::vec &y); /** * Compute the weight vector that is used in one iteration * in the Iteratively reweighted least squares algorithm. * * @param var Variance of each observation. * @param mu_eta The derivative of mu with respect to eta. * * @return A weight vector. */ arma::vec compute_w(const arma::vec &var, const arma::vec& mu_eta); /** * This function performs the iteratively reweighted * least squares algorithm to estimate beta coefficients * of a genearlized linear model. * * @param X The design matrix (caller is responsible for * adding an intercept). * @param y The observations. * @param model The GLM model to estimate. * @param output Output statistics of the estimated betas. * @param fast_inversion If true use less robust but faster inversion. * * @return Estimated beta coefficients. */ arma::vec irls(const arma::mat &X, const arma::vec &y, const glm_model &model, glm_info &output, bool fast_inversion = false); /** * This function performs the iteratively reweighted * least squares algorithm to estimate beta coefficients * of a genearlized linear model. * * @param X The design matrix (caller is responsible for * adding an intercept). * @param y The observations. * @param missing Identifies missing sampels by 1 and non-missing by 0. * @param model The GLM model to estimate. * @param output Output statistics of the estimated betas. * @param fast_inversion If true use less robust but faster inversion. * * @return Estimated beta coefficients. */ arma::vec irls(const arma::mat &X, const arma::vec &y, const arma::uvec &missing, const glm_model &model, glm_info &output, bool fast_inversion = false); #endif /* End of __IRLS_H__ */
31.418803
153
0.718172
[ "vector", "model" ]
0e9a9f53d31bccb928c96caff66152028e05ca7c
14,227
cpp
C++
source/screens/activity.cpp
ELY3M/NX-Activity-Log
daf8133c24acebfacaf31c8e87f48d8eb981d78c
[ "MIT" ]
null
null
null
source/screens/activity.cpp
ELY3M/NX-Activity-Log
daf8133c24acebfacaf31c8e87f48d8eb981d78c
[ "MIT" ]
null
null
null
source/screens/activity.cpp
ELY3M/NX-Activity-Log
daf8133c24acebfacaf31c8e87f48d8eb981d78c
[ "MIT" ]
null
null
null
#include "activity.hpp" #include "ui/list.hpp" #include "ui/listitem.hpp" #include "SDLHelper.hpp" #include <switch.h> #include "theme.hpp" #include "utils.hpp" namespace Screen { Activity::Activity(bool * b, User * u, std::vector<Title *> tls) : Screen::Screen(b) { u32 total_mins = 0; this->list = new UI::List(&this->touch_active, 400, 100, 850, 550); for (size_t i = 0; i < tls.size(); i++) { this->list->addItem(new UI::ListItem(tls[i])); total_mins += tls[i]->getPlaytime(); } // Sort list by most played this->list->sort(HoursAsc); // Create total hours texture std::string str = "Total Playtime: "; str += Utils::formatPlaytime(total_mins); this->total_hours = SDLHelper::renderText(str.c_str(), BODY_FONT_SIZE); // Create side menu this->menu = new UI::SideMenu(&this->touch_active, 30, 130, 400, 500); this->menu->addItem(new UI::SideItem("Play Activity")); this->menu->addItem(new UI::SideItem("Settings")); this->user = u; this->controls->reset(); this->controls->add(KEY_PLUS, "Exit", 0); this->controls->add(KEY_MINUS, "Sort", 1); // Set active element this->active_element = (int)ActiveElement::SideMenu; this->menu->setActive(true); this->list->setActive(false); } void Activity::event(){ // Poll events SDL_Event events; while (SDL_PollEvent(&events)) { switch (events.type) { // Button pressed case SDL_JOYBUTTONDOWN: // Break on first press (ie. only active highlighting) if (this->touch_active && events.jbutton.which != 99) { if (!(events.jbutton.button >= Utils::key_map[KEY_LSTICK_LEFT] && events.jbutton.button <= Utils::key_map[KEY_RSTICK_DOWN])) { this->touch_active = false; } if (events.jbutton.button >= Utils::key_map[KEY_DLEFT] && events.jbutton.button <= Utils::key_map[KEY_DDOWN] && this->active_element != (int)ActiveElement::List) { break; } } if (events.jbutton.which == 0 || events.jbutton.which == 99) { // Joysticks push appropriate button event if (events.jbutton.button >= Utils::key_map[KEY_LSTICK_LEFT] && events.jbutton.button <= Utils::key_map[KEY_RSTICK_DOWN]) { SDL_Event event; event.type = SDL_JOYBUTTONDOWN; event.jbutton.which = 0; event.jbutton.state = SDL_PRESSED; if (events.jbutton.button == Utils::key_map[KEY_LSTICK_LEFT] || events.jbutton.button == Utils::key_map[KEY_RSTICK_LEFT]) { event.jbutton.button = Utils::key_map[KEY_DLEFT]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_RIGHT] || events.jbutton.button == Utils::key_map[KEY_RSTICK_RIGHT]) { event.jbutton.button = Utils::key_map[KEY_DRIGHT]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_UP] || events.jbutton.button == Utils::key_map[KEY_RSTICK_UP]) { event.jbutton.button = Utils::key_map[KEY_DUP]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_DOWN] || events.jbutton.button == Utils::key_map[KEY_RSTICK_DOWN]) { event.jbutton.button = Utils::key_map[KEY_DDOWN]; } SDL_PushEvent(&event); // Plus exits app } else if (events.jbutton.button == Utils::key_map[KEY_PLUS]) { *(this->loop) = false; // Minus changes sorting method } else if (events.jbutton.button == Utils::key_map[KEY_MINUS]) { switch (this->list->getSorting()) { case AlphaAsc: this->list->sort(HoursAsc); break; case HoursAsc: this->list->sort(HoursDec); break; case HoursDec: this->list->sort(LaunchAsc); break; case LaunchAsc: this->list->sort(LaunchDec); break; case LaunchDec: this->list->sort(FirstPlayed); break; case FirstPlayed: this->list->sort(LastPlayed); break; case LastPlayed: this->list->sort(AlphaAsc); break; } this->list->setPos(0); // Left and right will swap active element } else if (events.jbutton.button == Utils::key_map[KEY_DLEFT]) { this->active_element = (int)ActiveElement::SideMenu; this->menu->setActive(true); this->list->setActive(false); } else if (events.jbutton.button == Utils::key_map[KEY_DRIGHT]) { this->active_element = (int)ActiveElement::List; this->menu->setActive(false); this->list->setActive(true); // All other buttons get handled by active element } else { switch (this->active_element) { case (int)ActiveElement::SideMenu: this->menu->handleButton(events.jbutton.button, events.jbutton.state); break; case (int)ActiveElement::List: this->list->handleButton(events.jbutton.button, events.jbutton.state); break; } } } break; case SDL_JOYBUTTONUP: if (events.jbutton.which == 0) { // Joysticks push appropriate button event if (events.jbutton.button >= Utils::key_map[KEY_LSTICK_LEFT] && events.jbutton.button <= Utils::key_map[KEY_RSTICK_DOWN]) { SDL_Event event; event.type = SDL_JOYBUTTONUP; event.jbutton.which = 0; event.jbutton.state = SDL_RELEASED; if (events.jbutton.button == Utils::key_map[KEY_LSTICK_LEFT] || events.jbutton.button == Utils::key_map[KEY_RSTICK_LEFT]) { event.jbutton.button = Utils::key_map[KEY_DLEFT]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_RIGHT] || events.jbutton.button == Utils::key_map[KEY_RSTICK_RIGHT]) { event.jbutton.button = Utils::key_map[KEY_DRIGHT]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_UP] || events.jbutton.button == Utils::key_map[KEY_RSTICK_UP]) { event.jbutton.button = Utils::key_map[KEY_DUP]; } else if (events.jbutton.button == Utils::key_map[KEY_LSTICK_DOWN] || events.jbutton.button == Utils::key_map[KEY_RSTICK_DOWN]) { event.jbutton.button = Utils::key_map[KEY_DDOWN]; } SDL_PushEvent(&event); // All other buttons get handled by active element } else { switch (this->active_element) { case (int)ActiveElement::SideMenu: this->menu->handleButton(events.jbutton.button, events.jbutton.state); break; case (int)ActiveElement::List: this->list->handleButton(events.jbutton.button, events.jbutton.state); break; } } } break; // Touch (pressed) case SDL_FINGERDOWN: { this->touch_active = true; float x = WIDTH * events.tfinger.x; float y = HEIGHT * events.tfinger.y; // Pressed within list if (x >= this->list->getX() && x <= this->list->getX() + this->list->getW() && y >= this->list->getY() && y <= this->list->getY() + this->list->getH()) { this->list->touched(events.type, x, y); this->active_element = (int)ActiveElement::List; this->menu->setActive(false); this->list->setActive(true); // Pressed within menu } else if (x >= this->menu->getX() && x <= this->menu->getX() + this->menu->getW() && y >= this->menu->getY() && y <= this->menu->getY() + this->menu->getH()) { this->menu->touched(events.type, x, y); this->active_element = (int)ActiveElement::SideMenu; this->menu->setActive(true); this->list->setActive(false); // Pass event to controls object if below bottom line } else if (y > 647) { this->controls->touched(events.type, x, y); } break; } // Touch (moved) case SDL_FINGERMOTION: { float x = WIDTH * events.tfinger.x; float y = HEIGHT * events.tfinger.y; float dx = WIDTH * events.tfinger.dx; float dy = HEIGHT * events.tfinger.dy; // List scrolling overrides any other actions if (this->list->isTouched()) { this->list->touched(events.type, x, y, dx, dy); // Moved after being in menu } else if ((x-dx) >= this->menu->getX() && (x-dx) <= this->menu->getX() + this->menu->getW() && (y-dy) >= this->menu->getY() && (y-dy) <= this->menu->getY() + this->menu->getH()) { this->menu->touched(events.type, x, y); } else { // Pass event to controls object if was below or originally below line if (y > 647 || (HEIGHT * (events.tfinger.y - events.tfinger.dy)) > 647) { this->controls->touched(events.type, x, y); } } break; } // Touch (released) case SDL_FINGERUP: { float x = WIDTH * events.tfinger.x; float y = HEIGHT * events.tfinger.y; if (this->list->isTouched()) { this->list->touched(events.type, x, y, (WIDTH * events.tfinger.dx), (HEIGHT * events.tfinger.dy)); // Released within menu } else if (x >= this->menu->getX() && x <= this->menu->getX() + this->menu->getW() && y >= this->menu->getY() && y <= this->menu->getY() + this->menu->getH()) { this->menu->touched(events.type, x, y); } else { // Pass event to controls object if below bottom line if (y > 647) { this->controls->touched(events.type, x, y); } } break; } } } } void Activity::update(uint32_t dt) { Screen::update(dt); this->menu->update(dt); this->list->update(dt); } void Activity::draw() { // Clear screen (draw background) SDLHelper::setColour(this->theme->getBG()); SDLHelper::clearScreen(); // Draw menu this->menu->draw(); // Different shade behind list SDLHelper::setColour(this->theme->getAltBG()); SDLHelper::drawRect(400, 88, 850, 560); // Draw list of items this->list->draw(); // Draw over list to hide scrolling SDLHelper::setColour(this->theme->getBG()); SDLHelper::drawRect(430, 0, 780, 87); SDLHelper::drawRect(430, 648, 1220, 72); // Draw top and bottom lines SDLHelper::setColour(this->theme->getFG()); SDLHelper::drawRect(30, 87, 1220, 1); SDLHelper::drawRect(30, 647, 1220, 1); // Draw player icon SDLHelper::drawTexture(this->user->getImage(), 65, 14, 60, 60); // Print heading std::string str = this->user->getUsername() + "'s Activity"; SDLHelper::drawText(str.c_str(), this->theme->getText(), 150, 44 - (HEADING_FONT_SIZE/2), HEADING_FONT_SIZE); // Print total hours int tw, th; SDLHelper::getDimensions(this->total_hours, &tw, &th); SDLHelper::drawTexture(this->total_hours, this->theme->getMutedText(), 1215 - tw, 44 - th/2); // Draw controls this->controls->draw(); } Activity::~Activity() { delete this->list; delete this->menu; } }
48.391156
200
0.458846
[ "object", "vector" ]
0e9cbf7654a93a0972aade479889f575a31dfdb6
12,837
cc
C++
ash/system/bluetooth/bluetooth_detailed_view.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/system/bluetooth/bluetooth_detailed_view.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/system/bluetooth/bluetooth_detailed_view.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/bluetooth/bluetooth_detailed_view.h" #include <map> #include <memory> #include <utility> #include "ash/public/cpp/system_tray_client.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/machine_learning/user_settings_event_logger.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/tray/hover_highlight_view.h" #include "ash/system/tray/tray_info_label.h" #include "ash/system/tray/tray_popup_item_style.h" #include "ash/system/tray/tray_popup_utils.h" #include "base/strings/utf_string_conversions.h" #include "services/device/public/cpp/bluetooth/bluetooth_utils.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/layout/box_layout.h" using device::mojom::BluetoothDeviceInfo; using device::mojom::BluetoothSystem; namespace ash { namespace tray { namespace { const int kDisabledPanelLabelBaselineY = 20; // Returns corresponding device type icons for given Bluetooth device types and // connection states. const gfx::VectorIcon& GetBluetoothDeviceIcon( BluetoothDeviceInfo::DeviceType device_type, BluetoothDeviceInfo::ConnectionState connection_state) { switch (device_type) { case BluetoothDeviceInfo::DeviceType::kComputer: return ash::kSystemMenuComputerIcon; case BluetoothDeviceInfo::DeviceType::kPhone: return ash::kSystemMenuPhoneIcon; case BluetoothDeviceInfo::DeviceType::kAudio: case BluetoothDeviceInfo::DeviceType::kCarAudio: return ash::kSystemMenuHeadsetIcon; case BluetoothDeviceInfo::DeviceType::kVideo: return ash::kSystemMenuVideocamIcon; case BluetoothDeviceInfo::DeviceType::kJoystick: case BluetoothDeviceInfo::DeviceType::kGamepad: return ash::kSystemMenuGamepadIcon; case BluetoothDeviceInfo::DeviceType::kKeyboard: case BluetoothDeviceInfo::DeviceType::kKeyboardMouseCombo: return ash::kSystemMenuKeyboardIcon; case BluetoothDeviceInfo::DeviceType::kTablet: return ash::kSystemMenuTabletIcon; case BluetoothDeviceInfo::DeviceType::kMouse: return ash::kSystemMenuMouseIcon; case BluetoothDeviceInfo::DeviceType::kModem: case BluetoothDeviceInfo::DeviceType::kPeripheral: return ash::kSystemMenuBluetoothIcon; default: return connection_state == BluetoothDeviceInfo::ConnectionState::kConnected ? ash::kSystemMenuBluetoothConnectedIcon : ash::kSystemMenuBluetoothIcon; } } views::View* CreateDisabledPanel() { views::View* container = new views::View; auto box_layout = std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical); box_layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); container->SetLayoutManager(std::move(box_layout)); TrayPopupItemStyle style(TrayPopupItemStyle::FontStyle::DETAILED_VIEW_LABEL); style.set_color_style(TrayPopupItemStyle::ColorStyle::DISABLED); views::ImageView* image_view = new views::ImageView; image_view->SetImage(gfx::CreateVectorIcon(kSystemMenuBluetoothDisabledIcon, style.GetIconColor())); image_view->SetVerticalAlignment(views::ImageView::Alignment::kTrailing); container->AddChildView(image_view); views::Label* label = new views::Label( l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_BLUETOOTH_DISABLED)); style.SetupLabel(label); label->SetBorder(views::CreateEmptyBorder( kDisabledPanelLabelBaselineY - label->GetBaseline(), 0, 0, 0)); container->AddChildView(label); // Make top padding of the icon equal to the height of the label so that the // icon is vertically aligned to center of the container. image_view->SetBorder( views::CreateEmptyBorder(label->GetPreferredSize().height(), 0, 0, 0)); return container; } void LogUserBluetoothEvent(const BluetoothAddress& device_address) { ml::UserSettingsEventLogger* logger = ml::UserSettingsEventLogger::Get(); if (logger) { logger->LogBluetoothUkmEvent(device_address); } } } // namespace BluetoothDetailedView::BluetoothDetailedView(DetailedViewDelegate* delegate, LoginStatus login) : TrayDetailedView(delegate), login_(login), toggle_(nullptr), settings_(nullptr), disabled_panel_(nullptr) { CreateItems(); } BluetoothDetailedView::~BluetoothDetailedView() = default; void BluetoothDetailedView::ShowLoadingIndicator() { // Setting a value of -1 gives progress_bar an infinite-loading behavior. ShowProgress(-1, true); } void BluetoothDetailedView::HideLoadingIndicator() { ShowProgress(0, false); } void BluetoothDetailedView::ShowBluetoothDisabledPanel() { device_map_.clear(); scroll_content()->RemoveAllChildViews(true); DCHECK(scroller()); if (!disabled_panel_) { disabled_panel_ = CreateDisabledPanel(); // Insert |disabled_panel_| before the scroller, since the scroller will // have unnecessary bottom border when it is not the last child. AddChildViewAt(disabled_panel_, GetIndexOf(scroller())); // |disabled_panel_| need to fill the remaining space below the title row // so that the inner contents of |disabled_panel_| are placed properly. box_layout()->SetFlexForView(disabled_panel_, 1); } disabled_panel_->SetVisible(true); scroller()->SetVisible(false); Layout(); } void BluetoothDetailedView::HideBluetoothDisabledPanel() { DCHECK(scroller()); if (disabled_panel_) disabled_panel_->SetVisible(false); scroller()->SetVisible(true); Layout(); } bool BluetoothDetailedView::IsDeviceScrollListEmpty() const { return device_map_.empty(); } void BluetoothDetailedView::UpdateDeviceScrollList( const BluetoothDeviceList& connected_devices, const BluetoothDeviceList& connecting_devices, const BluetoothDeviceList& paired_not_connected_devices, const BluetoothDeviceList& discovered_not_paired_devices) { connecting_devices_.clear(); for (const auto& device : connecting_devices) connecting_devices_.push_back(device->Clone()); paired_not_connected_devices_.clear(); for (const auto& device : paired_not_connected_devices) paired_not_connected_devices_.push_back(device->Clone()); base::Optional<BluetoothAddress> focused_device_address = GetFocusedDeviceAddress(); device_map_.clear(); scroll_content()->RemoveAllChildViews(true); // Add paired devices and their section header to the list. bool has_paired_devices = !connected_devices.empty() || !connecting_devices.empty() || !paired_not_connected_devices.empty(); if (has_paired_devices) { AddScrollListSubHeader(IDS_ASH_STATUS_TRAY_BLUETOOTH_PAIRED_DEVICES); AppendSameTypeDevicesToScrollList(connected_devices, true, true); AppendSameTypeDevicesToScrollList(connecting_devices, true, false); AppendSameTypeDevicesToScrollList(paired_not_connected_devices, false, false); } // Add unpaired devices to the list. If at least one paired device is // present, also add a section header above the unpaired devices. if (!discovered_not_paired_devices.empty()) { if (has_paired_devices) AddScrollListSubHeader(IDS_ASH_STATUS_TRAY_BLUETOOTH_UNPAIRED_DEVICES); AppendSameTypeDevicesToScrollList(discovered_not_paired_devices, false, false); } // Show user Bluetooth state if there is no bluetooth devices in list. if (device_map_.empty()) { scroll_content()->AddChildView(new TrayInfoLabel( nullptr /* delegate */, IDS_ASH_STATUS_TRAY_BLUETOOTH_DISCOVERING)); } // Focus the device which was focused before the device-list update. if (focused_device_address) FocusDeviceByAddress(focused_device_address.value()); scroll_content()->InvalidateLayout(); Layout(); } void BluetoothDetailedView::SetToggleIsOn(bool is_on) { if (toggle_) toggle_->AnimateIsOn(is_on); } const char* BluetoothDetailedView::GetClassName() const { return "BluetoothDetailedView"; } void BluetoothDetailedView::CreateItems() { CreateScrollableList(); CreateTitleRow(IDS_ASH_STATUS_TRAY_BLUETOOTH); } void BluetoothDetailedView::AppendSameTypeDevicesToScrollList( const BluetoothDeviceList& list, bool highlight, bool checked) { for (const auto& device : list) { const gfx::VectorIcon& icon = GetBluetoothDeviceIcon(device->device_type, device->connection_state); HoverHighlightView* container = AddScrollListItem( icon, device::GetBluetoothDeviceNameForDisplay(device)); container->SetAccessibleName( device::GetBluetoothDeviceLabelForAccessibility(device)); switch (device->connection_state) { case BluetoothDeviceInfo::ConnectionState::kNotConnected: break; case BluetoothDeviceInfo::ConnectionState::kConnecting: SetupConnectingScrollListItem(container); break; case BluetoothDeviceInfo::ConnectionState::kConnected: SetupConnectedScrollListItem( container, device->battery_info ? base::make_optional<uint8_t>( device->battery_info->battery_percentage) : base::nullopt); break; } device_map_[container] = device->address; } } bool BluetoothDetailedView::FoundDevice( const BluetoothAddress& device_address, const BluetoothDeviceList& device_list) const { for (const auto& device : device_list) { if (device->address == device_address) return true; } return false; } void BluetoothDetailedView::UpdateClickedDevice( const BluetoothAddress& device_address, views::View* item_container) { if (FoundDevice(device_address, paired_not_connected_devices_)) { HoverHighlightView* container = static_cast<HoverHighlightView*>(item_container); SetupConnectingScrollListItem(container); scroll_content()->SizeToPreferredSize(); scroller()->Layout(); } } void BluetoothDetailedView::ShowSettings() { if (TrayPopupUtils::CanOpenWebUISettings()) { CloseBubble(); // Deletes |this|. Shell::Get()->system_tray_model()->client()->ShowBluetoothSettings(); } } base::Optional<BluetoothAddress> BluetoothDetailedView::GetFocusedDeviceAddress() const { for (const auto& view_and_address : device_map_) { if (view_and_address.first->HasFocus()) return view_and_address.second; } return base::nullopt; } void BluetoothDetailedView::FocusDeviceByAddress( const BluetoothAddress& address) const { for (auto& view_and_address : device_map_) { if (view_and_address.second == address) { view_and_address.first->RequestFocus(); return; } } } void BluetoothDetailedView::HandleViewClicked(views::View* view) { TrayBluetoothHelper* helper = Shell::Get()->tray_bluetooth_helper(); if (helper->GetBluetoothState() != BluetoothSystem::State::kPoweredOn) return; std::map<views::View*, BluetoothAddress>::iterator find; find = device_map_.find(view); if (find == device_map_.end()) return; const BluetoothAddress& device_address = find->second; if (FoundDevice(device_address, connecting_devices_)) return; UpdateClickedDevice(device_address, view); LogUserBluetoothEvent(device_address); helper->ConnectToBluetoothDevice(device_address); } void BluetoothDetailedView::HandleButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == toggle_) { Shell::Get()->tray_bluetooth_helper()->SetBluetoothEnabled( toggle_->GetIsOn()); } else { DCHECK_EQ(settings_, sender); ShowSettings(); } } void BluetoothDetailedView::CreateExtraTitleRowButtons() { if (login_ == LoginStatus::LOCKED) return; DCHECK(!toggle_); DCHECK(!settings_); tri_view()->SetContainerVisible(TriView::Container::END, true); toggle_ = TrayPopupUtils::CreateToggleButton(this, IDS_ASH_STATUS_TRAY_BLUETOOTH); toggle_->SetIsOn(Shell::Get()->tray_bluetooth_helper()->GetBluetoothState() == BluetoothSystem::State::kPoweredOn); tri_view()->AddView(TriView::Container::END, toggle_); settings_ = CreateSettingsButton(IDS_ASH_STATUS_TRAY_BLUETOOTH_SETTINGS); tri_view()->AddView(TriView::Container::END, settings_); } } // namespace tray } // namespace ash
34.978202
80
0.733115
[ "model" ]
0ea03351337c9187a9143b8770be05ba6f997009
4,155
cc
C++
passes/techmap/dff2dffs.cc
jakobwenzel/yosys
984596c6bdac40fc2de4584a26ba5e1948f60a26
[ "0BSD" ]
null
null
null
passes/techmap/dff2dffs.cc
jakobwenzel/yosys
984596c6bdac40fc2de4584a26ba5e1948f60a26
[ "0BSD" ]
null
null
null
passes/techmap/dff2dffs.cc
jakobwenzel/yosys
984596c6bdac40fc2de4584a26ba5e1948f60a26
[ "0BSD" ]
null
null
null
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2018 David Shah <dave@ds0.me> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct Dff2dffsPass : public Pass { Dff2dffsPass() : Pass("dff2dffs", "process sync set/reset with SR over CE priority") { } void help() YS_OVERRIDE { log("\n"); log(" dff2dffs [options] [selection]\n"); log("\n"); log("Merge synchronous set/reset $_MUX_ cells to create $__DFFS_[NP][NP][01], to be run before\n"); log("dff2dffe for SR over CE priority.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing dff2dffs pass (merge synchronous set/reset into FF cells).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); pool<IdString> dff_types; dff_types.insert(ID($_DFF_N_)); dff_types.insert(ID($_DFF_P_)); for (auto module : design->selected_modules()) { log("Merging set/reset $_MUX_ cells into DFFs in %s.\n", log_id(module)); SigMap sigmap(module); dict<SigBit, Cell*> sr_muxes; vector<Cell*> ff_cells; for (auto cell : module->selected_cells()) { if (dff_types.count(cell->type)) { ff_cells.push_back(cell); continue; } if (cell->type != ID($_MUX_)) continue; SigBit bit_a = sigmap(cell->getPort(ID::A)); SigBit bit_b = sigmap(cell->getPort(ID::B)); if (bit_a.wire == nullptr || bit_b.wire == nullptr) sr_muxes[sigmap(cell->getPort(ID::Y))] = cell; } for (auto cell : ff_cells) { SigSpec sig_d = cell->getPort(ID(D)); if (GetSize(sig_d) < 1) continue; SigBit bit_d = sigmap(sig_d[0]); if (sr_muxes.count(bit_d) == 0) continue; Cell *mux_cell = sr_muxes.at(bit_d); SigBit bit_a = sigmap(mux_cell->getPort(ID::A)); SigBit bit_b = sigmap(mux_cell->getPort(ID::B)); SigBit bit_s = sigmap(mux_cell->getPort(ID(S))); log(" Merging %s (A=%s, B=%s, S=%s) into %s (%s).\n", log_id(mux_cell), log_signal(bit_a), log_signal(bit_b), log_signal(bit_s), log_id(cell), log_id(cell->type)); SigBit sr_val, sr_sig; bool invert_sr; sr_sig = bit_s; if (bit_a.wire == nullptr) { bit_d = bit_b; sr_val = bit_a; invert_sr = true; } else { log_assert(bit_b.wire == nullptr); bit_d = bit_a; sr_val = bit_b; invert_sr = false; } if (sr_val == State::S1) { if (cell->type == ID($_DFF_N_)) { if (invert_sr) cell->type = ID($__DFFS_NN1_); else cell->type = ID($__DFFS_NP1_); } else { log_assert(cell->type == ID($_DFF_P_)); if (invert_sr) cell->type = ID($__DFFS_PN1_); else cell->type = ID($__DFFS_PP1_); } } else { if (cell->type == ID($_DFF_N_)) { if (invert_sr) cell->type = ID($__DFFS_NN0_); else cell->type = ID($__DFFS_NP0_); } else { log_assert(cell->type == ID($_DFF_P_)); if (invert_sr) cell->type = ID($__DFFS_PN0_); else cell->type = ID($__DFFS_PP0_); } } cell->setPort(ID(R), sr_sig); cell->setPort(ID(D), bit_d); } } } } Dff2dffsPass; PRIVATE_NAMESPACE_END
29.055944
101
0.638267
[ "vector" ]
0ea0405c3ca98f297c1a2b29ab9a650822008eb3
4,266
cpp
C++
benchmarks/BunnymarkV2/cpp/BunnymarkV2.cpp
ColinKinloch/godot3-bunnymark
31b5ca7862018adfad68a095afbfe693ef9925ca
[ "MIT" ]
1
2019-11-27T01:35:26.000Z
2019-11-27T01:35:26.000Z
benchmarks/BunnymarkV2/cpp/BunnymarkV2.cpp
ColinKinloch/godot3-bunnymark
31b5ca7862018adfad68a095afbfe693ef9925ca
[ "MIT" ]
null
null
null
benchmarks/BunnymarkV2/cpp/BunnymarkV2.cpp
ColinKinloch/godot3-bunnymark
31b5ca7862018adfad68a095afbfe693ef9925ca
[ "MIT" ]
1
2022-01-24T11:08:25.000Z
2022-01-24T11:08:25.000Z
#include <stdlib.h> #include <vector> #include <string> #include <core/Godot.hpp> #include <core/GodotGlobal.hpp> #include <Node2D.hpp> #include <Texture.hpp> #include <Sprite.hpp> #include <Label.hpp> #include <ResourceLoader.hpp> #include <String.hpp> #include <Array.hpp> using namespace godot; class BunnymarkV2 : public GodotScript<Node2D> { GODOT_CLASS(BunnymarkV2); public: Vector2 screenSize; Ref<Texture> TBunny = ResourceLoader::load("res://images/godot_bunny.png"); float gravity = 500; std::vector<Vector2> speeds; Label* label = new Label(); Node2D* bunnies = new Node2D(); BunnymarkV2() { srand (time(NULL)); } void _ready() { owner->set_process(true); owner->add_child(bunnies); label->set_position(Vector2(0, 20)); owner->add_child(label); } void _process(const float delta) { screenSize = owner->get_viewport_rect().size; String bunnies_count = std::to_string(bunnies->get_child_count()).c_str(); String label_value = "Bunnies: " + bunnies_count; label->set_text(label_value); Array bunnyChildren = bunnies->get_children(); for (int i = 0; i < bunnyChildren.size(); i++) { Sprite* bunny = (Sprite*)(Object*)bunnyChildren[i]; Vector2 position = bunny->get_position(); Vector2 speed = speeds[i]; position.x += speed.x * delta; position.y += speed.y * delta; speed.y += gravity * delta; if (position.x > screenSize.x) { speed.x *= -1; position.x = screenSize.x; } if (position.x < 0) { speed.x *= -1; position.x = 0; } if (position.y > screenSize.y) { position.y = screenSize.y; if ((double)rand() / RAND_MAX > 0.5) { speed.y = (rand() % 1100 + 50); } else { speed.y *= -0.85f; } } if (position.y < 0) { speed.y = 0; position.y = 0; } bunny->set_position(position); speeds[i] = speed; } } void add_bunny() { Sprite* bunny = new Sprite(); bunny->set_texture(TBunny.ptr()); bunnies->add_child(bunny); bunny->set_position(Vector2(screenSize.x / 2.0, screenSize.y / 2.0)); speeds.push_back(Vector2(rand()%200+50, rand()%200+50)); } void remove_bunny() { int child_count = bunnies->get_child_count(); if (child_count == 0) { return; } Sprite* bunny = (Sprite*)bunnies->get_child(child_count - 1); speeds.pop_back(); bunnies->remove_child(bunny); } void finish() { Array array; array.push_back(bunnies->get_child_count()); owner->emit_signal("benchmark_finished", array); } static void _register_methods() { register_method((char *)"_ready", &BunnymarkV2::_ready); register_method((char *)"_process", &BunnymarkV2::_process); register_method((char *)"add_bunny", &BunnymarkV2::add_bunny); register_method((char *)"remove_bunny", &BunnymarkV2::remove_bunny); register_method((char *)"finish", &BunnymarkV2::finish); } };
34.967213
91
0.438115
[ "object", "vector" ]
0ea87a3eca515eaef364a92df05d3d673a1153e4
10,063
hpp
C++
atomics/PeopleInLocation.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
atomics/PeopleInLocation.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
atomics/PeopleInLocation.hpp
SimulationEverywhere/NEP_DAM
bc8cdf661c4a4e050abae12fb756f41ec6240e6b
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2017, Cristina Ruiz Martin * Carleton University, Universidad de Valladolid * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef CADMIUM_PEOPLE_IN_LOCATION_HPP #define CADMIUM_PEOPLE_IN_LOCATION_HPP #include <cadmium/modeling/ports.hpp> #include <cadmium/modeling/message_bag.hpp> #include <limits> #include <string> #include <iostream> #include <vector> #include <assert.h> #include "../data_structures/struct_types.hpp" #include "../data_structures/nep_model_enum_types.hpp" using namespace std; using namespace cadmium; using namespace nep_structures; using namespace nep_model_enum_types; //Port definition struct PeopleInLocation_defs{ //input ports struct in : public in_port<PeopleLocation> {}; //output ports struct out : public out_port<PeopleClassifiedByLocation> {}; }; //MODEL template<typename TIME> class PeopleInLocation { using defs=PeopleInLocation_defs; // putting definitions in context public: //default constructor PeopleInLocation() noexcept {} // state definition struct state_type{ vector <PeopleLocation> peopleLocation; vector <PeopleClassifiedByLocation> peopleClassifiedByLocation; vector <string> locationsUpdated; }; state_type state=state_type(); // ports definition using input_ports=std::tuple<typename defs::in>; using output_ports=std::tuple<typename defs::out>; // internal transition void internal_transition() { state.locationsUpdated.clear(); } // external transition void external_transition(TIME e, typename make_message_bags<input_ports>::type mbs) { bool old_location_updated; bool new_location_updated; bool person_found; bool location_in_the_list_to_send; for (const auto &x : get_messages<typename defs::in>(mbs)) { //cout << "external: " << "person id: " << x.peopleLocation.id << " location: " << x.peopleLocation.location << endl; old_location_updated = false; new_location_updated = false; person_found = false; location_in_the_list_to_send = false; //IF THE PERSON IS ALREADY REGISTERED for(int j = 0; j < state.peopleLocation.size(); j++){ if(x.id == state.peopleLocation[j].id){ person_found = true; //cout << "person_found" << endl; for (int z = 0; z < state.peopleClassifiedByLocation.size(); z++){ //FIND THE PREVIOUS LOCATION if(state.peopleLocation[j].location == state.peopleClassifiedByLocation[z].location){ //FIND THE PERSON AND DELETE IT FROM THAT LOCATION. OLD LOCATION UPDATED for(int k=0; k < state.peopleClassifiedByLocation[z].ids.size(); k++){ if(x.id == state.peopleClassifiedByLocation[z].ids[k]){ state.peopleClassifiedByLocation[z].ids.erase(state.peopleClassifiedByLocation[z].ids.begin()+k); old_location_updated = true; //IF THE LOCATION IS EMPTY DELETE FROM THE LIST. ELSE ADD TO THE LOCATIONS TO SEND IF IT IS NOT ALREADY if(state.peopleClassifiedByLocation[z].ids.empty()){ state.peopleClassifiedByLocation.erase(state.peopleClassifiedByLocation.begin()+z); }else{ location_in_the_list_to_send = false; for(int l = 0; l<state.locationsUpdated.size(); l++){ if(state.locationsUpdated[l] == state.peopleClassifiedByLocation[z].location){ location_in_the_list_to_send = true; break; } } if(location_in_the_list_to_send == false) state.locationsUpdated.push_back(state.peopleLocation[j].location); } break; } } } //FIND THE NEW LOCATION AND UPDATE IT if(x.location == state.peopleClassifiedByLocation[z].location){ //ADD THE PERSON TO THE NEW LOCATION state.peopleClassifiedByLocation[z].ids.push_back(x.id); new_location_updated = true; //UPDATE THE LOCATIONS TO SEND (THE ONES THAT HAVE CHANGED) location_in_the_list_to_send = false; for(int l = 0; l<state.locationsUpdated.size(); l++){ if(state.locationsUpdated[l] == state.peopleClassifiedByLocation[z].location){ location_in_the_list_to_send = true; break; } } if(location_in_the_list_to_send == false) state.locationsUpdated.push_back(x.location); } //IF OLD AND NEW LOCATION UPDATED. I HAVE FINISHED LOOKING FOR THEM if(old_location_updated && new_location_updated) break; } //UPDATE THE PERSON LOCATION state.peopleLocation[j] = x; //IF THE NEW LOCATION IS NOT REGISTERED ADD IT if(new_location_updated == false){ PeopleClassifiedByLocation aux_p; aux_p.location = x.location; aux_p.ids.push_back(x.id); state.peopleClassifiedByLocation.push_back(aux_p); new_location_updated = true; state.locationsUpdated.push_back(x.location); } //I HAVE FINISHED WITH THE MESSAGE break; } } //IF THE PERSON IS NOT REGISTERED if(person_found == false){ //cout << "entra en person_found == false" << endl; //REGISTED THE PERSON. THE OLD LOCATION IS UPDATED AS IT DID NOT EXISTS. state.peopleLocation.push_back(x); old_location_updated = true; //UPDATE THE NEW LOCATION AND TO THE LIST TO SEND IF NOT ALREADY for (int z = 0; z < state.peopleClassifiedByLocation.size(); z++){ if(x.location == state.peopleClassifiedByLocation[z].location){ state.peopleClassifiedByLocation[z].ids.push_back(x.id); new_location_updated = true; location_in_the_list_to_send = false; for(int l = 0; l<state.locationsUpdated.size(); l++){ if(state.locationsUpdated[l] == state.peopleClassifiedByLocation[z].location){ location_in_the_list_to_send = true; break; } } if(location_in_the_list_to_send == false) state.locationsUpdated.push_back(x.location); break; } } if(new_location_updated == false){ //cout << "entra en new_location_updated == false" << endl; PeopleClassifiedByLocation aux_p; aux_p.location = x.location; aux_p.ids.push_back(x.id); state.peopleClassifiedByLocation.push_back(aux_p); new_location_updated = true; state.locationsUpdated.push_back(x.location); //cout << state.locationsUpdated.size() << endl; } } if(old_location_updated ==false || new_location_updated == false) assert(false && "Error programing the function"); } } // confluence transition void confluence_transition(TIME e, typename make_message_bags<input_ports>::type mbs) { internal_transition(); external_transition(TIME(), std::move(mbs)); } // output function typename make_message_bags<output_ports>::type output() const { typename make_message_bags<output_ports>::type bags; for(int i = 0; i < state.locationsUpdated.size(); i++){ for(int j = 0; j < state.peopleClassifiedByLocation.size(); j++){ if(state.locationsUpdated[i] == state.peopleClassifiedByLocation[j].location){ get_messages<typename defs::out>(bags).emplace_back(state.peopleClassifiedByLocation[j]); break; } } } return bags; } // time_advance function TIME time_advance() const { return (state.locationsUpdated.empty() ? std::numeric_limits<TIME>::infinity() : TIME("00:00:00:001")); } // << operator for the state friend std::ostringstream& operator<<(std::ostringstream& os, const typename PeopleInLocation<TIME>::state_type& i) { os << "#locationsUpdated:" << i.locationsUpdated.size(); return os; } }; #endif //CADMIUM_PEOPLE_IN_LOCATION_HPP
46.804651
133
0.617311
[ "vector", "model" ]
0ea973543f3e3c97124ab7ab5f9fdcda0433b095
3,799
cpp
C++
DeviceCode/Targets/Native/STM32F2/DeviceCode/STM32F2_IntC/STM32F2_intc_functions.cpp
yangjunjiao/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
DeviceCode/Targets/Native/STM32F2/DeviceCode/STM32F2_IntC/STM32F2_intc_functions.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
DeviceCode/Targets/Native/STM32F2/DeviceCode/STM32F2_IntC/STM32F2_intc_functions.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:48:00.000Z
2021-05-04T12:37:55.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // 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 // // Copyright (c) Microsoft Corporation. All rights reserved. // Implementation for STM32F2: Copyright (c) Oberon microsystems, Inc. // // *** Interrupt Handling *** // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> #ifdef STM32F4XX #include "..\stm32f4xx.h" #else #include "..\stm32f2xx.h" #endif extern UINT32 ARM_Vectors[84]; // the interrupt vector table extern UINT32 FAULT_SubHandler; // the standard fault handler #ifdef FIQ_SAMPLING_PROFILER extern UINT32 FIQ_Handler; // the profiler NMI handler #endif void CPU_INTC_Initialize() { // disable all interrupts NVIC->ICER[0] = 0xFFFFFFFF; NVIC->ICER[1] = 0xFFFFFFFF; NVIC->ICER[2] = 0xFFFFFFFF; // clear pending bits NVIC->ICPR[0] = 0xFFFFFFFF; NVIC->ICPR[1] = 0xFFFFFFFF; NVIC->ICPR[2] = 0xFFFFFFFF; #ifdef FIQ_SAMPLING_PROFILER ARM_Vectors[2] = (UINT32)&FIQ_Handler; // NMI #else ARM_Vectors[2] = (UINT32)&FAULT_SubHandler; // NMI #endif ARM_Vectors[3] = (UINT32)&FAULT_SubHandler; // Hard Fault ARM_Vectors[4] = (UINT32)&FAULT_SubHandler; // MMU Fault ARM_Vectors[5] = (UINT32)&FAULT_SubHandler; // Bus Fault ARM_Vectors[6] = (UINT32)&FAULT_SubHandler; // Usage Fault ARM_Vectors[11] = (UINT32)&FAULT_SubHandler; // SVC ARM_Vectors[12] = (UINT32)&FAULT_SubHandler; // Debug ARM_Vectors[14] = (UINT32)&FAULT_SubHandler; // PendSV ARM_Vectors[15] = (UINT32)&FAULT_SubHandler; // Systick __DMB(); // ensure table is written SCB->AIRCR = (0x5FA << SCB_AIRCR_VECTKEY_Pos) // unlock key | (7 << SCB_AIRCR_PRIGROUP_Pos); // no priority group bits SCB->VTOR = (UINT32)ARM_Vectors; // vector table base SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk // enable faults | SCB_SHCSR_BUSFAULTENA_Msk | SCB_SHCSR_MEMFAULTENA_Msk; } BOOL CPU_INTC_ActivateInterrupt( UINT32 Irq_Index, HAL_CALLBACK_FPN ISR, void* ISR_Param ) { ARM_Vectors[Irq_Index + 16] = (UINT32)ISR; // exception = irq + 16 __DMB(); // asure table is written NVIC->ICPR[Irq_Index >> 5] = 1 << (Irq_Index & 0x1F); // clear pending bit NVIC->ISER[Irq_Index >> 5] = 1 << (Irq_Index & 0x1F); // set enable bit return TRUE; } BOOL CPU_INTC_DeactivateInterrupt( UINT32 Irq_Index ) { NVIC->ICER[Irq_Index >> 5] = 1 << (Irq_Index & 0x1F); // clear enable bit */ return TRUE; } BOOL CPU_INTC_InterruptEnable( UINT32 Irq_Index ) { UINT32 ier = NVIC->ISER[Irq_Index >> 5]; // old state NVIC->ISER[Irq_Index >> 5] = 1 << (Irq_Index & 0x1F); // set enable bit return (ier >> (Irq_Index & 0x1F)) & 1; // old enable bit } BOOL CPU_INTC_InterruptDisable( UINT32 Irq_Index ) { UINT32 ier = NVIC->ISER[Irq_Index >> 5]; // old state NVIC->ICER[Irq_Index >> 5] = 1 << (Irq_Index & 0x1F); // clear enable bit return (ier >> (Irq_Index & 0x1F)) & 1; // old enable bit } BOOL CPU_INTC_InterruptEnableState( UINT32 Irq_Index ) { // return enabled bit return (NVIC->ISER[Irq_Index >> 5] >> (Irq_Index & 0x1F)) & 1; } BOOL CPU_INTC_InterruptState( UINT32 Irq_Index ) { // return pending bit return (NVIC->ISPR[Irq_Index >> 5] >> (Irq_Index & 0x1F)) & 1; }
36.883495
200
0.591471
[ "vector" ]
0eac39e7d1397480427889901a6a808f713f844e
8,879
cpp
C++
core/script_language.cpp
includeLuka/godot
9010a25c0130cfa1fa407922cfb034c4f25b6bae
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/script_language.cpp
includeLuka/godot
9010a25c0130cfa1fa407922cfb034c4f25b6bae
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/script_language.cpp
includeLuka/godot
9010a25c0130cfa1fa407922cfb034c4f25b6bae
[ "CC-BY-3.0", "MIT" ]
null
null
null
/*************************************************************************/ /* script_language.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "script_language.h" ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES]; int ScriptServer::_language_count=0; bool ScriptServer::scripting_enabled=true; void Script::_notification( int p_what) { if (p_what==NOTIFICATION_POSTINITIALIZE) { if (ScriptDebugger::get_singleton()) ScriptDebugger::get_singleton()->set_break_language(get_language()); } } void Script::_bind_methods() { ObjectTypeDB::bind_method(_MD("can_instance"),&Script::can_instance); //ObjectTypeDB::bind_method(_MD("instance_create","base_object"),&Script::instance_create); ObjectTypeDB::bind_method(_MD("instance_has","base_object"),&Script::instance_has); ObjectTypeDB::bind_method(_MD("has_source_code"),&Script::has_source_code); ObjectTypeDB::bind_method(_MD("get_source_code"),&Script::get_source_code); ObjectTypeDB::bind_method(_MD("set_source_code","source"),&Script::set_source_code); ObjectTypeDB::bind_method(_MD("reload"),&Script::reload); } void ScriptServer::set_scripting_enabled(bool p_enabled) { scripting_enabled=p_enabled; } bool ScriptServer::is_scripting_enabled() { return scripting_enabled; } int ScriptServer::get_language_count() { return _language_count; } ScriptLanguage* ScriptServer::get_language(int p_idx) { ERR_FAIL_INDEX_V(p_idx,_language_count,NULL); return _languages[p_idx]; } void ScriptServer::register_language(ScriptLanguage *p_language) { ERR_FAIL_COND( _language_count >= MAX_LANGUAGES ); _languages[_language_count++]=p_language; } void ScriptServer::init_languages() { for(int i=0;i<_language_count;i++) { _languages[i]->init(); } } void ScriptInstance::get_property_state(List<Pair<StringName, Variant> > &state) { List<PropertyInfo> pinfo; get_property_list(&pinfo); for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { if (E->get().usage&PROPERTY_USAGE_STORAGE) { Pair<StringName,Variant> p; p.first=E->get().name; if (get(p.first,p.second)) state.push_back(p); } } } Variant ScriptInstance::call(const StringName& p_method,VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc=0; for(int i=0;i<VARIANT_ARG_MAX;i++) { if (argptr[i]->get_type()==Variant::NIL) break; argc++; } Variant::CallError error; return call(p_method,argptr,argc,error); } void ScriptInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { Variant::CallError ce; call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls } void ScriptInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { Variant::CallError ce; call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls } void ScriptInstance::call_multilevel(const StringName& p_method,VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc=0; for(int i=0;i<VARIANT_ARG_MAX;i++) { if (argptr[i]->get_type()==Variant::NIL) break; argc++; } Variant::CallError error; call_multilevel(p_method,argptr,argc); } ScriptInstance::~ScriptInstance() { } ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton=NULL; ScriptCodeCompletionCache::ScriptCodeCompletionCache() { singleton=this; } void ScriptLanguage::frame() { } ScriptDebugger * ScriptDebugger::singleton=NULL; void ScriptDebugger::set_lines_left(int p_left) { lines_left=p_left; } int ScriptDebugger::get_lines_left() const { return lines_left; } void ScriptDebugger::set_depth(int p_depth) { depth=p_depth; } int ScriptDebugger::get_depth() const { return depth; } void ScriptDebugger::insert_breakpoint(int p_line, const StringName& p_source) { if (!breakpoints.has(p_line)) breakpoints[p_line]=Set<StringName>(); breakpoints[p_line].insert(p_source); } void ScriptDebugger::remove_breakpoint(int p_line, const StringName& p_source) { if (!breakpoints.has(p_line)) return; breakpoints[p_line].erase(p_source); if (breakpoints[p_line].size()==0) breakpoints.erase(p_line); } bool ScriptDebugger::is_breakpoint(int p_line,const StringName& p_source) const { if (!breakpoints.has(p_line)) return false; return breakpoints[p_line].has(p_source); } bool ScriptDebugger::is_breakpoint_line(int p_line) const { return breakpoints.has(p_line); } String ScriptDebugger::breakpoint_find_source(const String& p_source) const { return p_source; } void ScriptDebugger::clear_breakpoints() { breakpoints.clear(); } void ScriptDebugger::idle_poll() { } void ScriptDebugger::line_poll() { } void ScriptDebugger::set_break_language(ScriptLanguage *p_lang) { break_lang=p_lang; } ScriptLanguage* ScriptDebugger::get_break_language() const{ return break_lang; } ScriptDebugger::ScriptDebugger() { singleton=this; lines_left=-1; depth=-1; break_lang=NULL; } bool PlaceHolderScriptInstance::set(const StringName& p_name, const Variant& p_value) { if (values.has(p_name)) { values[p_name]=p_value; return true; } return false; } bool PlaceHolderScriptInstance::get(const StringName& p_name, Variant &r_ret) const { if (values.has(p_name)) { r_ret=values[p_name]; return true; } return false; } void PlaceHolderScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { for(const List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) { p_properties->push_back(E->get()); } } Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const { if (values.has(p_name)) { if (r_is_valid) *r_is_valid=true; return values[p_name].get_type(); } if (r_is_valid) *r_is_valid=false; return Variant::NIL; } void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties,const Map<StringName,Variant>& p_values) { Set<StringName> new_values; for(const List<PropertyInfo>::Element *E=p_properties.front();E;E=E->next()) { StringName n = E->get().name; new_values.insert(n); if (!values.has(n) || values[n].get_type()!=E->get().type) { if (p_values.has(n)) values[n]=p_values[n]; } } properties=p_properties; List<StringName> to_remove; for(Map<StringName,Variant>::Element *E=values.front();E;E=E->next()) { if (!new_values.has(E->key())) to_remove.push_back(E->key()); } while(to_remove.size()) { values.erase(to_remove.front()->get()); to_remove.pop_front(); } if (owner && owner->get_script_instance()==this) { owner->_change_notify(); } //change notify } PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script,Object *p_owner) { language=p_language; script=p_script; owner=p_owner; } PlaceHolderScriptInstance::~PlaceHolderScriptInstance() { if (script.is_valid()) { script->_placeholder_erased(this); } }
25.296296
120
0.670458
[ "object" ]
0eacde00d6294c289d0ed37f6baa75389da4a40c
19,979
cpp
C++
Engine/Samples/LWForward+/Source/C++11/Camera.cpp
slicer4ever/Lightwaver
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
3
2017-10-24T08:04:49.000Z
2018-08-28T10:08:08.000Z
Engine/Samples/LWForward+/Source/C++11/Camera.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
Engine/Samples/LWForward+/Source/C++11/Camera.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
#include "Camera.h" #include "Model.h" #include "Renderer.h" #include <LWCore/LWMath.h> #include <iostream> #include <cstdarg> LWMatrix4f CameraPoint::MakeMatrix(void) const { float iRadi = 1.0f / m_Radius; return LWMatrix4f(iRadi, iRadi, iRadi, 1.0f); } CameraPoint &CameraPoint::BuildFrustrum(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { Result[0] = LWVector4f(Fwrd, m_Radius); Result[1] = LWVector4f(-Fwrd, m_Radius); Result[2] = LWVector4f(Right, m_Radius); Result[3] = LWVector4f(-Right, m_Radius); Result[4] = LWVector4f(-Up, m_Radius); Result[5] = LWVector4f(Up, m_Radius); return *this; } CameraPoint &CameraPoint::BuildFrustrumPoints(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { LWVector3f NC = -Fwrd * m_Radius; LWVector3f FC = Fwrd * m_Radius; Result[0] = LWVector4f(NC - Right * m_Radius - Up * m_Radius, -m_Radius); Result[1] = LWVector4f(NC + Right * m_Radius - Up * m_Radius, m_Radius); Result[2] = LWVector4f(NC + Right * m_Radius + Up * m_Radius, 0.0f); Result[3] = LWVector4f(FC - Right * m_Radius - Up * m_Radius, 0.0f); Result[4] = LWVector4f(FC + Right * m_Radius - Up * m_Radius, 0.0f); Result[5] = LWVector4f(FC + Right * m_Radius + Up * m_Radius, 0.0f); return *this; } CameraPoint::CameraPoint(float Radius) : m_Radius(Radius) {} LWMatrix4f CameraPerspective::MakeMatrix(void) const { return LWMatrix4f::Perspective(m_FOV, m_Aspect, m_Near, m_Far); } CameraPerspective &CameraPerspective::BuildFrustrum(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { float t = tanf(m_FOV*0.5f); float nh = m_Near * t; float nw = nh * m_Aspect; LWVector3f NC = Fwrd * m_Near; LWVector3f NT = (NC - (Up*nh)).Normalize(); LWVector3f NB = (NC + (Up*nh)).Normalize(); LWVector3f NR = (NC - (Right*nw)).Normalize(); LWVector3f NL = (NC + (Right*nw)).Normalize(); Result[0] = LWVector4f(Fwrd, m_Near); Result[1] = LWVector4f(-Fwrd, m_Far); Result[2] = LWVector4f(NR.Cross(Up), 0.0f); Result[3] = LWVector4f(-NL.Cross(Up), 0.0f); Result[4] = LWVector4f(-NT.Cross(Right), 0.0f); Result[5] = LWVector4f(NB.Cross(Right), 0.0f); return *this; } CameraPerspective &CameraPerspective::BuildFrustrumPoints(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { float t = tanf(m_FOV*0.5f); float nh = m_Near * t; float nw = nh * m_Aspect; float fh = m_Far * t; float fw = fh * m_Aspect; LWVector3f NC = Fwrd * m_Near; LWVector3f FC = Fwrd * m_Far; Result[0] = LWVector4f(NC - Right * nw + Up * nh, m_Near); Result[1] = LWVector4f(NC + Right * nw + Up * nh, m_Far); Result[2] = LWVector4f(NC - Right * nw - Up * nh, 0.0f); Result[3] = LWVector4f(FC - Right * fw + Up * fh, 0.0f); Result[4] = LWVector4f(FC + Right * fw + Up * fh, 0.0f); Result[5] = LWVector4f(FC - Right * fw - Up * fh, 0.0f); return *this; } CameraPerspective::CameraPerspective(float FOV, float Aspect, float Near, float Far) : m_FOV(FOV), m_Aspect(Aspect), m_Near(Near), m_Far(Far) {} LWMatrix4f CameraOrtho::MakeMatrix(void) const { return LWMatrix4f::Ortho(m_Left, m_Right, m_Bottom, m_Top, m_Near, m_Far); } CameraOrtho &CameraOrtho::BuildFrustrum(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { Result[0] = LWVector4f(Fwrd, m_Near); Result[1] = LWVector4f(-Fwrd, m_Far); Result[2] = LWVector4f(Right, -m_Left); Result[3] = LWVector4f(-Right, m_Right); Result[4] = LWVector4f(-Up, m_Top); Result[5] = LWVector4f(Up, -m_Bottom); return *this; } CameraOrtho &CameraOrtho::BuildFrustrumPoints(const LWVector3f &Fwrd, const LWVector3f &Up, const LWVector3f &Right, LWVector4f *Result) { LWVector3f NC = Fwrd * m_Near; LWVector3f FC = Fwrd * m_Far; Result[0] = LWVector4f(NC + Right * m_Left + Up * m_Bottom, m_Near); Result[1] = LWVector4f(NC + Right * m_Right + Up * m_Bottom, m_Far); Result[2] = LWVector4f(NC + Right * m_Right + Up * m_Top, 0.0f); Result[3] = LWVector4f(FC + Right * m_Left + Up * m_Bottom, 0.0f); Result[4] = LWVector4f(FC + Right * m_Right + Up * m_Bottom, 0.0f); Result[5] = LWVector4f(FC + Right * m_Right + Up * m_Top, 0.0f); return *this; } CameraOrtho::CameraOrtho(float Left, float Right, float Near, float Far, float Top, float Bottom) : m_Left(Left), m_Right(Right), m_Near(Near), m_Far(Far), m_Top(Top), m_Bottom(Bottom) {} uint32_t Camera::GetListForSphereInCameras(Camera **Cameras, uint32_t CameraCnt, const LWVector3f &Position, float Radius) { uint32_t ListBits = 0; for (uint32_t i = 0; i < CameraCnt; i++) { if (Cameras[i]->SphereInFrustrum(Position, Radius)) ListBits |= lFrame::GetIDBit(Cameras[i]->GetListID()); } return ListBits; } uint32_t Camera::GetListForSphereInCamerasf(uint32_t CameraCnt, const LWVector3f &Position, float Radius, ...) { Camera *CamList[64]; va_list lst; va_start(lst, Radius); for (uint32_t i = 0; i < CameraCnt; i++) CamList[i] = va_arg(lst, Camera*); va_end(lst); return GetListForSphereInCameras(CamList, CameraCnt, Position, Radius); } uint32_t Camera::GetListForConeInCameras(Camera **Cameras, uint32_t CameraCnt, const LWVector3f &Position, const LWVector3f &Direction, float Length, float Theta) { auto ConeInPlane = [](const LWVector4f &Plane, const LWVector3f &Pos, const LWVector3f &Dir, float Len, float Radius) { LWVector3f M = LWVector3f(Plane.x, Plane.y, Plane.z).Cross(Dir).Cross(Dir).Normalize(); LWVector3f Q = Pos + Dir * Len - M * Radius; float md = LWVector4f(Pos, 1.0f).Dot(Plane); float mq = LWVector4f(Q, 1.0f).Dot(Plane); return mq >= 0.0f || md >= 0.0f; }; uint32_t ListBits = 0; float Radi = tanf(Theta)*Length; for (uint32_t i = 0; i < CameraCnt; i++) { LWVector3f P = Position - Cameras[i]->GetPosition(); const LWVector4f *CF = Cameras[i]->GetViewFrustrum(); bool Inside = true; for (uint32_t n = 0; n < 6 && Inside; n++) Inside = ConeInPlane(CF[n], P, Direction, Length, Radi); if(!Inside) continue; ListBits |= lFrame::GetIDBit(Cameras[i]->GetListID()); } return ListBits; } uint32_t Camera::GetListForConeInCamerasf(uint32_t CameraCnt, const LWVector3f &Position, const LWVector3f &Direction, float Length, float Theta, ...) { Camera *CamList[64]; va_list lst; va_start(lst, Theta); for (uint32_t i = 0; i < CameraCnt; i++) CamList[i] = va_arg(lst, Camera*); va_end(lst); return GetListForConeInCameras(CamList, CameraCnt, Position, Direction, Length, Theta); } LWVector2f Camera::MakeSphereDirection(const LWVector3f &Direction) { return LWVector2f(atan2f(Direction.z, Direction.x), asinf(Direction.y)); } LWVector3f Camera::MakeDirection(const LWVector2f &SphereDir) { float c = cosf(SphereDir.y); return LWVector3f(cosf(SphereDir.x)*c, sinf(SphereDir.y), sinf(SphereDir.x)*c); } Camera &Camera::SetCameraControlled(bool Control) { m_CameraControlled = Control; return *this; } Camera &Camera::SetPosition(const LWVector3f &Position) { m_Position = Position; return *this; } Camera &Camera::SetDirection(const LWVector3f &Direction) { m_Direction = Direction; return *this; } Camera &Camera::SetUp(const LWVector3f &Up) { m_Up = Up; return *this; } Camera &Camera::SetAspect(float Aspect) { if (IsPointCamera()) return *this; if (IsOrthoCamera()) return *this; m_Perspective.m_Aspect = Aspect; return *this; } Camera &Camera::BuildCascadeCameraViews(const LWVector3f &LightDir, Camera *CamBuffer, uint32_t CascadeCnt, const LWVector3f &SceneAABBMin, const LWVector3f &SceneAABBMax, uint32_t ListOffset) { LWVector3f U = m_Up; if (fabs(U.Dot(LightDir)) >= 1.0f - std::numeric_limits<float>::epsilon()) U = LWVector3f(1.0f, 0.0f, 0.0f); LWVector3f R = LightDir.Cross(U).Normalize(); U = R.Cross(LightDir); LWVector4f F[6]; BuildFrustrumPoints(F); LWVector3f NTL = LWVector3f(F[0].x, F[0].y, F[0].z); LWVector3f NTR = LWVector3f(F[1].x, F[1].y, F[1].z); LWVector3f NBL = LWVector3f(F[2].x, F[2].y, F[2].z); LWVector3f FTL = LWVector3f(F[3].x, F[3].y, F[3].z); LWVector3f FTR = LWVector3f(F[4].x, F[4].y, F[4].z); LWVector3f FBL = LWVector3f(F[5].x, F[5].y, F[5].z); LWVector3f NX = NTR - NTL; LWVector3f NY = NBL - NTL; LWVector3f FX = FTR - FTL; LWVector3f FY = FBL - FTL; LWVector3f NBR = NTL + NX + NY; LWVector3f FBR = FTL + FX + FY; LWVector3f TL = FTL - NTL; LWVector3f TR = FTR - NTR; LWVector3f BL = FBL - NBL; LWVector3f BR = FBR - NBR; //Max of 4 cascades. CascadeCnt = std::min<uint32_t>(CascadeCnt, 4); float Far = m_Perspective.m_Far; float MinDistance = 200.0f; //Manually adjusted cascaded distances, depending on CasecadeCnt, and minimum distance float SDistances[5] = { 0.0f, MinDistance/Far, (MinDistance*3.0f)/Far, 0.5f, 1.0f }; SDistances[CascadeCnt] = 1.0f; LWVector3f AABBSize = SceneAABBMax - SceneAABBMin; LWVector3f AABBPnts[8] = { LWVector3f(SceneAABBMin), SceneAABBMin + LWVector3f(AABBSize.x, 0.0f, 0.0f), SceneAABBMin + LWVector3f(0.0f, 0.0f, AABBSize.z), SceneAABBMin + LWVector3f(AABBSize.x, 0.0f, AABBSize.z), SceneAABBMin + LWVector3f(0.0f, AABBSize.y, 0.0f), SceneAABBMin + LWVector3f(AABBSize.x, AABBSize.y, 0.0f), SceneAABBMin + LWVector3f(0.0f, AABBSize.y, AABBSize.z), SceneAABBMax }; LWMatrix4f ProjViewMatrix = GetProjViewMatrix(); for (uint32_t i = 0; i < 8; i++) AABBPnts[i] = AABBPnts[i] * ProjViewMatrix; for (uint32_t i = 0; i < CascadeCnt; i++) { float iL = SDistances[i]; float nL = SDistances[i+1]; LWVector3f P[8]; P[0] = NTL + iL * TL; P[1] = NTR + iL * TR; P[2] = NBL + iL * BL; P[3] = NBR + iL * BR; P[4] = NTL + nL * TL; P[5] = NTR + nL * TR; P[6] = NBL + nL * BL; P[7] = NBR + nL * BR; LWVector3f Min = LWVector3f(); LWVector3f Max = LWVector3f(); for (uint32_t n = 1; n < 8; n++) { //std::cout << n << ": " << P[n] << std::endl; LWVector3f C = P[n]-P[0]; LWVector3f Pnt = LWVector3f(R.Dot(C), U.Dot(C), LightDir.Dot(C)); Min = Min.Min(Pnt); Max = Max.Max(Pnt); } for (uint32_t i = 0; i < 8; i++) { float z = LightDir.Dot(AABBPnts[i]); Min.z = std::min<float>(z, Min.z); } P[0] += m_Position + LightDir * Min.z; CamBuffer[i] = Camera(P[0], LightDir, m_Up, ListOffset+i, Min.x, Max.x, Min.y, Max.y, 0.0f, Max.z - Min.z, true); CamBuffer[i].BuildFrustrum(); } return *this; } Camera &Camera::ProcessDirectionInputThird(const LWVector3f &Center, float Radius, const LWVector2f &MouseDis, float HorizontalSens, float VerticalSens, const LWVector4f &MinMaxXY, bool Controlling) { if (!Controlling || !m_CameraControlled) { m_PrevCameraControlled = false; return *this; } if (m_PrevCameraControlled) { LWVector2f CamDir = GetSphericalDirection(); CamDir.x += MouseDis.x*HorizontalSens; CamDir.y += MouseDis.y*VerticalSens; if (CamDir.x > LW_PI) CamDir.x -= LW_2PI; if (CamDir.x < -LW_PI) CamDir.x += LW_2PI; CamDir.x = std::min<float>(std::max<float>(CamDir.x, MinMaxXY.x), MinMaxXY.y); CamDir.y = std::min<float>(std::max<float>(CamDir.y, MinMaxXY.z), MinMaxXY.w); SetSphericalDirection(CamDir); m_Position = Center - GetDirection() * Radius; } m_PrevCameraControlled = true; return *this; } Camera &Camera::ProcessDirectionInputFirst(const LWVector2f &MouseDis, float HorizontalSens, float VerticalSens, const LWVector4f &MinMaxXY, bool Controlling) { if (!Controlling || !m_CameraControlled) { m_PrevCameraControlled = false; return *this; } if (m_PrevCameraControlled) { LWVector2f CamDir = GetSphericalDirection(); CamDir.x += MouseDis.x*HorizontalSens; CamDir.y += MouseDis.y*VerticalSens; if (CamDir.x > LW_PI) CamDir.x -= LW_2PI; if (CamDir.x < -LW_PI) CamDir.x += LW_2PI; CamDir.x = std::min<float>(std::max<float>(CamDir.x, MinMaxXY.x), MinMaxXY.y); CamDir.y = std::min<float>(std::max<float>(CamDir.y, MinMaxXY.z), MinMaxXY.w); SetSphericalDirection(CamDir); } m_PrevCameraControlled = true; return *this; } Camera &Camera::SetSphericalDirection(const LWVector2f &SphereCoordinates) { m_Direction = MakeDirection(SphereCoordinates); return *this; } Camera &Camera::ToggleCameraControl(void) { m_CameraControlled = !m_CameraControlled; return *this; } LWVector3f Camera::UnProject(const LWVector2f &ScreenPnt, float Depth, const LWVector2f &WndSize) const { LWVector4f Pnt = LWVector4f(ScreenPnt / WndSize * 2.0f - 1.0f, Depth*2.0f - 1.0f, 1.0f); Pnt = Pnt * (GetViewMatrix()*GetProjMatrix()).Inverse(); if (fabs(Pnt.w) <= std::numeric_limits<float>::epsilon()) return m_Position; Pnt.w = 1.0f / Pnt.w; return LWVector3f(Pnt.x, Pnt.y, Pnt.z) * Pnt.w; } LWVector3f Camera::Project(const LWVector3f &Pnt, const LWVector2f &WndSize) const { LWVector4f P = LWVector4f(Pnt, 1.0f); P = P * GetViewMatrix()*GetProjMatrix(); if (fabs(P.w) <= std::numeric_limits<float>::epsilon()) return LWVector3f(-1.0f); P.w = 1.0f / P.w; P *= P.w; return LWVector3f((P.x*0.5f + 0.5f)*WndSize.x, (P.y*0.5f + 0.5f)*WndSize.y, (1.0f+P.z)*0.5f); } Camera &Camera::SetOrtho(bool isOrtho) { m_Flag = (m_Flag&~OrthoSource) | (isOrtho ? OrthoSource : 0); return *this; } Camera &Camera::SetPointSource(bool isPointSource) { m_Flag = (m_Flag&~PointSource) | (isPointSource ? PointSource : 0); return *this; } Camera &Camera::SetShadowCaster(bool isShadowCaster) { m_Flag = (m_Flag&~ShadowCaster) | (isShadowCaster ? ShadowCaster : 0); return *this; } Camera &Camera::SetListID(uint32_t ListID) { m_ListID = ListID; return *this; } Camera &Camera::BuildFrustrum(void) { LWVector3f U = m_Up; if (fabs(m_Direction.Dot(U)) >= 1.0f - std::numeric_limits<float>::epsilon()) U = LWVector3f(1.0f, 0.0f, 0.0f); LWVector3f R = m_Direction.Cross(U).Normalize(); U = R.Cross(m_Direction); if (IsPointCamera()) m_Point.BuildFrustrum(m_Direction, U, R, m_ViewFrustrum); else if (IsOrthoCamera()) m_Ortho.BuildFrustrum(m_Direction, U, R, m_ViewFrustrum); else m_Perspective.BuildFrustrum(m_Direction, U, R, m_ViewFrustrum); return *this; } Camera &Camera::BuildFrustrumPoints(LWVector4f *Result) { LWVector3f U = m_Up; if (fabs(m_Direction.Dot(U)) >= 1.0f - std::numeric_limits<float>::epsilon()) U = LWVector3f(1.0f, 0.0f, 0.0f); LWVector3f R = m_Direction.Cross(U).Normalize(); U = R.Cross(m_Direction); if (IsPointCamera()) m_Point.BuildFrustrumPoints(m_Direction, U, R, Result); else if (IsOrthoCamera()) m_Ortho.BuildFrustrumPoints(m_Direction, U, R, Result); else m_Perspective.BuildFrustrumPoints(m_Direction, U, R, Result); return *this; } LWMatrix4f Camera::GetViewMatrix(void) const { LWVector3f U = m_Up; float D = fabs(U.Dot(m_Direction)); if (D >= 1.0f - std::numeric_limits<float>::epsilon()) U = LWVector3f(1.0f, 0.0f, 0.0f); return LWMatrix4f::LookAt(m_Position, m_Position + m_Direction, U).Inverse(); } LWMatrix4f Camera::GetDirectionMatrix(void) const { LWVector3f U = m_Up; float D = fabs(U.Dot(m_Direction)); if (D >= 1.0f - std::numeric_limits<float>::epsilon()) U = LWVector3f(1.0f, 0.0f, 0.0f); return LWMatrix4f::LookAt(m_Position, m_Position + m_Direction, U); } LWMatrix4f Camera::GetProjMatrix(void) const { if (IsPointCamera()) return m_Point.MakeMatrix(); if (IsOrthoCamera()) return m_Ortho.MakeMatrix(); return m_Perspective.MakeMatrix(); } LWMatrix4f Camera::GetProjViewMatrix(void) const { return GetViewMatrix()*GetProjMatrix(); } LWVector3f Camera::GetPosition(void) const { return m_Position; } LWVector3f Camera::GetDirection(void) const { return m_Direction; } LWVector3f Camera::GetFlatDirection(void) const { LWVector3f Dir = m_Direction; Dir.y = 0.0f; return Dir.Normalize(); } LWVector3f Camera::GetUp(void) const { return m_Up; } CameraOrtho &Camera::GetOrthoPropertys(void) { return m_Ortho; } CameraPerspective &Camera::GetPerspectivePropertys(void) { return m_Perspective; } CameraPoint &Camera::GetPointPropertys(void) { return m_Point; } LWVector2f Camera::GetSphericalDirection(void) const { return MakeSphereDirection(m_Direction); } const LWVector4f *Camera::GetViewFrustrum(void) const { return m_ViewFrustrum; } bool Camera::SphereInFrustrum(const LWVector3f &Position, float Radius) { LWVector4f P = LWVector4f(Position - m_Position, 1.0f); float d0 = m_ViewFrustrum[0].Dot(P); float d1 = m_ViewFrustrum[1].Dot(P); float d2 = m_ViewFrustrum[2].Dot(P); float d3 = m_ViewFrustrum[3].Dot(P); float d4 = m_ViewFrustrum[4].Dot(P); float d5 = m_ViewFrustrum[5].Dot(P); float m = std::min<float>(std::min<float>(std::min<float>(d0, d1), std::min<float>(d2, d3)), std::min<float>(d4, d5)); return m >= -Radius; } bool Camera::ConeInFrustrum(const LWVector3f &Position, const LWVector3f &Direction, float Length, float Theta) { auto ConeInPlane = [](const LWVector4f &Plane, const LWVector3f &Pos, const LWVector3f &Dir, float Len, float Radius) { LWVector3f M = LWVector3f(Plane.x, Plane.y, Plane.z).Cross(Dir).Cross(Dir).Normalize(); LWVector3f Q = Pos + Dir * Len - M * Radius; float md = LWVector4f(Pos, 1.0f).Dot(Plane); float mq = LWVector4f(Q, 1.0f).Dot(Plane); return mq >= 0.0f || md >= 0.0f; }; LWVector3f P = Position - m_Position; float Radi = tanf(Theta)*Length; for (uint32_t i = 0; i < 6; i++) { if (!ConeInPlane(m_ViewFrustrum[i], P, Direction, Length, Radi)) { return false; } } return true; } bool Camera::GetCameraControlled(void) const { return m_CameraControlled; } bool Camera::IsOrthoCamera(void) const { return (m_Flag&OrthoSource)!=0; } bool Camera::IsPointCamera(void) const { return (m_Flag&PointSource)!=0; } bool Camera::IsShadowCaster(void) const { return (m_Flag&ShadowCaster) != 0; } uint32_t Camera::GetListID(void) const { return m_ListID; } Camera::Camera(const LWVector3f &Position, const LWVector3f &ViewDirection, const LWVector3f &Up, uint32_t ListID, float Aspect, float Fov, float Near, float Far, bool ShadowCast) : m_Position(Position), m_Direction(ViewDirection), m_Up(Up), m_CameraControlled(false), m_PrevCameraControlled(false), m_ListID(ListID), m_Flag(ShadowCast?ShadowCaster:0) { m_Perspective = CameraPerspective(Fov, Aspect, Near, Far); BuildFrustrum(); } Camera::Camera(const LWVector3f &Position, const LWVector3f &ViewDirection, const LWVector3f &Up, uint32_t ListID, float Left, float Right, float Bottom, float Top, float Near, float Far, bool ShadowCast) : m_Position(Position), m_Direction(ViewDirection), m_Up(Up), m_CameraControlled(false), m_PrevCameraControlled(false), m_ListID(ListID), m_Flag((ShadowCast?ShadowCaster:0) | OrthoSource) { m_Ortho = CameraOrtho(Left, Right, Near, Far, Top, Bottom); BuildFrustrum(); } Camera::Camera(const LWVector3f &Position, float Radius, uint32_t ListID, bool ShadowCast) : m_Position(Position), m_Direction(LWVector3f(0.0f, 0.0f, 1.0f)), m_Up(LWVector3f(0.0f, 1.0f, 0.0f)), m_CameraControlled(false), m_PrevCameraControlled(false), m_ListID(ListID), m_Flag((ShadowCast?ShadowCaster:0)|PointSource) { m_Point = CameraPoint(Radius); BuildFrustrum(); } Camera::Camera(uint32_t ListID) : m_Position(LWVector3f()), m_Direction(LWVector3f(1.0f, 0.0f, 0.0f)), m_Up(LWVector3f(0.0f, 1.0f, 0.0f)), m_CameraControlled(false), m_PrevCameraControlled(false), m_ListID(ListID), m_Flag(0) { m_Perspective = CameraPerspective(LW_PI_4, 1.0f, 0.1f, 10000.0f); } Camera::Camera() : m_Position(LWVector3f(0.0f)), m_Direction(LWVector3f(1.0f, 0.0f, 0.0f)), m_Up(LWVector3f(0.0f, 1.0f, 0.0f)), m_CameraControlled(false), m_PrevCameraControlled(false), m_ListID(0), m_Flag(0) { m_Perspective = CameraPerspective(LW_PI_4, 1.0f, 0.1f, 10000.0f); }
37.839015
395
0.687021
[ "model" ]
0eaea3169b935de4fef0afbe8c558e7f1235b23c
54,035
cpp
C++
test/source/tests/executor_tests/manual_executor_tests.cpp
chausner/concurrencpp
cbfc4a16f11a2f540a4fa15d6b56dc16966ecfe6
[ "MIT" ]
898
2017-08-21T21:54:45.000Z
2022-03-29T07:39:27.000Z
test/source/tests/executor_tests/manual_executor_tests.cpp
chausner/concurrencpp
cbfc4a16f11a2f540a4fa15d6b56dc16966ecfe6
[ "MIT" ]
32
2019-05-26T03:01:13.000Z
2022-03-23T11:03:43.000Z
test/source/tests/executor_tests/manual_executor_tests.cpp
chausner/concurrencpp
cbfc4a16f11a2f540a4fa15d6b56dc16966ecfe6
[ "MIT" ]
94
2017-08-03T22:09:53.000Z
2022-03-31T09:31:00.000Z
#include "concurrencpp/concurrencpp.h" #include "infra/tester.h" #include "infra/assertions.h" #include "utils/object_observer.h" #include "utils/test_generators.h" #include "utils/executor_shutdowner.h" namespace concurrencpp::tests { void test_manual_executor_name(); void test_manual_executor_shutdown_method_access(); void test_manual_executor_shutdown_more_than_once(); void test_manual_executor_shutdown(); void test_manual_executor_max_concurrency_level(); void test_manual_executor_post_foreign(); void test_manual_executor_post_inline(); void test_manual_executor_post(); void test_manual_executor_submit_foreign(); void test_manual_executor_submit_inline(); void test_manual_executor_submit(); void test_manual_executor_bulk_post_foreign(); void test_manual_executor_bulk_post_inline(); void test_manual_executor_bulk_post(); void test_manual_executor_bulk_submit_foreign(); void test_manual_executor_bulk_submit_inline(); void test_manual_executor_bulk_submit(); void test_manual_executor_loop_once(); void test_manual_executor_loop_once_for(); void test_manual_executor_loop_once_until(); void test_manual_executor_loop(); void test_manual_executor_loop_for(); void test_manual_executor_loop_until(); void test_manual_executor_clear(); void test_manual_executor_wait_for_task(); void test_manual_executor_wait_for_task_for(); void test_manual_executor_wait_for_task_until(); void test_manual_executor_wait_for_tasks(); void test_manual_executor_wait_for_tasks_for(); void test_manual_executor_wait_for_tasks_until(); void assert_executed_locally(const std::unordered_map<size_t, size_t>& execution_map) { assert_equal(execution_map.size(), static_cast<size_t>(1)); // only one thread executed the tasks assert_equal(execution_map.begin()->first, concurrencpp::details::thread::get_current_virtual_id()); // and it's this thread. } } // namespace concurrencpp::tests using namespace std::chrono; void concurrencpp::tests::test_manual_executor_name() { auto executor = std::make_shared<concurrencpp::manual_executor>(); assert_equal(executor->name, concurrencpp::details::consts::k_manual_executor_name); } void concurrencpp::tests::test_manual_executor_shutdown_method_access() { auto executor = std::make_shared<manual_executor>(); assert_false(executor->shutdown_requested()); executor->shutdown(); assert_true(executor->shutdown_requested()); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->enqueue(concurrencpp::task {}); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { concurrencpp::task array[4]; std::span<concurrencpp::task> span = array; executor->enqueue(span); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->clear(); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop_once(); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop_once_for(milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop_once_until(high_resolution_clock::now() + milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop(100); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop_for(100, milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->loop_until(100, high_resolution_clock::now() + milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_task(); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_task_for(milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_task_until(high_resolution_clock::now() + milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_tasks(8); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_tasks_for(8, milliseconds(100)); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->wait_for_tasks_until(8, high_resolution_clock::now() + milliseconds(100)); }); } void concurrencpp::tests::test_manual_executor_shutdown_more_than_once() { auto executor = std::make_shared<manual_executor>(); for (size_t i = 0; i < 4; i++) { executor->shutdown(); } } void concurrencpp::tests::test_manual_executor_shutdown() { test_manual_executor_shutdown_method_access(); test_manual_executor_shutdown_more_than_once(); } void concurrencpp::tests::test_manual_executor_max_concurrency_level() { auto executor = std::make_shared<manual_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->max_concurrency_level(), concurrencpp::details::consts::k_manual_executor_max_concurrency_level); } void concurrencpp::tests::test_manual_executor_post_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<concurrencpp::manual_executor>(); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); for (size_t i = 0; i < task_count; i++) { executor->post(observer.get_testing_stub()); assert_equal(executor->size(), 1 + i); assert_false(executor->empty()); } // manual executor doesn't execute the tasks automatically, hence manual. assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(observer.get_execution_count(), i + 1); } executor->shutdown(); assert_equal(observer.get_destruction_count(), task_count); assert_executed_locally(observer.get_execution_map()); } void concurrencpp::tests::test_manual_executor_post_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); executor->post([executor, &observer] { for (size_t i = 0; i < task_count; i++) { executor->post(observer.get_testing_stub()); assert_equal(executor->size(), 1 + i); assert_false(executor->empty()); } }); // the tasks are not enqueued yet, only the spawning task is. assert_equal(executor->size(), static_cast<size_t>(1)); assert_false(executor->empty()); assert_true(executor->loop_once()); assert_equal(executor->size(), task_count); assert_false(executor->empty()); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_equal(observer.get_destruction_count(), task_count); assert_executed_locally(observer.get_execution_map()); } void concurrencpp::tests::test_manual_executor_post() { test_manual_executor_post_foreign(); test_manual_executor_post_inline(); } void concurrencpp::tests::test_manual_executor_submit_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(results[i].get(), i); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_executed_locally(observer.get_execution_map()); for (size_t i = task_count / 2; i < task_count; i++) { assert_throws<errors::broken_task>([&, i] { results[i].get(); }); } assert_equal(observer.get_destruction_count(), task_count); } void concurrencpp::tests::test_manual_executor_submit_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<concurrencpp::manual_executor>(); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); auto results_res = executor->submit([executor, &observer] { std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } return results; }); // the tasks are not enqueued yet, only the spawning task is. assert_equal(executor->size(), static_cast<size_t>(1)); assert_false(executor->empty()); assert_true(executor->loop_once()); assert_equal(executor->size(), task_count); assert_false(executor->empty()); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); assert_equal(results_res.status(), result_status::value); auto results = results_res.get(); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(results[i].get(), i); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_executed_locally(observer.get_execution_map()); for (size_t i = task_count / 2; i < task_count; i++) { assert_throws<errors::broken_task>([&, i] { results[i].get(); }); } assert_equal(observer.get_destruction_count(), task_count); } void concurrencpp::tests::test_manual_executor_submit() { test_manual_executor_submit_foreign(); test_manual_executor_submit_inline(); } void concurrencpp::tests::test_manual_executor_bulk_post_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); std::vector<testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub()); } executor->bulk_post<testing_stub>(stubs); assert_equal(executor->size(), task_count); assert_false(executor->empty()); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_equal(observer.get_destruction_count(), task_count); assert_executed_locally(observer.get_execution_map()); } void concurrencpp::tests::test_manual_executor_bulk_post_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); executor_shutdowner shutdown(executor); executor->post([executor, &observer]() mutable { std::vector<testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub()); } executor->bulk_post<testing_stub>(stubs); }); // the tasks are not enqueued yet, only the spawning task is. assert_equal(executor->size(), static_cast<size_t>(1)); assert_false(executor->empty()); assert_true(executor->loop_once()); assert_equal(executor->size(), task_count); assert_false(executor->empty()); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_equal(observer.get_destruction_count(), task_count); assert_executed_locally(observer.get_execution_map()); } void concurrencpp::tests::test_manual_executor_bulk_post() { test_manual_executor_bulk_post_foreign(); test_manual_executor_bulk_post_inline(); } void concurrencpp::tests::test_manual_executor_bulk_submit_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); executor_shutdowner shutdown(executor); std::vector<value_testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub(i)); } auto results = executor->bulk_submit<value_testing_stub>(stubs); assert_false(executor->empty()); assert_equal(executor->size(), task_count); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(results[i].get(), i); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_executed_locally(observer.get_execution_map()); for (size_t i = task_count / 2; i < task_count; i++) { assert_throws<errors::broken_task>([&, i] { results[i].get(); }); } assert_equal(observer.get_destruction_count(), task_count); } void concurrencpp::tests::test_manual_executor_bulk_submit_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<manual_executor>(); executor_shutdowner shutdown(executor); auto results_res = executor->submit([executor, &observer] { std::vector<value_testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub(i)); } return executor->bulk_submit<value_testing_stub>(stubs); }); // the tasks are not enqueued yet, only the spawning task is. assert_equal(executor->size(), static_cast<size_t>(1)); assert_false(executor->empty()); assert_true(executor->loop_once()); assert_equal(executor->size(), task_count); assert_false(executor->empty()); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); assert_equal(results_res.status(), result_status::value); auto results = results_res.get(); for (size_t i = 0; i < task_count / 2; i++) { assert_true(executor->loop_once()); assert_equal(results[i].get(), i); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); } executor->shutdown(); assert_executed_locally(observer.get_execution_map()); for (size_t i = task_count / 2; i < task_count; i++) { assert_throws<errors::broken_task>([&, i] { results[i].get(); }); } assert_equal(observer.get_destruction_count(), task_count); } void concurrencpp::tests::test_manual_executor_bulk_submit() { test_manual_executor_bulk_submit_foreign(); test_manual_executor_bulk_submit_inline(); } void concurrencpp::tests::test_manual_executor_loop_once() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); for (size_t i = 0; i < 10; i++) { assert_false(executor->loop_once()); } std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); for (size_t i = 0; i < task_count; i++) { assert_true(executor->loop_once()); assert_equal(results[i].get(), i); assert_equal(observer.get_execution_count(), i + 1); assert_equal(observer.get_destruction_count(), i + 1); assert_equal(executor->size(), task_count - (i + 1)); } assert_executed_locally(observer.get_execution_map()); for (size_t i = 0; i < 10; i++) { assert_false(executor->loop_once()); } } void concurrencpp::tests::test_manual_executor_loop_once_for() { // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(50); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto before = high_resolution_clock::now(); assert_false(executor->loop_once_for(waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before); assert_bigger_equal(ms_elapsed, waiting_time_ms); } } // case 2: tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(150); executor_shutdowner shutdown(executor); object_observer observer; executor->post(observer.get_testing_stub()); const auto before = high_resolution_clock::now(); assert_true(executor->loop_once_for(waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); assert_equal(observer.get_execution_count(), static_cast<size_t>(1)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(1)); assert_executed_locally(observer.get_execution_map()); } // case 3: goes to sleep, then woken by an incoming task { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); object_observer observer; const auto enqueue_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, enqueue_time, &observer]() mutable { std::this_thread::sleep_until(enqueue_time); executor->post(observer.get_testing_stub()); }); assert_true(executor->loop_once_for(seconds(10))); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, enqueue_time); assert_smaller_equal(now, enqueue_time + seconds(1)); thread.join(); assert_executed_locally(observer.get_execution_map()); } // case 4: goes to sleep, then woken by a shutdown interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->loop_once_for(seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_loop_once_until() { // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(50); const auto before = high_resolution_clock::now(); assert_false(executor->loop_once_until(max_waiting_time_point)); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, max_waiting_time_point); } } // case 2: tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); object_observer observer; const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(150); executor->post(observer.get_testing_stub()); const auto before = high_resolution_clock::now(); assert_true(executor->loop_once_until(max_waiting_time_point)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); assert_equal(observer.get_execution_count(), static_cast<size_t>(1)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(1)); assert_executed_locally(observer.get_execution_map()); } // case 3: goes to sleep, then woken by an incoming task { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); object_observer observer; const auto enqueue_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, enqueue_time, &observer]() mutable { std::this_thread::sleep_until(enqueue_time); executor->post(observer.get_testing_stub()); }); const auto max_looping_time_point = high_resolution_clock::now() + seconds(10); assert_true(executor->loop_once_until(max_looping_time_point)); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, enqueue_time); assert_smaller_equal(now, enqueue_time + seconds(1)); thread.join(); assert_executed_locally(observer.get_execution_map()); } // case 4: goes to sleep, then woken by a shutdown interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { const auto max_looping_time_point = high_resolution_clock::now() + seconds(10); executor->loop_once_until(max_looping_time_point); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_loop() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->size(), static_cast<size_t>(0)); assert_true(executor->empty()); assert_equal(executor->loop(100), static_cast<size_t>(0)); std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); const size_t chunk_size = 150; const auto cycles = task_count / chunk_size; const auto remained = task_count % (cycles * chunk_size); for (size_t i = 0; i < cycles; i++) { const auto executed = executor->loop(chunk_size); assert_equal(executed, chunk_size); const auto total_executed = (i + 1) * chunk_size; assert_equal(observer.get_execution_count(), total_executed); assert_equal(executor->size(), task_count - total_executed); } // execute the remaining tasks const auto executed = executor->loop(chunk_size); assert_equal(executed, remained); assert_equal(observer.get_execution_count(), task_count); assert_true(executor->empty()); assert_equal(executor->size(), static_cast<size_t>(0)); assert_equal(executor->loop(100), static_cast<size_t>(0)); assert_executed_locally(observer.get_execution_map()); for (size_t i = 0; i < task_count; i++) { assert_equal(results[i].get(), i); } assert_equal(observer.get_destruction_count(), task_count); } void concurrencpp::tests::test_manual_executor_loop_for() { // when max_count == 0, the function returns immediately { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto before = high_resolution_clock::now(); const auto executed = executor->loop_for(0, seconds(10)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = duration_cast<milliseconds>(after - before); assert_equal(executed, static_cast<size_t>(0)); assert_smaller_equal(ms_elapsed, milliseconds(5)); } // when max_waiting_time == 0ms, the function behaves like manual_executor::loop { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->loop_for(100, milliseconds(0)), static_cast<size_t>(0)); const size_t task_count = 100; for (size_t i = 0; i < task_count; i++) { executor->post(observer.get_testing_stub()); } for (size_t i = 0; i < (task_count - 2) / 2; i++) { const auto executed = executor->loop_for(2, milliseconds(0)); assert_equal(executed, 2); assert_equal(observer.get_execution_count(), (i + 1) * 2); assert_equal(observer.get_destruction_count(), (i + 1) * 2); } assert_equal(executor->loop_for(10, milliseconds(0)), 2); assert_equal(observer.get_execution_count(), 100); assert_equal(observer.get_destruction_count(), 100); assert_equal(executor->loop_for(10, milliseconds(0)), 0); assert_executed_locally(observer.get_execution_map()); } // if max_count is reached, the function returns { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto max_looping_time = seconds(10); const auto enqueueing_interval = milliseconds(100); const size_t max_count = 8; std::thread enqueuer([max_count, enqueueing_interval, executor, &observer] { for (size_t i = 0; i < max_count + 1; i++) { std::this_thread::sleep_for(enqueueing_interval); executor->post(observer.get_testing_stub()); } }); const auto before = high_resolution_clock::now(); const auto executed = executor->loop_for(max_count, max_looping_time); const auto after = high_resolution_clock::now(); const auto ms_elapsed = duration_cast<milliseconds>(after - before); assert_equal(executed, max_count); assert_bigger_equal(ms_elapsed, max_count * enqueueing_interval); assert_smaller(ms_elapsed, max_count * enqueueing_interval + seconds(1)); enqueuer.join(); } // if shutdown requested, the function returns and throws { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->loop_for(100, seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_loop_until() { // when max_count == 0, the function returns immediately { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto max_waiting_time_point = high_resolution_clock::now() + seconds(10); const auto before = high_resolution_clock::now(); const auto executed = executor->loop_until(0, max_waiting_time_point); const auto after = high_resolution_clock::now(); const auto ms_elapsed = duration_cast<milliseconds>(after - before); assert_equal(executed, static_cast<size_t>(0)); assert_smaller_equal(ms_elapsed, milliseconds(5)); } // when deadline <= now, the function returns 0 { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto now = high_resolution_clock::now(); std::this_thread::sleep_for(milliseconds(1)); assert_equal(executor->loop_until(100, now), static_cast<size_t>(0)); executor->post(observer.get_testing_stub()); assert_equal(executor->loop_until(100, now), static_cast<size_t>(0)); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); assert_equal(observer.get_destruction_count(), static_cast<size_t>(0)); } // if max_count is reached, the function returns { object_observer observer; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto max_looping_time_point = high_resolution_clock::now() + seconds(10); const auto enqueueing_interval = milliseconds(100); const size_t max_count = 8; std::thread enqueuer([max_count, enqueueing_interval, executor, &observer] { for (size_t i = 0; i < max_count + 1; i++) { std::this_thread::sleep_for(enqueueing_interval); executor->post(observer.get_testing_stub()); } }); const auto executed = executor->loop_until(max_count, max_looping_time_point); assert_equal(executed, max_count); assert_smaller(high_resolution_clock::now(), max_looping_time_point); enqueuer.join(); } // if shutdown requested, the function returns and throws { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->loop_until(100, high_resolution_clock::now() + seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_clear() { object_observer observer; const size_t task_count = 100; auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->clear(), static_cast<size_t>(0)); std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } assert_equal(executor->clear(), task_count); assert_true(executor->empty()); assert_equal(executor->size(), static_cast<size_t>(0)); assert_equal(observer.get_execution_count(), static_cast<size_t>(0)); for (auto& result : results) { assert_throws<concurrencpp::errors::broken_task>([&result]() mutable { result.get(); }); } assert_equal(observer.get_destruction_count(), task_count); assert_equal(executor->clear(), static_cast<size_t>(0)); } void concurrencpp::tests::test_manual_executor_wait_for_task() { // case 1: tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); executor->post([] { }); const auto before = high_resolution_clock::now(); executor->wait_for_task(); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 2: goes to sleep, woken by a task { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); auto enqueuing_time = high_resolution_clock::now() + milliseconds(150); std::thread enqueuing_thread([executor, enqueuing_time]() mutable { std::this_thread::sleep_until(enqueuing_time); executor->post([] { }); }); assert_equal(executor->size(), static_cast<size_t>(0)); executor->wait_for_task(); const auto now = high_resolution_clock::now(); assert_equal(executor->size(), static_cast<size_t>(1)); assert_bigger_equal(high_resolution_clock::now(), enqueuing_time); enqueuing_thread.join(); } // case 3: goes to sleep, wakes up by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_task(); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_wait_for_task_for() { // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(50); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto before = high_resolution_clock::now(); assert_false(executor->wait_for_task_for(waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before); assert_equal(executor->size(), 0); assert_bigger_equal(ms_elapsed, waiting_time_ms); } } // case 2: tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(150); executor_shutdowner shutdown(executor); executor->post([] { }); const auto before = high_resolution_clock::now(); assert_true(executor->wait_for_task_for(waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 3: goes to sleep, then woken by an incoming task { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto enqueuing_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, enqueuing_time]() mutable { std::this_thread::sleep_until(enqueuing_time); executor->post([] { }); }); assert_true(executor->wait_for_task_for(seconds(10))); const auto now = high_resolution_clock::now(); assert_equal(executor->size(), static_cast<size_t>(1)); assert_bigger_equal(now, enqueuing_time); assert_smaller_equal(now, enqueuing_time + seconds(1)); thread.join(); } // case 4: goes to sleep, then woken by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_task_for(seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_wait_for_task_until() { // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(50); assert_false(executor->wait_for_task_until(max_waiting_time_point)); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, max_waiting_time_point); } } // case 2: tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(150); executor->post([] { }); const auto before = high_resolution_clock::now(); assert_true(executor->wait_for_task_until(max_waiting_time_point)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 3: goes to sleep, then woken by an incoming task { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto enqueue_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, enqueue_time]() mutable { std::this_thread::sleep_until(enqueue_time); executor->post([] { }); }); assert_true(executor->wait_for_task_until(high_resolution_clock::now() + seconds(10))); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, enqueue_time); assert_smaller_equal(now, enqueue_time + seconds(1)); thread.join(); } // case 4: goes to sleep, then woken by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_task_until(high_resolution_clock::now() + seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_wait_for_tasks() { constexpr size_t task_count = 4; // case 0: max_count == 0, the function returns immediately { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto before = high_resolution_clock::now(); executor->wait_for_tasks(0); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 1: max_count tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); for (size_t i = 0; i < task_count; i++) { executor->post([] { }); } const auto before = high_resolution_clock::now(); executor->wait_for_tasks(4); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 2: goes to sleep, woken by incoming tasks { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto enqueuing_interval = milliseconds(100); const auto before = high_resolution_clock::now(); std::thread enqueuing_thread([executor, enqueuing_interval]() mutable { for (size_t i = 0; i < task_count; i++) { std::this_thread::sleep_for(enqueuing_interval); executor->post([] { }); } }); executor->wait_for_tasks(task_count); const auto now = high_resolution_clock::now(); assert_equal(executor->size(), task_count); assert_bigger_equal(now, before + enqueuing_interval * task_count); assert_smaller_equal(now, before + enqueuing_interval * task_count + seconds(1)); enqueuing_thread.join(); } // case 3: goes to sleep, wakes up by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_tasks(task_count); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_wait_for_tasks_for() { constexpr size_t task_count = 4; // case 0: max_count == 0, the function returns immediately { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto before = high_resolution_clock::now(); executor->wait_for_tasks_for(0, seconds(4)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(50); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto before = high_resolution_clock::now(); assert_false(executor->wait_for_tasks_for(task_count, waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before); assert_equal(executor->size(), 0); assert_bigger_equal(ms_elapsed, waiting_time_ms); } } // case 2: max_count tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); const auto waiting_time_ms = milliseconds(150); executor_shutdowner shutdown(executor); for (size_t i = 0; i < task_count; i++) { executor->post([] { }); } const auto before = high_resolution_clock::now(); assert_true(executor->wait_for_tasks_for(task_count, waiting_time_ms)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 3: goes to sleep, then woken by incoming tasks { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto enqueuing_interval = milliseconds(100); const auto before = high_resolution_clock::now(); std::thread enqueuing_thread([executor, enqueuing_interval]() mutable { for (size_t i = 0; i < task_count; i++) { std::this_thread::sleep_for(enqueuing_interval); executor->post([] { }); } }); executor->wait_for_tasks_for(task_count, std::chrono::seconds(10)); const auto now = high_resolution_clock::now(); assert_equal(executor->size(), task_count); assert_bigger_equal(now, before + enqueuing_interval * task_count); assert_smaller_equal(now, before + enqueuing_interval * task_count + seconds(1)); enqueuing_thread.join(); } // case 4: goes to sleep, then woken by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_tasks_for(task_count, seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } void concurrencpp::tests::test_manual_executor_wait_for_tasks_until() { constexpr size_t task_count = 4; // case 0: max_count == 0, the function returns immediately { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto before = high_resolution_clock::now(); executor->wait_for_tasks_until(0, high_resolution_clock::now() + seconds(4)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 1: timeout { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); for (size_t i = 0; i < 10; i++) { const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(50); assert_false(executor->wait_for_tasks_until(task_count, max_waiting_time_point)); const auto after = high_resolution_clock::now(); assert_equal(executor->size(), 0); assert_bigger_equal(after, max_waiting_time_point); } } // case 2: max_count tasks already exist { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto max_waiting_time_point = high_resolution_clock::now() + milliseconds(150); for (size_t i = 0; i < task_count; i++) { executor->post([] { }); } const auto before = high_resolution_clock::now(); assert_true(executor->wait_for_tasks_until(task_count, max_waiting_time_point)); const auto after = high_resolution_clock::now(); const auto ms_elapsed = std::chrono::duration_cast<milliseconds>(after - before).count(); assert_smaller_equal(ms_elapsed, 5); } // case 3: goes to sleep, then woken by incoming tasks { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto enqueuing_interval = milliseconds(150); const auto before = high_resolution_clock::now(); std::thread enqueuing_thread([executor, enqueuing_interval]() mutable { for (size_t i = 0; i < task_count; i++) { std::this_thread::sleep_for(enqueuing_interval); executor->post([] { }); } }); executor->wait_for_tasks_until(task_count, high_resolution_clock::now() + std::chrono::seconds(10)); const auto now = high_resolution_clock::now(); assert_equal(executor->size(), task_count); assert_bigger_equal(now, before + enqueuing_interval * task_count); assert_smaller_equal(now, before + enqueuing_interval * task_count + seconds(2)); enqueuing_thread.join(); } // case 4: goes to sleep, then woken by an interrupt { auto executor = std::make_shared<concurrencpp::manual_executor>(); executor_shutdowner shutdown(executor); const auto shutdown_time = high_resolution_clock::now() + milliseconds(150); std::thread thread([executor, shutdown_time]() mutable { std::this_thread::sleep_until(shutdown_time); executor->shutdown(); }); assert_throws<errors::runtime_shutdown>([executor] { executor->wait_for_tasks_until(task_count, high_resolution_clock::now() + seconds(10)); }); const auto now = high_resolution_clock::now(); assert_bigger_equal(now, shutdown_time); assert_smaller_equal(now, shutdown_time + seconds(1)); thread.join(); } } using namespace concurrencpp::tests; int main() { tester tester("manual_executor test"); tester.add_step("name", test_manual_executor_name); tester.add_step("shutdown", test_manual_executor_shutdown); tester.add_step("max_concurrency_level", test_manual_executor_max_concurrency_level); tester.add_step("post", test_manual_executor_post); tester.add_step("submit", test_manual_executor_submit); tester.add_step("bulk_post", test_manual_executor_bulk_post); tester.add_step("bulk_submit", test_manual_executor_bulk_submit); tester.add_step("loop_once", test_manual_executor_loop_once); tester.add_step("loop_once_for", test_manual_executor_loop_once_for); tester.add_step("loop_once_until", test_manual_executor_loop_once_until); tester.add_step("loop", test_manual_executor_loop); tester.add_step("loop_for", test_manual_executor_loop_for); tester.add_step("loop_until", test_manual_executor_loop_until); tester.add_step("wait_for_task", test_manual_executor_wait_for_task); tester.add_step("wait_for_task_for", test_manual_executor_wait_for_task_for); tester.add_step("wait_for_task_until", test_manual_executor_wait_for_task_until); tester.add_step("wait_for_tasks", test_manual_executor_wait_for_tasks); tester.add_step("wait_for_tasks_for", test_manual_executor_wait_for_tasks_for); tester.add_step("wait_for_tasks_until", test_manual_executor_wait_for_tasks_until); tester.add_step("clear", test_manual_executor_clear); tester.launch_test(); return 0; }
36.411725
134
0.670417
[ "vector" ]
0eb152aea3a5d2bfde3ff24f0d1fc75aebae7e36
5,460
cc
C++
source/use_case/asr/src/Wav2LetterMfcc.cc
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
source/use_case/asr/src/Wav2LetterMfcc.cc
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
source/use_case/asr/src/Wav2LetterMfcc.cc
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Arm Limited. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Wav2LetterMfcc.hpp" #include "PlatformMath.hpp" #include <cfloat> namespace arm { namespace app { namespace audio { bool Wav2LetterMFCC::ApplyMelFilterBank( std::vector<float>& fftVec, std::vector<std::vector<float>>& melFilterBank, std::vector<uint32_t>& filterBankFilterFirst, std::vector<uint32_t>& filterBankFilterLast, std::vector<float>& melEnergies) { const size_t numBanks = melEnergies.size(); if (numBanks != filterBankFilterFirst.size() || numBanks != filterBankFilterLast.size()) { printf_err("Unexpected filter bank lengths\n"); return false; } for (size_t bin = 0; bin < numBanks; ++bin) { auto filterBankIter = melFilterBank[bin].begin(); auto end = melFilterBank[bin].end(); /* Avoid log of zero at later stages, same value used in librosa. * The number was used during our default wav2letter model training. */ float melEnergy = 1e-10; const uint32_t firstIndex = filterBankFilterFirst[bin]; const uint32_t lastIndex = std::min<uint32_t>(filterBankFilterLast[bin], fftVec.size() - 1); for (uint32_t i = firstIndex; i <= lastIndex && filterBankIter != end; ++i) { melEnergy += (*filterBankIter++ * fftVec[i]); } melEnergies[bin] = melEnergy; } return true; } void Wav2LetterMFCC::ConvertToLogarithmicScale( std::vector<float>& melEnergies) { float maxMelEnergy = -FLT_MAX; /* Container for natural logarithms of mel energies. */ std::vector <float> vecLogEnergies(melEnergies.size(), 0.f); /* Because we are taking natural logs, we need to multiply by log10(e). * Also, for wav2letter model, we scale our log10 values by 10. */ constexpr float multiplier = 10.0 * /* Default scalar. */ 0.4342944819032518; /* log10f(std::exp(1.0)) */ /* Take log of the whole vector. */ math::MathUtils::VecLogarithmF32(melEnergies, vecLogEnergies); /* Scale the log values and get the max. */ for (auto iterM = melEnergies.begin(), iterL = vecLogEnergies.begin(); iterM != melEnergies.end() && iterL != vecLogEnergies.end(); ++iterM, ++iterL) { *iterM = *iterL * multiplier; /* Save the max mel energy. */ if (*iterM > maxMelEnergy) { maxMelEnergy = *iterM; } } /* Clamp the mel energies. */ constexpr float maxDb = 80.0; const float clampLevelLowdB = maxMelEnergy - maxDb; for (float& melEnergy : melEnergies) { melEnergy = std::max(melEnergy, clampLevelLowdB); } } std::vector<float> Wav2LetterMFCC::CreateDCTMatrix( const int32_t inputLength, const int32_t coefficientCount) { std::vector<float> dctMatix(inputLength * coefficientCount); /* Orthonormal normalization. */ const float normalizerK0 = 2 * math::MathUtils::SqrtF32(1.0f / static_cast<float>(4*inputLength)); const float normalizer = 2 * math::MathUtils::SqrtF32(1.0f / static_cast<float>(2*inputLength)); const float angleIncr = M_PI / inputLength; float angle = angleIncr; /* We start using it at k = 1 loop. */ /* First row of DCT will use normalizer K0. */ for (int32_t n = 0; n < inputLength; ++n) { dctMatix[n] = normalizerK0 /* cos(0) = 1 */; } /* Second row (index = 1) onwards, we use standard normalizer. */ for (int32_t k = 1, m = inputLength; k < coefficientCount; ++k, m += inputLength) { for (int32_t n = 0; n < inputLength; ++n) { dctMatix[m+n] = normalizer * math::MathUtils::CosineF32((n + 0.5f) * angle); } angle += angleIncr; } return dctMatix; } float Wav2LetterMFCC::GetMelFilterBankNormaliser( const float& leftMel, const float& rightMel, const bool useHTKMethod) { /* Slaney normalization for mel weights. */ return (2.0f / (MFCC::InverseMelScale(rightMel, useHTKMethod) - MFCC::InverseMelScale(leftMel, useHTKMethod))); } } /* namespace audio */ } /* namespace app */ } /* namespace arm */
38.723404
104
0.564652
[ "vector", "model" ]
0eb40e88bd0ee7fc3e391dc62d2eaf0099d8d4c0
12,064
cpp
C++
app/src/main/cpp/basicSFMLmain.cpp
Is-Daouda/is-Engine-Pong
a806fed49c6dfbaea7b3910f94c5c78e76da05b5
[ "Zlib" ]
1
2020-12-07T17:44:10.000Z
2020-12-07T17:44:10.000Z
app/src/main/cpp/basicSFMLmain.cpp
Is-Daouda/is-Engine-Pong
a806fed49c6dfbaea7b3910f94c5c78e76da05b5
[ "Zlib" ]
null
null
null
app/src/main/cpp/basicSFMLmain.cpp
Is-Daouda/is-Engine-Pong
a806fed49c6dfbaea7b3910f94c5c78e76da05b5
[ "Zlib" ]
null
null
null
#include "isEngine/core/GameEngine.h" namespace is { bool GameEngine::basicSFMLmain() { //////////////////////////////////////////////////////////// // WINDOW CREATION //////////////////////////////////////////////////////////// #if defined(__ANDROID__) m_window.create(sf::VideoMode::getDesktopMode(), ""); #if defined(IS_ENGINE_USE_ADMOB) JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jobject activity = (jobject)SDL_AndroidGetActivity(); jclass clazz(env->GetObjectClass(activity)); JavaVM* vm; env->GetJavaVM(&vm); m_gameSysExt.m_admobManager = std::make_shared<AdmobManager>(m_window, activity, env); m_gameSysExt.m_admobManager->checkAdObjInit(); #endif // definded #else m_window.create(sf::VideoMode(is::GameConfig::WINDOW_WIDTH, is::GameConfig::WINDOW_HEIGHT), is::GameConfig::GAME_NAME, is::getWindowStyle()); // load application icon sf::Image iconTex; if (!iconTex.loadFromFile(is::GameConfig::GUI_DIR + "icon.png")) return false; m_window.setIcon(32, 32, iconTex.getPixelsPtr()); #endif // defined setFPS(m_window, is::GameConfig::FPS); // set frames per second (FPS) sf::View m_view(sf::Vector2f(is::GameConfig::VIEW_WIDTH / 2.f, is::GameConfig::VIEW_HEIGHT / 2.f), sf::Vector2f(is::GameConfig::VIEW_WIDTH, is::GameConfig::VIEW_HEIGHT)); m_window.setView(m_view); //////////////////////////////////////////////////////////// // INITIALIZATION //////////////////////////////////////////////////////////// // Define some constants const float pi = 3.14159f; sf::Vector2f paddleSize(25, 100); float ballRadius = 10.f; // Load the sounds used in the game sf::SoundBuffer ballSoundBuffer; is::loadSFMLSoundBuffer(ballSoundBuffer, is::GameConfig::SFX_DIR + "ball.wav"); sf::Sound ballSound(ballSoundBuffer); // Create the left paddle sf::RectangleShape leftPaddle; leftPaddle.setSize(paddleSize - sf::Vector2f(3, 3)); leftPaddle.setFillColor(sf::Color(100, 100, 200)); leftPaddle.setOrigin(paddleSize / 2.f); // Create the right paddle sf::RectangleShape rightPaddle; rightPaddle.setSize(paddleSize - sf::Vector2f(3, 3)); rightPaddle.setFillColor(sf::Color(200, 100, 100)); rightPaddle.setOrigin(paddleSize / 2.f); // Create the ball sf::CircleShape ball; ball.setRadius(ballRadius - 3); ball.setFillColor(sf::Color::White); ball.setOrigin(ballRadius / 2, ballRadius / 2); // Load the text font sf::Font font; is::loadSFMLFont(font, is::GameConfig::FONT_DIR + "sansation.ttf", 40); // Initialize the pause message sf::Text pauseMessage; is::createText(font, pauseMessage, "", 170.f, 150.f, sf::Color::White, 40); #ifdef __ANDROID__ pauseMessage.setString("Welcome to SFML pong!\nTouch the screen to start the game"); #else pauseMessage.setString("Welcome to SFML pong!\nPress space to start the game"); #endif // Define the paddles properties sf::Clock AITimer; const sf::Time AITime = sf::seconds(0.1f); const float paddleSpeed = 400.f; float rightPaddleSpeed = 0.f; const float ballSpeed = 400.f; float ballAngle = 0.f; // to be changed later sf::Clock clock; bool isPlaying = false; //////////////////////////////////////////////////////////// // RENDER LOOP // //////////////////////////////////////////////////////////// // This starts the render loop. // // Don't touch unless you know what you're doing. // #if !defined(IS_ENGINE_HTML_5) // while (m_window.isOpen()) // #else // EM_ASM(console.log("Start successfully!");, 0); // execMainLoop([&] // { // if (emscripten_run_script_int("Module.syncdone") == 1)// #endif // { // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // EVENT //////////////////////////////////////////////////////////// sf::Event event; while (m_window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: m_window.close(); break; default: break; } } //////////////////////////////////////////////////////////// // UPDATE OBJECTS //////////////////////////////////////////////////////////// // Window closed or escape key pressed: exit if (m_gameSysExt.keyIsPressed(sf::Keyboard::Escape)) is::closeApplication(); // Space key pressed: play if (m_gameSysExt.keyIsPressed(sf::Keyboard::Space) || m_gameSysExt.isPressed(is::GameSystem::MOUSE)) { if (!isPlaying) { // (re)start the game isPlaying = true; clock.restart(); // Reset the position of the paddles and ball leftPaddle.setPosition(10 + paddleSize.x / 2, is::GameConfig::WINDOW_HEIGHT / 2); rightPaddle.setPosition(is::GameConfig::WINDOW_WIDTH - 10 - paddleSize.x / 2, is::GameConfig::WINDOW_HEIGHT / 2); ball.setPosition(is::GameConfig::WINDOW_WIDTH / 2, is::GameConfig::WINDOW_HEIGHT / 2); // Reset the ball angle do { // Make sure the ball initial angle is not too much vertical ballAngle = (std::rand() % 360) * 2 * pi / 360; } while (std::abs(std::cos(ballAngle)) < 0.7f); } } if (isPlaying) { float deltaTime = clock.restart().asSeconds(); // Move the player's paddle if (m_gameSysExt.keyIsPressed(sf::Keyboard::Up) && (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) { leftPaddle.move(0.f, -paddleSpeed * deltaTime); } if (m_gameSysExt.keyIsPressed(sf::Keyboard::Down) && (leftPaddle.getPosition().y + paddleSize.y / 2 < is::GameConfig::WINDOW_HEIGHT - 5.f)) { leftPaddle.move(0.f, paddleSpeed * deltaTime); } if (m_gameSysExt.isPressed(is::GameSystem::MOUSE)) { sf::Vector2f pos = is::getCursor(m_window); leftPaddle.setPosition(leftPaddle.getPosition().x, pos.y); } // Move the computer's paddle if (((rightPaddleSpeed < 0.f) && (rightPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) || ((rightPaddleSpeed > 0.f) && (rightPaddle.getPosition().y + paddleSize.y / 2 < is::GameConfig::WINDOW_HEIGHT - 5.f))) { rightPaddle.move(0.f, rightPaddleSpeed * deltaTime); } // Update the computer's paddle direction according to the ball position if (AITimer.getElapsedTime() > AITime) { AITimer.restart(); if (ball.getPosition().y + ballRadius > rightPaddle.getPosition().y + paddleSize.y / 2) rightPaddleSpeed = paddleSpeed; else if (ball.getPosition().y - ballRadius < rightPaddle.getPosition().y - paddleSize.y / 2) rightPaddleSpeed = -paddleSpeed; else rightPaddleSpeed = 0.f; } // Move the ball float factor = ballSpeed * deltaTime; ball.move(std::cos(ballAngle) * factor, std::sin(ballAngle) * factor); #ifdef __ANDROID__ const std::string inputString = "Touch the screen to restart"; #else const std::string inputString = "Press space to restart or\nescape to exit"; #endif // Check collisions between the ball and the screen if (ball.getPosition().x - ballRadius < 0.f) { isPlaying = false; pauseMessage.setString("You Lost!\n" + inputString); } if (ball.getPosition().x + ballRadius > is::GameConfig::WINDOW_WIDTH) { isPlaying = false; pauseMessage.setString("You Won!\n" + inputString); } if (ball.getPosition().y - ballRadius < 0.f) { ballSound.play(); ballAngle = -ballAngle; ball.setPosition(ball.getPosition().x, ballRadius + 0.1f); } if (ball.getPosition().y + ballRadius > is::GameConfig::WINDOW_HEIGHT) { ballSound.play(); ballAngle = -ballAngle; ball.setPosition(ball.getPosition().x, is::GameConfig::WINDOW_HEIGHT - ballRadius - 0.1f); } // Check the collisions between the ball and the paddles // Left Paddle if (ball.getPosition().x - ballRadius < leftPaddle.getPosition().x + paddleSize.x / 2 && ball.getPosition().x - ballRadius > leftPaddle.getPosition().x && ball.getPosition().y + ballRadius >= leftPaddle.getPosition().y - paddleSize.y / 2 && ball.getPosition().y - ballRadius <= leftPaddle.getPosition().y + paddleSize.y / 2) { if (ball.getPosition().y > leftPaddle.getPosition().y) ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180; else ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180; ballSound.play(); ball.setPosition(leftPaddle.getPosition().x + ballRadius + paddleSize.x / 2 + 0.1f, ball.getPosition().y); } // Right Paddle if (ball.getPosition().x + ballRadius > rightPaddle.getPosition().x - paddleSize.x / 2 && ball.getPosition().x + ballRadius < rightPaddle.getPosition().x && ball.getPosition().y + ballRadius >= rightPaddle.getPosition().y - paddleSize.y / 2 && ball.getPosition().y - ballRadius <= rightPaddle.getPosition().y + paddleSize.y / 2) { if (ball.getPosition().y > rightPaddle.getPosition().y) ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180; else ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180; ballSound.play(); ball.setPosition(rightPaddle.getPosition().x - ballRadius - paddleSize.x / 2 - 0.1f, ball.getPosition().y); } } //////////////////////////////////////////////////////////// // DRAW OBJECTS //////////////////////////////////////////////////////////// // Clear the window m_window.clear(sf::Color(50, 200, 50)); if (isPlaying) { // Draw the paddles and the ball m_window.draw(leftPaddle); m_window.draw(rightPaddle); m_window.draw(ball); } else { // Draw the pause message m_window.draw(pauseMessage); } // Display things on screen m_window.display(); } //////////////////////////////////////////////////////////// // Don't touch unless you know what you're doing. // #if defined(IS_ENGINE_HTML_5) // }); // #endif // //////////////////////////////////////////////////////////// return true; } }
40.756757
174
0.490302
[ "render" ]
0eb4a2870ef0f19ad325708da2b02dabcc8bfb1d
5,828
cpp
C++
Graph/Tree/Binary Tree/Flatten BT to a Singly Linked List.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Graph/Tree/Binary Tree/Flatten BT to a Singly Linked List.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Graph/Tree/Binary Tree/Flatten BT to a Singly Linked List.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Problem: https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list/ // Ref: http://www.crazyforcode.com/flatten-binary-tree-linked-list-in-place/ /***************************************************************************************************/ // METHOD - 1 /* A brute approach to solve this problem is by iterating over the tree in pre-order fashion. While traversing, store the values of the nodes in a list. Create the required linked list using the stored values. But this method is not in-place */ /********************************************************************************************************/ // METHOD - 2 (RECURSIVE IN-PLACE) #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; class TreeNode { public: int val; TreeNode *left; TreeNode *right; TreeNode(): val(0), left(NULL), right(NULL) {} TreeNode(int data): val(data), left(NULL), right(NULL) {} TreeNode(int data, TreeNode *left, TreeNode *right): val(data), left(left), right(right) {} }; void inorder(TreeNode *root) { if(root == NULL) return; inorder(root->left); cout << root->val << " "; inorder(root->right); } TreeNode* flatten(TreeNode *root) { if(root == NULL) return root; TreeNode *lft = flatten(root->left); TreeNode *rgt = flatten(root->right); root->left = NULL; root->right = lft; TreeNode *tmp = root; while(tmp->right != NULL) tmp = tmp->right; tmp->right = rgt; return root; } void solve() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->right->left = new TreeNode(4); root->right->right = new TreeNode(5); root->right->left->left = new TreeNode(6); root->right->left->right = new TreeNode(7); root->right->left->right->left = new TreeNode(8); root->right->left->right->right = new TreeNode(9); root = flatten(root); inorder(root); cout << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // int test = 1; // cin >> t; while(t--) { // cout << "Case #" << test++ << ": "; solve(); } return 0; } // TC: O(n) // SC: O(n), due to internal call stack /********************************************************************************************************/ // METHOD - 3 (ITERATIVE IN-PLACE) #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; class TreeNode { public: int val; TreeNode *left; TreeNode *right; TreeNode(): val(0), left(NULL), right(NULL) {} TreeNode(int data): val(data), left(NULL), right(NULL) {} TreeNode(int data, TreeNode *left, TreeNode *right): val(data), left(left), right(right) {} }; void inorder(TreeNode *root) { if(root == NULL) return; inorder(root->left); cout << root->val << " "; inorder(root->right); } TreeNode* flatten(TreeNode *root) { if(root == NULL) return root; TreeNode *cur = root; while(cur != NULL) { if(cur->left != NULL) { if(cur->right != NULL) { TreeNode *tmp = cur->left; while(tmp->right != NULL) tmp = tmp->right; tmp->right = cur->right; } cur->right = cur->left; cur->left = NULL; } cur = cur->right; } return root; } void solve() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->right->left = new TreeNode(4); root->right->right = new TreeNode(5); root->right->left->left = new TreeNode(6); root->right->left->right = new TreeNode(7); root->right->left->right->left = new TreeNode(8); root->right->left->right->right = new TreeNode(9); root = flatten(root); inorder(root); cout << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // int test = 1; // cin >> t; while(t--) { // cout << "Case #" << test++ << ": "; solve(); } return 0; } // TC: O(n) // SC: O(1)
24.8
106
0.59849
[ "vector" ]
0eb64a958898b2b81ced714507e25428b547da77
57,845
cpp
C++
src/core/gpuMemory.cpp
inequation/pal
1f6c2382823451d232dfb86dd54e7c63673d73e8
[ "MIT" ]
1
2021-11-27T15:15:29.000Z
2021-11-27T15:15:29.000Z
src/core/gpuMemory.cpp
inequation/pal
1f6c2382823451d232dfb86dd54e7c63673d73e8
[ "MIT" ]
null
null
null
src/core/gpuMemory.cpp
inequation/pal
1f6c2382823451d232dfb86dd54e7c63673d73e8
[ "MIT" ]
null
null
null
/* *********************************************************************************************************************** * * Copyright (c) 2014-2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/device.h" #include "core/gpuMemory.h" #include "core/image.h" #include "core/platform.h" #include "palDeveloperHooks.h" #include "palSysMemory.h" #include "palFormatInfo.h" using namespace Util; namespace Pal { #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 652 // ===================================================================================================================== // Copies only the valid heaps from pHeaps to pOutHeaps. The filtering happens based on if the heap exists on the // device. static uint32 CopyViableHeaps( const GpuHeap* pHeaps, uint32 heapCount, const Device& device, GpuHeap* pOutHeaps) { uint32 outHeapsCount = 0; for (uint32 heap = 0; heap < heapCount; ++heap) { const GpuMemoryHeapProperties& heapProps = device.HeapProperties(pHeaps[heap]); if (heapProps.heapSize > 0u) { pOutHeaps[outHeapsCount++] = pHeaps[heap]; } } return outHeapsCount; } #endif // ===================================================================================================================== Result GpuMemory::ValidateCreateInfo( const Device* pDevice, const GpuMemoryCreateInfo& createInfo) { Result result = Result::Success; const auto& memProps = pDevice->MemoryProperties(); if ((memProps.flags.multipleVaRangeSupport == 0) && (createInfo.vaRange != VaRange::Default) && (createInfo.vaRange != VaRange::DescriptorTable)) // We map DescriptorTable to Default on low-VA space configs { result = Result::ErrorOutOfGpuMemory; } if (createInfo.flags.useReservedGpuVa) { if (createInfo.pReservedGpuVaOwner == nullptr) { result = Result::ErrorInvalidPointer; } else { const gpusize fragmentSize = pDevice->MemoryProperties().fragmentSize; const gpusize alignment = Pow2Align(createInfo.alignment, fragmentSize); const GpuMemory* const pObj = static_cast<const GpuMemory* const>(createInfo.pReservedGpuVaOwner); const GpuMemoryDesc& desc = pObj->Desc(); if ((desc.gpuVirtAddr != Pow2Align(desc.gpuVirtAddr, alignment)) || (desc.alignment != createInfo.alignment) || (desc.size < createInfo.size) || (pObj->m_vaPartition != pDevice->ChooseVaPartition(createInfo.vaRange, createInfo.flags.virtualAlloc))) { result = Result::ErrorInvalidValue; } } } if (createInfo.flags.typedBuffer) { if (Formats::IsUndefined(createInfo.typedBufferInfo.swizzledFormat.format)) { result = Result::ErrorInvalidFormat; } else if ((createInfo.typedBufferInfo.extent.width == 0) || (createInfo.typedBufferInfo.extent.height == 0) || (createInfo.typedBufferInfo.extent.depth == 0) || (createInfo.typedBufferInfo.rowPitch == 0) || (createInfo.typedBufferInfo.depthPitch == 0)) { result = Result::ErrorInvalidValue; } } else if (createInfo.pImage != nullptr) { #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 585 const Pal::Image* pImage = static_cast<const Pal::Image*>(createInfo.pImage); if (createInfo.flags.presentable != pImage->GetImageCreateInfo().flags.presentable) { result = Result::ErrorInvalidFlags; } #endif } if ((result == Result::Success) && (createInfo.size == 0)) { // Cannot create an allocation of size 0! result = Result::ErrorInvalidMemorySize; } // If this is real GPU memory allocation, we need to know if it must reside in a non-local heap. bool nonLocalOnly = true; if (result == Result::Success) { if (createInfo.flags.virtualAlloc == false) { if (createInfo.heapCount == 0) { // Physical GPU memory allocations must specify at least one heap! result = Result::ErrorInvalidValue; } else { for (uint32 idx = 0; idx < createInfo.heapCount; ++idx) { if ((createInfo.heaps[idx] == GpuHeapLocal) || (createInfo.heaps[idx] == GpuHeapInvisible)) { nonLocalOnly = false; break; } } } } else if (createInfo.heapCount != 0) { // Virtual GPU memory allocations cannot specify any heaps! result = Result::ErrorInvalidValue; } } const gpusize allocGranularity = createInfo.flags.virtualAlloc ? memProps.virtualMemAllocGranularity : memProps.realMemAllocGranularity; if ((result == Result::Success) && createInfo.flags.shareable && (nonLocalOnly == false)) { // Shareable allocations must reside only in non-local heaps in order for multiple GPU's to access them // simultaneously without problems! result = Result::ErrorInvalidFlags; } if ((result == Result::Success) && createInfo.flags.globalGpuVa && (memProps.flags.globalGpuVaSupport == 0)) { // The globalGpuVa flag can't be set if the feature isn't supported! result = Result::ErrorInvalidFlags; } if ((result == Result::Success) && (createInfo.vaRange == Pal::VaRange::Svm) && ((memProps.flags.svmSupport == 0) || (pDevice->GetPlatform()->SvmModeEnabled() == false))) { // The SVM range can't be used if the feature isn't supported! result = Result::ErrorInvalidValue; } if ((result == Result::Success) && createInfo.flags.autoPriority && (memProps.flags.autoPrioritySupport == 0)) { // The autoPriority flag can't be set if the feature isn't supported! result = Result::ErrorInvalidFlags; } if (result == Result::Success) { if (createInfo.vaRange == VaRange::ShadowDescriptorTable) { const gpusize alignment = Max(createInfo.alignment, allocGranularity); gpusize descrStartAddr = 0; gpusize descrEndAddr = 0; pDevice->VirtualAddressRange(VaPartition::DescriptorTable, &descrStartAddr, &descrEndAddr); // The descriptor GPU VA must meet the address alignment and fit in the DescriptorTable range. if (((createInfo.descrVirtAddr % alignment) != 0) || (createInfo.descrVirtAddr < descrStartAddr) || (createInfo.descrVirtAddr >= descrEndAddr)) { result = Result::ErrorInvalidValue; } } else if ((createInfo.descrVirtAddr != 0) && (createInfo.flags.useReservedGpuVa == false) && (createInfo.vaRange != VaRange::CaptureReplay)) { // The "descrVirtAddr" field is only used for the ShadowDescriptorTable VA range. result = Result::ErrorInvalidValue; } } #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) if ((result == Result::Success) && (createInfo.flags.mallRangeActive != 0)) { // Page size for specifyng a MALL range is always in units of 4kB pages constexpr uint32 PageSize = 4096; // If the mall-range is active then the mall policy must be either "always" or "never"; the KMD // ensures that the memory associated with this allocation outside the specified region gets the // "opposite" mall policy. if ((createInfo.mallPolicy == GpuMemMallPolicy::Default) || // Ensure that the specified range fits within the size of this allocation. (((createInfo.mallRange.startPage + createInfo.mallRange.numPages) * PageSize) > createInfo.size)) { result = Result::ErrorInvalidValue; } } #endif if ((result == Result::Success) && createInfo.flags.gl2Uncached && (pDevice->ChipProperties().gfxip.supportGl2Uncached == 0)) { // The gl2Uncached flag can't be set if the feature isn't supported! result = Result::ErrorInvalidFlags; } return result; } // ===================================================================================================================== Result GpuMemory::ValidatePinInfo( const Device* pDevice, const PinnedGpuMemoryCreateInfo& createInfo) { Result result = Result::ErrorInvalidPointer; const gpusize alignment = pDevice->MemoryProperties().realMemAllocGranularity; if (IsPow2Aligned(reinterpret_cast<gpusize>(createInfo.pSysMem), alignment)) { result = IsPow2Aligned(createInfo.size, alignment) ? Result::Success : Result::ErrorInvalidMemorySize; } return result; } // ===================================================================================================================== Result GpuMemory::ValidateSvmInfo( const Device* pDevice, const SvmGpuMemoryCreateInfo& createInfo) { Result result = Result::ErrorInvalidPointer; const gpusize alignment = pDevice->MemoryProperties().realMemAllocGranularity; if (IsPow2Aligned(createInfo.alignment, alignment)) { result = IsPow2Aligned(createInfo.size, alignment) ? Result::Success : Result::ErrorInvalidAlignment; } return result; } // ===================================================================================================================== Result GpuMemory::ValidateOpenInfo( const Device* pDevice, const GpuMemoryOpenInfo& openInfo) { Result result = Result::Success; const GpuMemory* pOriginalMem = static_cast<GpuMemory*>(openInfo.pSharedMem); if (openInfo.pSharedMem == nullptr) { result = Result::ErrorInvalidPointer; } else if (pOriginalMem->IsShareable() == false) { result = Result::ErrorNotShareable; } return result; } // ===================================================================================================================== Result GpuMemory::ValidatePeerOpenInfo( const Device* pDevice, const PeerGpuMemoryOpenInfo& peerInfo) { Result result = Result::Success; if (peerInfo.pOriginalMem == nullptr) { result = Result::ErrorInvalidPointer; } return result; } // ===================================================================================================================== GpuMemory::GpuMemory( Device* pDevice) : m_pDevice(pDevice), m_vaPartition(VaPartition::Default), m_heapCount(0), m_priority(GpuMemPriority::Unused), m_priorityOffset(GpuMemPriorityOffset::Offset0), m_pImage(nullptr), m_mtype(MType::Default), m_minPageSize(PAL_PAGE_BYTES), m_remoteSdiSurfaceIndex(0), m_remoteSdiMarkerIndex(0), m_markerVirtualAddr(0) ,m_mallPolicy(GpuMemMallPolicy::Default) { memset(&m_desc, 0, sizeof(m_desc)); memset(&m_heaps[0], 0, sizeof(m_heaps)); memset(&m_typedBufferInfo, 0, sizeof(m_typedBufferInfo)); #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) memset(&m_mallRange, 0, sizeof(m_mallRange)); #endif m_flags.u64All = 0; m_pPinnedMemory = nullptr; m_pOriginalMem = nullptr; } // ===================================================================================================================== GpuMemory::~GpuMemory() { // We need to force-remove this allocation from the device's per-heap memory totals because the client might not // call RemoveGpuMemoryReferences once for each time they call AddGpuMemoryReferences. IGpuMemory*const pGpuMemory = this; m_pDevice->SubtractFromReferencedMemoryTotals(1, &pGpuMemory, true); m_pDevice->GetPlatform()->GetEventProvider()->LogDestroyGpuMemoryEvent(this); Developer::GpuMemoryData data = {}; data.size = m_desc.size; data.heap = m_heaps[0]; data.flags.isClient = IsClient(); data.flags.isFlippable = IsFlippable(); data.flags.isUdmaBuffer = IsUdmaBuffer(); data.flags.isCmdAllocator = IsCmdAllocator(); data.flags.isVirtual = IsVirtual(); m_pDevice->DeveloperCb(Developer::CallbackType::FreeGpuMemory, &data); } // ===================================================================================================================== // Initializes GPU memory objects that are built from create info structs. This includes: // - Real GPU memory allocations owned by the local process. // - Virtual GPU memory allocations owned by the local process. // - External, shared GPU memory objects that point to GPU memory allocations owned by an external process. Result GpuMemory::Init( const GpuMemoryCreateInfo& createInfo, const GpuMemoryInternalCreateInfo& internalInfo) { m_pImage = static_cast<Image*>(createInfo.pImage); m_desc.flags.isVirtual = createInfo.flags.virtualAlloc || createInfo.flags.sdiExternal; m_desc.flags.isExternPhys = createInfo.flags.sdiExternal; m_desc.flags.isExternal = internalInfo.flags.isExternal; m_desc.flags.isShared = internalInfo.flags.isExternal; // External memory is memory shared between processes. { m_flags.isPresentable = createInfo.flags.presentable; m_flags.isFlippable = createInfo.flags.flippable; m_flags.isShareable = createInfo.flags.shareable; m_flags.interprocess = createInfo.flags.interprocess; m_flags.peerWritable = createInfo.flags.peerWritable; m_flags.turboSyncSurface = createInfo.flags.turboSyncSurface; } m_flags.globallyCoherent = createInfo.flags.globallyCoherent; m_flags.xdmaBuffer = createInfo.flags.xdmaBuffer || internalInfo.flags.xdmaBuffer; m_flags.globalGpuVa = createInfo.flags.globalGpuVa; m_flags.useReservedGpuVa = createInfo.flags.useReservedGpuVa; m_flags.typedBuffer = createInfo.flags.typedBuffer; m_flags.busAddressable = createInfo.flags.busAddressable; m_flags.isStereo = createInfo.flags.stereo; m_flags.autoPriority = createInfo.flags.autoPriority; m_flags.restrictedContent = createInfo.flags.restrictedContent; m_flags.restrictedAccess = createInfo.flags.restrictedAccess; m_flags.crossAdapter = createInfo.flags.crossAdapter; m_flags.tmzProtected = createInfo.flags.tmzProtected; m_flags.tmzUserQueue = internalInfo.flags.tmzUserQueue; #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_flags.mallRangeActive = createInfo.flags.mallRangeActive; #endif m_flags.isClient = internalInfo.flags.isClient; m_flags.pageDirectory = internalInfo.flags.pageDirectory; m_flags.pageTableBlock = internalInfo.flags.pageTableBlock; m_flags.udmaBuffer = internalInfo.flags.udmaBuffer; m_flags.unmapInfoBuffer = internalInfo.flags.unmapInfoBuffer; m_flags.historyBuffer = internalInfo.flags.historyBuffer; m_flags.isCmdAllocator = internalInfo.flags.isCmdAllocator; m_flags.buddyAllocated = internalInfo.flags.buddyAllocated; m_flags.privateScreen = internalInfo.flags.privateScreen; m_flags.isUserQueue = internalInfo.flags.userQueue; m_flags.isTimestamp = internalInfo.flags.timestamp; m_flags.accessedPhysically = internalInfo.flags.accessedPhysically; m_flags.gpuReadOnly = internalInfo.flags.gpuReadOnly; if (IsClient() == false) { m_flags.autoPriority = m_pDevice->IsUsingAutoPriorityForInternalAllocations(); } if (IsTypedBuffer()) { memcpy(&m_typedBufferInfo, &(createInfo.typedBufferInfo), sizeof(TypedBufferCreateInfo)); } // In general, private driver resources are expected to be always resident. The app and/or client is expected to // manage residency for anything that doesn't set this flag, including: // - Resources allocated using CreateGpuMemory(). // - Presentable images. // - Private screens. // - Peer memory and images. // - Shared memory and images. // - External, shared memory and images. // - setting has enabled always resident by default m_flags.alwaysResident = m_pDevice->Settings().alwaysResident || internalInfo.flags.alwaysResident; // Asking for the paging fence value returned by the OS is pointless if the allocation is not marked as // always resident. PAL_ALERT((IsAlwaysResident() == false) && (internalInfo.pPagingFence != nullptr)); const gpusize allocGranularity = (IsVirtual() == false) ? m_pDevice->MemoryProperties().realMemAllocGranularity : m_pDevice->MemoryProperties().virtualMemAllocGranularity; // If this is not external SDI memory, align size and base alignment to allocGranularity. If no alignment value was // provided, use the allocation granularity. This enforces a general PAL assumption: GPU memory objects have page // aligned addresses and sizes. if (createInfo.flags.sdiExternal == 0) { m_desc.size = Pow2Align(createInfo.size, allocGranularity); m_desc.alignment = ((createInfo.alignment != 0) ? Pow2Align(createInfo.alignment, allocGranularity) : allocGranularity); PAL_ASSERT((createInfo.alignment == 0) || ((m_desc.alignment % createInfo.alignment) == 0)); } else { m_desc.size = createInfo.size; m_desc.alignment = ((createInfo.alignment != 0) ? createInfo.alignment : allocGranularity); } m_vaPartition = m_pDevice->ChooseVaPartition(createInfo.vaRange, (createInfo.flags.virtualAlloc != 0)); m_priority = createInfo.priority; m_priorityOffset = createInfo.priorityOffset; m_mallPolicy = createInfo.mallPolicy; #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_mallRange = createInfo.mallRange; #endif #if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 652 m_heapCount = createInfo.heapCount; #endif m_schedulerId = internalInfo.schedulerId; m_mtype = internalInfo.mtype; // The number of reserved compute units for a real-time queue m_numReservedCu = internalInfo.numReservedCu; if (IsBusAddressable()) { // one extra page for marker const gpusize pageSize = m_pDevice->MemoryProperties().virtualMemPageSize; m_desc.size = Pow2Align(m_desc.size, pageSize) + pageSize; } if (IsVirtual() == false) { #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 652 switch (createInfo.heapAccess) { case GpuHeapAccess::GpuHeapAccessExplicit: // imperative heap selection; createInfo.heaps determines the heaps m_heapCount = createInfo.heapCount; for (uint32 heap = 0; heap < createInfo.heapCount; ++heap) { m_heaps[heap] = createInfo.heaps[heap]; } break; case GpuHeapAccess::GpuHeapAccessCpuNoAccess: { // declarative heap selection; memory does not need to be CPU accessible const GpuChipProperties& chipProps = m_pDevice->ChipProperties(); switch (chipProps.gpuType) { case GpuType::Discrete: { // considering both invisible and local, in case the former is 0 (e.g., under Resizable BAR) constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapInvisible, GpuHeap::GpuHeapLocal }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; case GpuType::Integrated: { // integrated solutions seem to miss invisible and local constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapGartUswc, GpuHeap::GpuHeapGartCacheable }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; default: PAL_ALERT_ALWAYS_MSG("Unexpected GPU type"); break; } } break; case GpuHeapAccess::GpuHeapAccessGpuMostly: { // declarative heap selection; optimized for GPU access constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapLocal, GpuHeap::GpuHeapGartUswc, GpuHeap::GpuHeapGartCacheable }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; case GpuHeapAccess::GpuHeapAccessCpuReadMostly: { // declarative heap selection; CPU will mostly do reads constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapGartCacheable }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; case GpuHeapAccess::GpuHeapAccessCpuWriteMostly: { // declarative heap selection; CPU will do multiple writes constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapGartUswc }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; case GpuHeapAccess::GpuHeapAccessCpuMostly: { // declarative heap selection; CPU will do a mix of reads and writes constexpr GpuHeap PreferredHeaps[] = { GpuHeap::GpuHeapGartUswc, GpuHeap::GpuHeapGartCacheable }; m_heapCount = CopyViableHeaps(PreferredHeaps, ArrayLen32(PreferredHeaps), *m_pDevice, m_heaps); } break; default: PAL_ALERT_ALWAYS_MSG("Unexpected GPU heap access type"); break; } PAL_ASSERT(m_heapCount > 0u); #endif // NOTE: Assume that the heap selection is both local-only and nonlocal-only temporarily. When we scan the // heap selections below, this paradoxical assumption will be corrected. m_flags.localOnly = 1; m_flags.nonLocalOnly = 1; // NOTE: Any memory object not being used as a page-directory or page-table block is considered to be CPU // visible as long as all of its selected heaps are CPU visible. m_flags.cpuVisible = ((m_flags.pageDirectory == 0) && (m_flags.pageTableBlock == 0) && (createInfo.flags.cpuInvisible == 0)); for (uint32 heap = 0; heap < m_heapCount; ++heap) { #if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 652 m_heaps[heap] = createInfo.heaps[heap]; #endif const GpuMemoryHeapProperties& heapProps = m_pDevice->HeapProperties(m_heaps[heap]); if (heapProps.flags.cpuVisible == 0) { m_flags.cpuVisible = 0; } switch (m_heaps[heap]) { case GpuHeapLocal: case GpuHeapInvisible: m_flags.nonLocalOnly = 0; break; case GpuHeapGartCacheable: case GpuHeapGartUswc: m_flags.localOnly = 0; break; default: PAL_ALERT_ALWAYS_MSG("Unexpected GPU heap type"); break; } } // Give OS-specific code an opportunity to examine the client-specified heaps and add an extra GART backup // heap for local-only allocations if needed. if (m_heapCount > 0) { PAL_ASSERT((m_flags.nonLocalOnly == 0) || (m_flags.localOnly == 0)); OsFinalizeHeaps(); } } m_desc.preferredHeap = m_heaps[0]; m_flags.isLocalPreferred = ((m_heaps[0] == GpuHeapLocal) || (m_heaps[0] == GpuHeapInvisible)); Result result = Result::Success; if (IsShared()) { result = OpenSharedMemory(internalInfo.hExternalResource); if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Opened); } } else { gpusize baseVirtAddr = internalInfo.baseVirtAddr; if (createInfo.flags.useReservedGpuVa && (createInfo.pReservedGpuVaOwner != nullptr)) { const GpuMemoryDesc& desc = createInfo.pReservedGpuVaOwner->Desc(); // It's illegal for the internal path to specify non-zero base VA when client already does. PAL_ASSERT(internalInfo.baseVirtAddr == 0); // Do not expect client set "useReservedGpuVa" for ShadowDescriptorTable case PAL_ASSERT(m_vaPartition != VaPartition::ShadowDescriptorTable); baseVirtAddr = desc.gpuVirtAddr; } if (m_vaPartition == VaPartition::ShadowDescriptorTable) { // It's illegal for the internal path to use this VA range. PAL_ASSERT(IsClient()); gpusize descrStartAddr = 0; gpusize descrEndAddr = 0; gpusize shadowStartAddr = 0; gpusize shadowEndAddr = 0; m_pDevice->VirtualAddressRange(VaPartition::DescriptorTable, &descrStartAddr, &descrEndAddr); m_pDevice->VirtualAddressRange(VaPartition::ShadowDescriptorTable, &shadowStartAddr, &shadowEndAddr); // The descriptor GPU VA must meet the address alignment and fit in the DescriptorTable range. PAL_ASSERT(((createInfo.descrVirtAddr % m_desc.alignment) == 0) && (createInfo.descrVirtAddr >= descrStartAddr) && (createInfo.descrVirtAddr < descrEndAddr)); baseVirtAddr = shadowStartAddr + (createInfo.descrVirtAddr - descrStartAddr); } else if ((createInfo.vaRange == VaRange::Svm) && (m_pDevice->MemoryProperties().flags.iommuv2Support == 0)) { result = AllocateSvmVirtualAddress(baseVirtAddr, createInfo.size, createInfo.alignment, false); baseVirtAddr = m_desc.gpuVirtAddr; } else if (createInfo.vaRange == VaRange::Default) { // For performance reasons we may wish to force our GPU memory allocations' addresses and sizes to be // either fragment-aligned or aligned to KMD's reported optimized large page size, big page size or for // specific images iterate256 page size. This should be skipped if any of the following are true: // - We're not using the default VA range because non-default VA ranges have special address usage rules. // - We have selected a specific base VA for the allocation because it might not be 64KB aligned. // - The allocation prefers a non-local heap because we can only get 64KB fragments in local memory. // - The allocation prefers a local visible heap on ResizeBarOff case. Local visible heap size in // ResizeBarOff case has small size (usually 256MB); it's easy to run out of the heap size due to various // alignment padding which will cause worse performance. // - Type is SDI ExternalPhysical because it has no real allocation and size must be consistent with KMD. auto memoryProperties = m_pDevice->MemoryProperties(); if ((baseVirtAddr == 0) && ((m_heaps[0] == GpuHeapInvisible) || ((m_heaps[0] == GpuHeapLocal) && (memoryProperties.invisibleHeapSize == 0))) && (createInfo.flags.sdiExternal == 0)) { gpusize idealAlignment = 0; if (memoryProperties.largePageSupport.gpuVaAlignmentNeeded || memoryProperties.largePageSupport.sizeAlignmentNeeded) { const gpusize largePageSize = memoryProperties.largePageSupport.largePageSizeInBytes; idealAlignment = Max(idealAlignment, largePageSize); } // BigPage is only supported for allocations > bigPageMinAlignment. // Also, if bigPageMinAlignment == 0, BigPage optimization is not supported per KMD. // We do either LargePage or BigPage alignment, whichever has a higher value. if ((memoryProperties.bigPageMinAlignment > 0) && m_pDevice->Settings().enableBigPagePreAlignment && (createInfo.size >= memoryProperties.bigPageMinAlignment)) { gpusize bigPageSize = memoryProperties.bigPageMinAlignment; if ((memoryProperties.bigPageLargeAlignment > 0) && (createInfo.size >= memoryProperties.bigPageLargeAlignment)) { bigPageSize = memoryProperties.bigPageLargeAlignment; } idealAlignment = Max(idealAlignment, bigPageSize); } // Finally, we try to do alignment for iterate256 hardware optimization if m_pImage is populated and // all required conditions for the device and image to support it are met. // When we do this we are actually making this Image (rather the memory block/page that contains this // Image) compatible to pass the conditions of Image::GetIterate256(); which in turn will actually help // when creating this Image's SRD or for setting the value of the iterate256 register or the related // DecompressOnNZPlanes register. if ((m_pImage != nullptr) && m_pDevice->GetGfxDevice()->SupportsIterate256()) { // If the device supports iterate256 the Image should satisy some conditions so that we can // justify aligning memory to make the optimization work. #if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 642 const SubResourceInfo* pBaseSubResInfo = m_pImage->SubresourceInfo(m_pImage->GetBaseSubResource()); #else const SubResourceInfo* pBaseSubResInfo = m_pImage->SubresourceInfo(0); #endif if (m_pDevice->Settings().enableIterate256PreAlignment && m_pImage->GetGfxImage()->IsIterate256Meaningful(pBaseSubResInfo) && (createInfo.size >= memoryProperties.iterate256MinAlignment)) { gpusize iterate256PageSize = memoryProperties.iterate256MinAlignment; if ((memoryProperties.iterate256LargeAlignment > 0) && createInfo.size >= memoryProperties.iterate256LargeAlignment) { iterate256PageSize = memoryProperties.iterate256LargeAlignment; } idealAlignment = Max(idealAlignment, iterate256PageSize); } } // The client decides whether or not we pad allocations at all and so should be the final // deciding factor on use of ideal alignment. #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 584 if((createInfo.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForVaAlignmentInBytes) && #else if ((createInfo.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForAlignmentInBytes) && #endif (idealAlignment != 0)) { m_desc.alignment = Pow2Align(m_desc.alignment, idealAlignment); } #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 584 if ((createInfo.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForSizeAlignmentInBytes) && #else if ((createInfo.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForAlignmentInBytes) && #endif (idealAlignment != 0)) { m_desc.size = Pow2Align(m_desc.size, idealAlignment); } } } else if (createInfo.vaRange == VaRange::CaptureReplay) { baseVirtAddr = createInfo.replayVirtAddr; } if (result == Result::Success && (Desc().flags.isExternPhys == false)) { result = AllocateOrPinMemory(baseVirtAddr, internalInfo.pPagingFence, createInfo.virtualAccessMode, 0, nullptr, nullptr); if (IsVirtual() == false) { const gpusize fragmentSize = m_pDevice->MemoryProperties().fragmentSize; // All currently supported OSes manage local framebuffer memory as physically contiguous allocations. // This means that if the assigned VA, the requested PA alignment, and allocation size are all // fragment aligned, we know that various "big page" hardware features are valid if the required // big page size is compatible with the KMD-reported fragment size. if (IsLocalOnly() && IsPow2Aligned(m_desc.gpuVirtAddr, fragmentSize) && IsPow2Aligned(GetPhysicalAddressAlignment(), fragmentSize) && IsPow2Aligned(m_desc.size, fragmentSize)) { m_minPageSize = fragmentSize; } } } if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Normal); } } // Verify that if the allocation succeeded, we got a GPU virtual address back as expected (except for // page directory and page table allocations and SDI External Physical Memory). if ((IsPageDirectory() == false) && (IsPageTableBlock() == false) && (Desc().flags.isExternPhys == false)) { PAL_ASSERT((result != Result::Success) || (m_desc.gpuVirtAddr != 0)); } return result; } // ===================================================================================================================== // Initializes this GPU memory object as a SVM memory allocation. Result GpuMemory::Init( const SvmGpuMemoryCreateInfo& createInfo) { Result result = Result::Success; m_flags.isPinned = 1; m_flags.nonLocalOnly = 1; // Pinned allocations always go into a non-local heap. m_flags.cpuVisible = 1; // Pinned allocations are by definition CPU visible. m_flags.useReservedGpuVa = createInfo.flags.useReservedGpuVa; m_desc.size = createInfo.size; m_desc.alignment = createInfo.alignment; if (createInfo.flags.gl2Uncached) { m_mtype = MType::Uncached; } m_mallPolicy = createInfo.mallPolicy; #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_mallRange = createInfo.mallRange; #endif m_vaPartition = VaPartition::Svm; gpusize baseVirtAddr = 0; if (IsGpuVaPreReserved()) { baseVirtAddr = createInfo.pReservedGpuVaOwner->Desc().gpuVirtAddr; } if (m_pDevice->MemoryProperties().flags.iommuv2Support) { m_desc.flags.isSvmAlloc = 1; if (createInfo.isUsedForKernel) { m_desc.flags.isExecutable = 1; } } else { result = AllocateSvmVirtualAddress(baseVirtAddr, createInfo.size, createInfo.alignment, true); } if (result == Result::Success) { // Scan the list of available GPU heaps to determine which heap(s) this pinned allocation will end up in. for (uint32 idx = 0; idx < GpuHeapCount; ++idx) { const GpuHeap heap = static_cast<GpuHeap>(idx); if (m_pDevice->HeapProperties(heap).flags.holdsPinned != 0) { m_heaps[m_heapCount++] = heap; } } m_desc.preferredHeap = m_heaps[0]; m_flags.isLocalPreferred = ((m_heaps[0] == GpuHeapLocal) || (m_heaps[0] == GpuHeapInvisible)); result = AllocateOrPinMemory(m_desc.gpuVirtAddr, nullptr, VirtualGpuMemAccessMode::Undefined, 0, nullptr, nullptr); m_pPinnedMemory = reinterpret_cast<const void*>(m_desc.gpuVirtAddr); } PAL_ASSERT((result != Result::Success) || (m_desc.gpuVirtAddr != 0)); if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Svm); } return result; } // ===================================================================================================================== // Initializes this GPU memory object as a pinned (GPU-accessible) system-memory allocation. Result GpuMemory::Init( const PinnedGpuMemoryCreateInfo& createInfo) { m_flags.isPinned = 1; m_flags.nonLocalOnly = 1; // Pinned allocations always go into a non-local heap. m_flags.cpuVisible = 1; // Pinned allocations are by definition CPU visible. m_pPinnedMemory = createInfo.pSysMem; m_mallPolicy = createInfo.mallPolicy; #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_mallRange = createInfo.mallRange; #endif m_desc.size = createInfo.size; m_desc.alignment = (createInfo.alignment != 0) ? createInfo.alignment : m_pDevice->MemoryProperties().realMemAllocGranularity; m_vaPartition = m_pDevice->ChooseVaPartition(createInfo.vaRange, false); // Scan the list of available GPU heaps to determine which heap(s) this pinned allocation will end up in. for (uint32 idx = 0; idx < GpuHeapCount; ++idx) { const GpuHeap heap = static_cast<GpuHeap>(idx); if (m_pDevice->HeapProperties(heap).flags.holdsPinned != 0) { m_heaps[m_heapCount++] = heap; } } m_desc.preferredHeap = m_heaps[0]; m_flags.isLocalPreferred = ((m_heaps[0] == GpuHeapLocal) || (m_heaps[0] == GpuHeapInvisible)); const Result result = AllocateOrPinMemory(0, nullptr, VirtualGpuMemAccessMode::Undefined, 0, nullptr, nullptr); // Verify that if the pinning succeeded, we got a GPU virtual address back as expected. PAL_ASSERT((result != Result::Success) || (m_desc.gpuVirtAddr != 0)); if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Pinned); } return result; } // ===================================================================================================================== // Initializes this GPU memory object as a share of the other memory object specified in openInfo.pSharedMem. // The shared memory must be owned by the local process, external shared memory uses a different init path. Result GpuMemory::Init( const GpuMemoryOpenInfo& openInfo) { m_pOriginalMem = static_cast<GpuMemory*>(openInfo.pSharedMem); m_desc.size = m_pOriginalMem->m_desc.size; m_desc.alignment = m_pOriginalMem->m_desc.alignment; m_vaPartition = m_pOriginalMem->m_vaPartition; m_mtype = m_pOriginalMem->m_mtype; m_heapCount = m_pOriginalMem->m_heapCount; m_mallPolicy = m_pOriginalMem->MallPolicy(); #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_mallRange = m_pOriginalMem->MallRange(); #endif for (uint32 i = 0; i < m_heapCount; ++i) { m_heaps[i] = m_pOriginalMem->m_heaps[i]; } m_desc.preferredHeap = m_heaps[0]; m_desc.flags.isShared = 1; m_flags.isShareable = m_pOriginalMem->m_flags.isShareable; m_flags.isFlippable = m_pOriginalMem->m_flags.isFlippable; m_flags.isStereo = m_pOriginalMem->m_flags.isStereo; m_flags.localOnly = m_pOriginalMem->m_flags.localOnly; m_flags.nonLocalOnly = m_pOriginalMem->m_flags.nonLocalOnly; m_flags.isLocalPreferred = m_pOriginalMem->m_flags.isLocalPreferred; m_flags.interprocess = m_pOriginalMem->m_flags.interprocess; m_flags.globalGpuVa = m_pOriginalMem->m_flags.globalGpuVa; m_flags.cpuVisible = m_pOriginalMem->m_flags.cpuVisible; // Set the gpuVirtAddr if the GPU VA is visible to all devices if (IsGlobalGpuVa()) { m_desc.gpuVirtAddr = m_pOriginalMem->m_desc.gpuVirtAddr; } // NOTE: The following flags are not expected to be set for shared memory objects! PAL_ASSERT((m_pOriginalMem->m_desc.flags.isVirtual == 0) && (m_pOriginalMem->m_desc.flags.isPeer == 0) && (m_pOriginalMem->m_flags.isPinned == 0) && (m_pOriginalMem->m_flags.pageDirectory == 0) && (m_pOriginalMem->m_flags.pageTableBlock == 0) && (m_pOriginalMem->m_flags.isCmdAllocator == 0) && (m_pOriginalMem->m_flags.udmaBuffer == 0) && (m_pOriginalMem->m_flags.historyBuffer == 0) && (m_pOriginalMem->m_flags.xdmaBuffer == 0) && (m_pOriginalMem->m_flags.buddyAllocated == 0) && (m_pOriginalMem->m_flags.alwaysResident == 0)); Pal::GpuMemoryExportInfo exportInfo = { }; const Result result = OpenSharedMemory( #if PAL_AMDGPU_BUILD m_pOriginalMem->ExportExternalHandle(exportInfo)); #else 0); #endif if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Opened); } // Verify that if opening the peer memory connection succeeded, we got a GPU virtual address back as expected. PAL_ASSERT((result != Result::Success) || (m_desc.gpuVirtAddr != 0)); return result; } // ===================================================================================================================== // Initializes this GPU memory object as a peer of the other memory object specified in peerInfo.pOriginalMem. Result GpuMemory::Init( const PeerGpuMemoryOpenInfo& peerInfo) { m_pOriginalMem = static_cast<GpuMemory*>(peerInfo.pOriginalMem); m_desc.size = m_pOriginalMem->m_desc.size; m_desc.alignment = m_pOriginalMem->m_desc.alignment; m_vaPartition = m_pOriginalMem->m_vaPartition; m_mtype = m_pOriginalMem->m_mtype; m_heapCount = m_pOriginalMem->m_heapCount; m_mallPolicy = m_pOriginalMem->MallPolicy(); #if ( (PAL_CLIENT_INTERFACE_MAJOR_VERSION>= 569)) m_mallRange = m_pOriginalMem->MallRange(); #endif for (uint32 i = 0; i < m_heapCount; ++i) { m_heaps[i] = m_pOriginalMem->m_heaps[i]; } m_desc.preferredHeap = m_heaps[0]; m_desc.flags.isPeer = 1; m_flags.isShareable = m_pOriginalMem->m_flags.isShareable; m_flags.isFlippable = m_pOriginalMem->m_flags.isFlippable; m_flags.isStereo = m_pOriginalMem->m_flags.isStereo; m_flags.localOnly = m_pOriginalMem->m_flags.localOnly; m_flags.nonLocalOnly = m_pOriginalMem->m_flags.nonLocalOnly; m_flags.isLocalPreferred = m_pOriginalMem->m_flags.isLocalPreferred; m_flags.interprocess = m_pOriginalMem->m_flags.interprocess; m_flags.globalGpuVa = m_pOriginalMem->m_flags.globalGpuVa; m_flags.useReservedGpuVa = (m_vaPartition == VaPartition::Svm); m_flags.cpuVisible = m_pOriginalMem->m_flags.cpuVisible; m_flags.peerWritable = m_pOriginalMem->m_flags.peerWritable; PAL_ASSERT(m_flags.peerWritable == 1); // Set the gpuVirtAddr if the GPU VA is visible to all devices if (IsGlobalGpuVa() || IsGpuVaPreReserved()) { m_desc.gpuVirtAddr = m_pOriginalMem->m_desc.gpuVirtAddr; } // NOTE: The following flags are not expected to be set for peer memory objects! PAL_ASSERT((m_pOriginalMem->m_desc.flags.isVirtual == 0) && (m_pOriginalMem->m_desc.flags.isShared == 0) && (m_pOriginalMem->m_flags.isPinned == 0) && (m_pOriginalMem->m_flags.pageDirectory == 0) && (m_pOriginalMem->m_flags.pageTableBlock == 0) && (m_pOriginalMem->m_flags.isCmdAllocator == 0) && (m_pOriginalMem->m_flags.udmaBuffer == 0) && (m_pOriginalMem->m_flags.historyBuffer == 0) && (m_pOriginalMem->m_flags.xdmaBuffer == 0) && (m_pOriginalMem->m_flags.buddyAllocated == 0)); const Result result = OpenPeerMemory(); if (result == Result::Success) { // If this object's VA is aligned to the source object's minimum page size, inherit its minimum page size. // Otherwise, stick with 4KiB default and we will have to potentially lose out on some big page optimizations. const gpusize origMinPageSize = m_pOriginalMem->MinPageSize(); if (IsPow2Aligned(m_desc.gpuVirtAddr, origMinPageSize)) { m_minPageSize = origMinPageSize; } } if (IsErrorResult(result) == false) { DescribeGpuMemory(Developer::GpuMemoryAllocationMethod::Peer); } // Verify that if opening the peer memory connection succeeded, we got a GPU virtual address back as expected. PAL_ASSERT((result != Result::Success) || (m_desc.gpuVirtAddr != 0)); return result; } // ===================================================================================================================== // Destroys an internal GPU memory object: invokes the destructor and frees the system memory block it resides in. void GpuMemory::DestroyInternal() { Platform* pPlatform = m_pDevice->GetPlatform(); Destroy(); PAL_FREE(this, pPlatform); } // ===================================================================================================================== // Set mapppedToPeerMemory flag for virtual GPU memory when mapped to peer real memory. void GpuMemory::SetMapDestPeerMem(GpuMemory* pMapDestPeerMem) { // The p2p workaround only supports one mapping per virtual GPU memory object. PAL_ASSERT(pMapDestPeerMem->IsPeer()); PAL_ASSERT((m_pMapDestPeerMem == nullptr) || (m_pMapDestPeerMem == pMapDestPeerMem)); m_pMapDestPeerMem = pMapDestPeerMem; m_flags.mapppedToPeerMemory = 1; } // ===================================================================================================================== // Changes the allocation's priority. This is only supported for "real" allocations. Result GpuMemory::SetPriority( GpuMemPriority priority, GpuMemPriorityOffset priorityOffset) { Result result = Result::ErrorUnavailable; if ((IsPinned() == false) && (IsVirtual() == false) && (IsPeer() == false) && (IsAutoPriority() == false) && (IsShared() == false)) { // Save off the new priority information. m_priority = priority; m_priorityOffset = priorityOffset; // Call the OS to change the priority of the GpuMemory allocation. result = OsSetPriority(priority, priorityOffset); } return result; } // ===================================================================================================================== // Maps the GPU memory allocation into CPU address space. Result GpuMemory::Map( void** ppData) { Result result = Result::ErrorInvalidPointer; if (ppData != nullptr) { if (IsPinned()) { PAL_ASSERT(m_pPinnedMemory != nullptr); (*ppData) = const_cast<void*>(m_pPinnedMemory); result = Result::Success; } else if (IsVirtual()) { (*ppData) = nullptr; result = Result::ErrorUnavailable; } else if (IsCpuVisible()) { if (IsSvmAlloc()) { (*ppData) = reinterpret_cast<void*>(m_desc.gpuVirtAddr); result = Result::Success; } else { result = OsMap(ppData); } } else { (*ppData) = nullptr; result = Result::ErrorNotMappable; } if (result == Result::Success) { m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryCpuMapEvent(this); } } return result; } // ===================================================================================================================== // Unmaps the GPU memory allocation out of CPU address space. Result GpuMemory::Unmap() { Result result = Result::ErrorNotMappable; if (IsPinned()) { result = Result::Success; } else if (IsCpuVisible()) { if (IsSvmAlloc()) { result = Result::Success; } else { result = OsUnmap(); } } else if (IsVirtual()) { result = Result::ErrorUnavailable; } if (result == Result::Success) { m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryCpuUnmapEvent(this); } return result; } // ===================================================================================================================== // Describes the GPU memory allocation to the above layers void GpuMemory::DescribeGpuMemory( Developer::GpuMemoryAllocationMethod allocMethod ) const { Developer::GpuMemoryData data = {}; data.size = m_desc.size; data.heap = m_heaps[0]; data.flags.isClient = IsClient(); data.flags.isFlippable = IsFlippable(); data.flags.isCmdAllocator = IsCmdAllocator(); data.flags.isUdmaBuffer = IsUdmaBuffer(); data.flags.isVirtual = IsVirtual(); data.allocMethod = allocMethod; m_pDevice->DeveloperCb(Developer::CallbackType::AllocGpuMemory, &data); } // ===================================================================================================================== bool GpuMemory::IsCpuVisible() const { bool isCpuVisible = (m_flags.cpuVisible != 0); return isCpuVisible; } // ===================================================================================================================== // Returns an acceptable physical memory address base alignment for the given gpu memory object. To avoid fragmentation // this should be a small value unless there are hardware or OS reasons to increase it. gpusize GpuMemory::GetPhysicalAddressAlignment() const { // By default copy the virtual address alignment. This is the safest thing we can do and will meet all HW // requirements, assuming the caller gave us a properly aligned alignment as required by the PAL interface. gpusize alignment = m_desc.alignment; // Now if this GPU memory object doesn't place special requirements on the physical address alignment we want to // pick a much smaller alignment to avoid heap fragmentation. Clearly this means we can't change the alignment if // we're going to use physical engines like some of the video engines or the display controller. Conceptually any // hardware that uses virtual addresses will never care about the physical address so we can make its alignment as // low as we want. Note that the PhysicalEnginesAvailable check is total overkill and effectively forces large // alignments for all allocations if someone creates a physical queue, however we have no other choice because // we don't know if this allocation will be used on a physical engine until we see the patch list at submit time. // // However when non-PAL code opens a shared resource it may use the physical alignment as the virtual alignment // which means that we need to tie the two alignments together to avoid corruption. In theory we can fix this issue // by modifying the KMD and UMDs but that's a big can of worms so let's just keep the larger alignment for now. if ((IsSvmAlloc() == false) && (IsShareable() == false) && (IsFlippable() == false) && (IsXdmaBuffer() == false) && (IsInterprocess() == false) && (IsBusAddressable() == false) && (IsTurboSyncSurface() == false) && (m_pDevice->PhysicalEnginesAvailable() == false)) { const GpuMemoryProperties& memProps = m_pDevice->MemoryProperties(); // Runtime will keep the same alignment between physical alignment and virtual alignment by default. // If this function returns a smaller alignment, we have to use ReserveGpuVirtualAddress to reserve // the VA which aligns to customer required alignment. if (memProps.flags.virtualRemappingSupport == 1) { // Default to clamping the physical address to system page alignment. gpusize clamp = memProps.realMemAllocGranularity; if (IsNonLocalOnly() == false) { // If the allocation supports local heaps and is suitably large, increase the clamp to the large // page size or big page size (typically 256KiB or 2MiB) or fragment size (typically 64KiB) as // appropriate to allow hardware-specific big page features when the allocation resides in local. // If the allocation is small, stick with the system page alignment to avoid fragmentation. const gpusize fragmentSize = memProps.fragmentSize; // If client allows it we can try to do alignments for LargePage, BigPage or Iterate256 optimization. #if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 584 if (m_desc.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForSizeAlignmentInBytes) { #else if (m_desc.size >= m_pDevice->GetPublicSettings()->largePageMinSizeForAlignmentInBytes) { #endif // LargePage alignment. if (memProps.largePageSupport.sizeAlignmentNeeded) { clamp = Max(clamp, memProps.largePageSupport.largePageSizeInBytes); } // BigPage alignment. if ((memProps.bigPageMinAlignment > 0) && (m_desc.size >= memProps.bigPageMinAlignment)) { clamp = Max(clamp, memProps.bigPageMinAlignment); if ((memProps.bigPageLargeAlignment > 0) && (m_desc.size >= memProps.bigPageLargeAlignment)) { clamp = Max(clamp, memProps.bigPageLargeAlignment); } } // Iterate256 alignment. if ((m_pImage != nullptr) && m_pDevice->GetGfxDevice()->SupportsIterate256() && (m_pImage->GetGfxImage()->IsIterate256Meaningful( #if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 642 (m_pImage->SubresourceInfo(m_pImage->GetBaseSubResource())))) && #else (m_pImage->SubresourceInfo(0)))) && #endif (m_desc.size >= memProps.iterate256MinAlignment)) { clamp = Max(clamp, memProps.iterate256MinAlignment); if ((memProps.iterate256LargeAlignment > 0) && (m_desc.size >= memProps.iterate256LargeAlignment)) { clamp = Max(clamp, memProps.iterate256LargeAlignment); } } } if (m_desc.size >= fragmentSize) { clamp = Max(clamp, fragmentSize); } } alignment = Min(alignment, clamp); } } return alignment; } } // Pal
42.911721
120
0.596854
[ "object" ]
0eb6d14e56c58101042e7142dd77b94873f7a818
7,922
cpp
C++
Simbody/tests/adhoc/JunkMain2.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
1,916
2015-01-01T09:35:21.000Z
2022-03-30T11:38:43.000Z
Simbody/tests/adhoc/JunkMain2.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
389
2015-01-01T01:13:51.000Z
2022-03-16T15:30:58.000Z
Simbody/tests/adhoc/JunkMain2.cpp
e-schumann/simbody
4d8842270d5c400ef64cfd5723e0e0399161e51f
[ "Apache-2.0" ]
486
2015-01-02T10:25:49.000Z
2022-03-16T15:31:40.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm) Example: Cable Path * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2012 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * 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. * * -------------------------------------------------------------------------- */ /* Simbody ExampleCablePath This example shows how to use a CableTrackerSubsystem to follow the motion of a cable that connects two bodies and passes around obstacles. We'll then create a force element that generates spring forces that result from the stretching and stretching rate of the cable. */ #include "Simbody.h" #include <cassert> #include <iostream> using std::cout; using std::endl; using namespace SimTK; // This gets called periodically to dump out interesting things about // the cables and the system as a whole. It also saves states so that we // can play back at the end. static Array_<State> saveStates; class ShowStuff : public PeriodicEventReporter { public: ShowStuff(const MultibodySystem& mbs, const CableSpring& cable1, Real interval) : PeriodicEventReporter(interval), mbs(mbs), cable1(cable1) {} static void showHeading(std::ostream& o) { printf("%8s %10s %10s %10s %10s %10s %10s %10s %10s %12s\n", "time", "length", "rate", "integ-rate", "unitpow", "tension", "disswork", "KE", "PE", "KE+PE-W"); } /** This is the implementation of the EventReporter virtual. **/ void handleEvent(const State& state) const override { const CablePath& path1 = cable1.getCablePath(); printf("%8g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %12.6g CPU=%g\n", state.getTime(), path1.getCableLength(state), path1.getCableLengthDot(state), path1.getIntegratedCableLengthDot(state), path1.calcCablePower(state, 1), // unit power cable1.getTension(state), cable1.getDissipatedEnergy(state), mbs.calcKineticEnergy(state), mbs.calcPotentialEnergy(state), mbs.calcEnergy(state) + cable1.getDissipatedEnergy(state), cpuTime()); saveStates.push_back(state); } private: const MultibodySystem& mbs; CableSpring cable1; }; int main() { try { // Create the system. MultibodySystem system; SimbodyMatterSubsystem matter(system); CableTrackerSubsystem cables(system); GeneralForceSubsystem forces(system); system.setUseUniformBackground(true); // no ground plane in display Force::UniformGravity gravity(forces, matter, Vec3(0, -9.8, 0)); //Force::GlobalDamper(forces, matter, 5); Body::Rigid someBody(MassProperties(1.0, Vec3(0), Inertia(1))); const Real Rad = 1.5; someBody.addDecoration(Transform(), DecorativeSphere(Rad).setOpacity(.75).setResolution(4)); Body::Rigid biggerBody(MassProperties(1.0, Vec3(0), Inertia(1))); const Real BiggerRad = .5; biggerBody.addDecoration(Transform(), DecorativeSphere(BiggerRad).setOpacity(.75).setResolution(4)); const Vec3 radii(2,1.5,1.7); Body::Rigid ellipsoidBody(MassProperties(1.0, Vec3(0), UnitInertia::ellipsoid(radii))); //ellipsoidBody.addDecoration(Transform(), // DecorativeEllipsoid(radii).setOpacity(.9).setResolution(4) // .setColor(Orange)); const Real CylRad = .25, HalfLen = .5; Body::Rigid cylinderBody(MassProperties(1.0, Vec3(0), 1.*UnitInertia::cylinderAlongX(Rad,HalfLen))); cylinderBody.addDecoration(Rotation(-Pi/2,ZAxis), DecorativeCylinder(CylRad,HalfLen).setOpacity(.75) .setResolution(4).setColor(Orange)); Body::Rigid fancyBody = biggerBody; // NOT USING ELLIPSOID MobilizedBody Ground = matter.Ground(); MobilizedBody::Free body1(Ground, Transform(Vec3(0)), ellipsoidBody, Transform(Vec3(0))); CablePath path1(cables, Ground, Vec3(-5,0,-.5), Ground, Vec3(5,0,-.5)); CablePath path2(cables, Ground, Vec3(-5,0,.5), Ground, Vec3(5,0,.5)); CableSpring cable1(forces, path1, 15000., 10, 0.1); CableSpring cable2(forces, path2, 15000., 10, 0.1); CableObstacle::Surface theBall1(path1, body1, Vec3(0), ContactGeometry::Ellipsoid(radii)); //ContactGeometry::Sphere(Rad)); theBall1.setContactPointHints(Vec3(-.5,-1.5,-.5),Vec3(.5,-1.5,-.5)); CableObstacle::Surface theBall2(path2, body1, Vec3(0), ContactGeometry::Ellipsoid(radii)); //ContactGeometry::Sphere(Rad)); theBall2.setContactPointHints(Vec3(-.5,-1.5,.5),Vec3(.5,-1.5,.5)); Visualizer viz(system); viz.setShowFrameNumber(true); system.addEventReporter(new Visualizer::Reporter(viz, 0.1*1./30)); system.addEventReporter(new ShowStuff(system, cable1, 0.1*0.1)); // Initialize the system and state. system.realizeTopology(); State state = system.getDefaultState(); body1.setQToFitTranslation(state, Vec3(0,.9,0)); body1.setUToFitAngularVelocity(state, 0*.25*Vec3(1,4,1)); system.realize(state, Stage::Position); viz.report(state); cout << "path1 init length=" << path1.getCableLength(state) << endl; cout << "Hit ENTER ..."; getchar(); path1.setIntegratedCableLengthDot(state, path1.getCableLength(state)); // Simulate it. saveStates.clear(); saveStates.reserve(2000); RungeKuttaMersonIntegrator integ(system); //CPodesIntegrator integ(system); integ.setAccuracy(1e-3); TimeStepper ts(system, integ); ts.initialize(state); ShowStuff::showHeading(cout); const Real finalTime = 5; const double startTime = realTime(), startCPU = cpuTime(); ts.stepTo(finalTime); cout << "DONE with " << finalTime << "s simulated in " << realTime()-startTime << "s elapsed, " << cpuTime()-startCPU << "s CPU.\n"; while (true) { cout << "Hit ENTER FOR REPLAY, Q to quit ..."; const char ch = getchar(); if (ch=='q' || ch=='Q') break; for (unsigned i=0; i < saveStates.size(); ++i) viz.report(saveStates[i]); } } catch (const std::exception& e) { cout << "EXCEPTION: " << e.what() << "\n"; } }
41.260417
93
0.580914
[ "transform" ]
0ebb644548b468626c41ddb2a0b63c40ca6c86a5
4,776
cc
C++
content/renderer/media/webrtc/webrtc_set_remote_description_observer.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/renderer/media/webrtc/webrtc_set_remote_description_observer.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/renderer/media/webrtc/webrtc_set_remote_description_observer.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/webrtc/webrtc_set_remote_description_observer.h" #include "base/logging.h" namespace content { WebRtcReceiverState::WebRtcReceiverState( scoped_refptr<webrtc::RtpReceiverInterface> receiver, std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref, std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>> stream_refs) : receiver(std::move(receiver)), track_ref(std::move(track_ref)), stream_refs(std::move(stream_refs)) {} WebRtcReceiverState::WebRtcReceiverState(WebRtcReceiverState&& other) = default; WebRtcReceiverState& WebRtcReceiverState::operator=( WebRtcReceiverState&& other) = default; WebRtcReceiverState::~WebRtcReceiverState() {} WebRtcSetRemoteDescriptionObserver::States::States() {} WebRtcSetRemoteDescriptionObserver::States::States(States&& other) : receiver_states(std::move(other.receiver_states)) {} WebRtcSetRemoteDescriptionObserver::States::~States() {} WebRtcSetRemoteDescriptionObserver::States& WebRtcSetRemoteDescriptionObserver::States::operator=(States&& other) { receiver_states = std::move(other.receiver_states); return *this; } void WebRtcSetRemoteDescriptionObserver::States::CheckInvariants() const { // Invariants: // - All receiver states have a stream ref // - All receiver states refer to streams that are non-null. for (auto& receiver_state : receiver_states) { for (auto& stream_ref : receiver_state.stream_refs) { CHECK(stream_ref); CHECK(!stream_ref->adapter().web_stream().IsNull()); } } } WebRtcSetRemoteDescriptionObserver::WebRtcSetRemoteDescriptionObserver() {} WebRtcSetRemoteDescriptionObserver::~WebRtcSetRemoteDescriptionObserver() {} scoped_refptr<WebRtcSetRemoteDescriptionObserverHandler> WebRtcSetRemoteDescriptionObserverHandler::Create( scoped_refptr<base::SingleThreadTaskRunner> main_thread, scoped_refptr<webrtc::PeerConnectionInterface> pc, scoped_refptr<WebRtcMediaStreamAdapterMap> stream_adapter_map, scoped_refptr<WebRtcSetRemoteDescriptionObserver> observer) { return new rtc::RefCountedObject<WebRtcSetRemoteDescriptionObserverHandler>( std::move(main_thread), std::move(pc), std::move(stream_adapter_map), std::move(observer)); } WebRtcSetRemoteDescriptionObserverHandler:: WebRtcSetRemoteDescriptionObserverHandler( scoped_refptr<base::SingleThreadTaskRunner> main_thread, scoped_refptr<webrtc::PeerConnectionInterface> pc, scoped_refptr<WebRtcMediaStreamAdapterMap> stream_adapter_map, scoped_refptr<WebRtcSetRemoteDescriptionObserver> observer) : main_thread_(std::move(main_thread)), pc_(std::move(pc)), stream_adapter_map_(std::move(stream_adapter_map)), observer_(std::move(observer)) {} WebRtcSetRemoteDescriptionObserverHandler:: ~WebRtcSetRemoteDescriptionObserverHandler() {} void WebRtcSetRemoteDescriptionObserverHandler::OnSetRemoteDescriptionComplete( webrtc::RTCError error) { CHECK(!main_thread_->BelongsToCurrentThread()); webrtc::RTCErrorOr<WebRtcSetRemoteDescriptionObserver::States> states_or_error; if (error.ok()) { WebRtcSetRemoteDescriptionObserver::States states; for (const auto& webrtc_receiver : pc_->GetReceivers()) { std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef> track_ref = track_adapter_map()->GetOrCreateRemoteTrackAdapter( webrtc_receiver->track().get()); std::vector<std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef>> stream_refs; for (const auto& stream : webrtc_receiver->streams()) { stream_refs.push_back( stream_adapter_map_->GetOrCreateRemoteStreamAdapter(stream.get())); } states.receiver_states.push_back(WebRtcReceiverState( webrtc_receiver.get(), std::move(track_ref), std::move(stream_refs))); } states_or_error = std::move(states); } else { states_or_error = std::move(error); } main_thread_->PostTask( FROM_HERE, base::BindOnce(&WebRtcSetRemoteDescriptionObserverHandler:: OnSetRemoteDescriptionCompleteOnMainThread, this, std::move(states_or_error))); } void WebRtcSetRemoteDescriptionObserverHandler:: OnSetRemoteDescriptionCompleteOnMainThread( webrtc::RTCErrorOr<WebRtcSetRemoteDescriptionObserver::States> states_or_error) { CHECK(main_thread_->BelongsToCurrentThread()); observer_->OnSetRemoteDescriptionComplete(std::move(states_or_error)); } } // namespace content
39.471074
81
0.754397
[ "vector" ]
0ebc7406b147a0f2aff2411e707fc0f7d8aaaec7
3,719
cpp
C++
SRCS/Core.cpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
1
2021-07-12T21:59:28.000Z
2021-07-12T21:59:28.000Z
SRCS/Core.cpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
null
null
null
SRCS/Core.cpp
Dreinale/Bomberman_project
ed98d44f54906b1e3f7941b58d8e1493711f355b
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** Core ** File description: ** Core */ #include <iostream> #include "Core.hpp" Core::Core() { InitAudioDevice(); _volume = 0.4; _music = new Zic(&_volume, 0, "ASSETS/SOUND/music.mp3"); _music->play_music(); _running = true; _i_graphic = new Graphic(); _occupancy = 0.8; _cur_controller = "MENU"; auto game = new Game(&_volume, &_occupancy, _i_graphic->getModels()); _i_entities_controllers["GAME"] = game; _i_entities_controllers["MENU"] = new Menu(); _i_entities_controllers["PAUSE"] = new Pause(); _i_entities_controllers["INPUT"] = new Input(game->getPlayers(), _i_graphic->getModels()); _i_entities_controllers["SETTINGS"] = new Settings(&_volume, &_occupancy, _i_graphic); _i_entities_controllers["END"] = new End(&_volume, game->getPlayers()); } void Core::handle_global_event(Event event) { switch (event) { case Event::CLOSE_WINDOW: _running = false; break; case Event::GAME: dynamic_cast<Game *>(_i_entities_controllers.at("GAME"))->bot_generation(); dynamic_cast<Game *>(_i_entities_controllers.at("GAME"))->map_generation(); _cur_controller = "GAME"; break; case Event::KEYBIND: _cur_controller = "INPUT"; break; case Event::MENU: _music->play_music(); if (_cur_controller == "PAUSE" || _cur_controller == "END") { // reset controllers delete dynamic_cast<Game *>(_i_entities_controllers.at("GAME")); _i_entities_controllers["GAME"] = new Game(&_volume, &_occupancy, _i_graphic->getModels()); delete dynamic_cast<Input *>(_i_entities_controllers.at("INPUT")); _i_entities_controllers["INPUT"] = new Input(dynamic_cast<Game *>(_i_entities_controllers.at("GAME"))->getPlayers(), _i_graphic->getModels()); delete dynamic_cast<End *>(_i_entities_controllers.at("END")); _i_entities_controllers["END"] = new End(&_volume, dynamic_cast<Game *>(_i_entities_controllers.at("GAME"))->getPlayers()); } _cur_controller = "MENU"; break; case Event::PAUSE_EVENT: if (_cur_controller == "GAME") _cur_controller = "PAUSE"; break; case Event::SAVE: Game::Save::save(dynamic_cast<Game *>(_i_entities_controllers["GAME"])); break; case Event::SETTINGS: _cur_controller = "SETTINGS"; break; case Event::END_GAME: _music->stop(); _cur_controller = "END"; break; case Event::LOAD_SAVE: if (!Game::Save::SaveExists()) return; Game::Save::loadSave(dynamic_cast<Game *>(_i_entities_controllers["GAME"]), _i_graphic->getModels()); _cur_controller = "INPUT"; break; } } int Core::mainLoop() { Info *info; Event event; while (_running) { info = _i_graphic->getInfo(); handle_global_event(info->getEvent()); event = _i_entities_controllers[_cur_controller]->update(info); handle_global_event(event); std::vector<IEntities *> entities = _i_entities_controllers[_cur_controller]->getEntities(); _i_graphic->drawEntities(entities); _music->update(); } return (0); } Core::~Core() { if (IsWindowFullscreen()) _i_graphic->toggleFullscreen(); CloseAudioDevice(); for (auto ite = _i_entities_controllers.begin(); ite != _i_entities_controllers.end(); ite++) delete ite.operator*().second; delete _i_graphic; delete _music; }
33.205357
158
0.605808
[ "vector" ]
b1beb7585cec553817ce463ed95077e82490b6af
12,050
cpp
C++
src/kernel/cpuid.cpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
src/kernel/cpuid.cpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
src/kernel/cpuid.cpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <kernel/cpuid.hpp> #include <cstring> #include <cstdint> #include <array> namespace { using namespace CPUID; enum class Register { EAX, EBX, ECX, EDX }; struct FeatureInfo { // Input when calling cpuid (eax and ecx) const uint32_t func; const uint32_t subfunc; // Register and bit that holds the result const Register register_; const uint32_t bitmask; }; constexpr auto get_feature_info(Feature f) { // Use switch-case so that the we get compiler warnings if // we forget to add information for features that we have declared switch (f) { // ---------------------------------------------------------------------- // EAX=1: Processor Info and Feature Bits // ---------------------------------------------------------------------- case Feature::SSE3: return FeatureInfo { 1, 0, Register::ECX, 1u << 0 }; // Streaming SIMD Extensions 3 case Feature::PCLMULQDQ: return FeatureInfo { 1, 0, Register::ECX, 2u << 0 }; // PCLMULQDQ Instruction case Feature::DTES64: return FeatureInfo { 1, 0, Register::ECX, 1u << 2 }; // 64-Bit Debug Store Area case Feature::MONITOR: return FeatureInfo { 1, 0, Register::ECX, 1u << 3 }; // MONITOR/MWAIT case Feature::DS_CPL: return FeatureInfo { 1, 0, Register::ECX, 1u << 4 }; // CPL Qualified Debug Store case Feature::VMX: return FeatureInfo { 1, 0, Register::ECX, 1u << 5 }; // Virtual Machine Extensions case Feature::SMX: return FeatureInfo { 1, 0, Register::ECX, 1u << 6 }; // Safer Mode Extensions (Intel TXT) case Feature::EST: return FeatureInfo { 1, 0, Register::ECX, 1u << 7 }; // Enhanced SpeedStep Technology case Feature::TM2: return FeatureInfo { 1, 0, Register::ECX, 1u << 8 }; // Thermal Monitor 2 case Feature::SSSE3: return FeatureInfo { 1, 0, Register::ECX, 1u << 9 }; // Supplemental Streaming SIMD Extensions 3 case Feature::CNXT_ID: return FeatureInfo { 1, 0, Register::ECX, 1u << 10 }; // L1 Context ID case Feature::FMA: return FeatureInfo { 1, 0, Register::ECX, 1u << 12 }; // Fused Multiply Add case Feature::CX16: return FeatureInfo { 1, 0, Register::ECX, 1u << 13 }; // CMPXCHG16B Instruction case Feature::XTPR: return FeatureInfo { 1, 0, Register::ECX, 1u << 14 }; // xTPR Update Control case Feature::PDCM: return FeatureInfo { 1, 0, Register::ECX, 1u << 15 }; // Perf/Debug Capability MSR case Feature::PCID: return FeatureInfo { 1, 0, Register::ECX, 1u << 17 }; // Process-context Identifiers case Feature::DCA: return FeatureInfo { 1, 0, Register::ECX, 1u << 18 }; // Direct Cache Access case Feature::SSE4_1: return FeatureInfo { 1, 0, Register::ECX, 1u << 19 }; // Streaming SIMD Extensions 4.1 case Feature::SSE4_2: return FeatureInfo { 1, 0, Register::ECX, 1u << 20 }; // Streaming SIMD Extensions 4.2 case Feature::X2APIC: return FeatureInfo { 1, 0, Register::ECX, 1u << 21 }; // Extended xAPIC Support case Feature::MOVBE: return FeatureInfo { 1, 0, Register::ECX, 1u << 22 }; // MOVBE Instruction case Feature::POPCNT: return FeatureInfo { 1, 0, Register::ECX, 1u << 23 }; // POPCNT Instruction case Feature::TSC_DEADLINE: return FeatureInfo { 1, 0, Register::ECX, 1u << 24 }; // Local APIC supports TSC Deadline case Feature::AES: return FeatureInfo { 1, 0, Register::ECX, 1u << 25 }; // AESNI Instruction case Feature::XSAVE: return FeatureInfo { 1, 0, Register::ECX, 1u << 26 }; // XSAVE/XSTOR States case Feature::OSXSAVE: return FeatureInfo { 1, 0, Register::ECX, 1u << 27 }; // OS Enabled Extended State Management case Feature::AVX: return FeatureInfo { 1, 0, Register::ECX, 1u << 28 }; // AVX Instructions case Feature::F16C: return FeatureInfo { 1, 0, Register::ECX, 1u << 29 }; // 16-bit Floating Point Instructions case Feature::RDRAND: return FeatureInfo { 1, 0, Register::ECX, 1u << 30 }; // RDRAND Instruction case Feature::FPU: return FeatureInfo { 1, 0, Register::EDX, 1u << 0 }; // Floating-Point Unit On-Chip case Feature::VME: return FeatureInfo { 1, 0, Register::EDX, 1u << 1 }; // Virtual 8086 Mode Extensions case Feature::DE: return FeatureInfo { 1, 0, Register::EDX, 1u << 2 }; // Debugging Extensions case Feature::PSE: return FeatureInfo { 1, 0, Register::EDX, 1u << 3 }; // Page Size Extension case Feature::TSC: return FeatureInfo { 1, 0, Register::EDX, 1u << 4 }; // Time Stamp Counter case Feature::MSR: return FeatureInfo { 1, 0, Register::EDX, 1u << 5 }; // Model Specific Registers case Feature::PAE: return FeatureInfo { 1, 0, Register::EDX, 1u << 6 }; // Physical Address Extension case Feature::MCE: return FeatureInfo { 1, 0, Register::EDX, 1u << 7 }; // Machine-Check Exception case Feature::CX8: return FeatureInfo { 1, 0, Register::EDX, 1u << 8 }; // CMPXCHG8 Instruction case Feature::APIC: return FeatureInfo { 1, 0, Register::EDX, 1u << 9 }; // APIC On-Chip case Feature::SEP: return FeatureInfo { 1, 0, Register::EDX, 1u << 11 }; // SYSENTER/SYSEXIT instructions case Feature::MTRR: return FeatureInfo { 1, 0, Register::EDX, 1u << 12 }; // Memory Type Range Registers case Feature::PGE: return FeatureInfo { 1, 0, Register::EDX, 1u << 13 }; // Page Global Bit case Feature::MCA: return FeatureInfo { 1, 0, Register::EDX, 1u << 14 }; // Machine-Check Architecture case Feature::CMOV: return FeatureInfo { 1, 0, Register::EDX, 1u << 15 }; // Conditional Move Instruction case Feature::PAT: return FeatureInfo { 1, 0, Register::EDX, 1u << 16 }; // Page Attribute Table case Feature::PSE_36: return FeatureInfo { 1, 0, Register::EDX, 1u << 17 }; // 36-bit Page Size Extension case Feature::PSN: return FeatureInfo { 1, 0, Register::EDX, 1u << 18 }; // Processor Serial Number case Feature::CLFLUSH: return FeatureInfo { 1, 0, Register::EDX, 1u << 19 }; // CLFLUSH Instruction case Feature::DS: return FeatureInfo { 1, 0, Register::EDX, 1u << 21 }; // Debug Store case Feature::ACPI: return FeatureInfo { 1, 0, Register::EDX, 1u << 22 }; // Thermal Monitor and Software Clock Facilities case Feature::MMX: return FeatureInfo { 1, 0, Register::EDX, 1u << 23 }; // MMX Technology case Feature::FXSR: return FeatureInfo { 1, 0, Register::EDX, 1u << 24 }; // FXSAVE and FXSTOR Instructions case Feature::SSE: return FeatureInfo { 1, 0, Register::EDX, 1u << 25 }; // Streaming SIMD Extensions case Feature::SSE2: return FeatureInfo { 1, 0, Register::EDX, 1u << 26 }; // Streaming SIMD Extensions 2 case Feature::SS: return FeatureInfo { 1, 0, Register::EDX, 1u << 27 }; // Self Snoop case Feature::HTT: return FeatureInfo { 1, 0, Register::EDX, 1u << 28 }; // Multi-Threading case Feature::TM: return FeatureInfo { 1, 0, Register::EDX, 1u << 29 }; // Thermal Monitor case Feature::PBE: return FeatureInfo { 1, 0, Register::EDX, 1u << 31 }; // Pending Break Enable // ---------------------------------------------------------------------- // EAX=80000001h: Extended Processor Info and Feature Bits (not complete) // ---------------------------------------------------------------------- case Feature::SYSCALL: return FeatureInfo { 0x80000001, 0, Register::EDX, 1u << 11 }; // SYSCALL/SYSRET case Feature::NX: return FeatureInfo { 0x80000001, 0, Register::EDX, 1u << 20 }; // Execute Disable Bit case Feature::PDPE1GB: return FeatureInfo { 0x80000001, 0, Register::EDX, 1u << 26 }; // 1 GB Pages case Feature::RDTSCP: return FeatureInfo { 0x80000001, 0, Register::EDX, 1u << 27 }; // RDTSCP and IA32_TSC_AUX case Feature::LM: return FeatureInfo { 0x80000001, 0, Register::EDX, 1u << 29 }; // 64-bit Architecture case Feature::SVM: return FeatureInfo { 0x80000001, 0, Register::ECX, 1u << 2 }; // Secure Virtual Machine (AMD-V) case Feature::SSE4A: return FeatureInfo { 0x80000001, 0, Register::ECX, 1u << 6 }; // SSE4a } } // Holds results of call to cpuid struct cpuid_t { uint32_t EAX; uint32_t EBX; uint32_t ECX; uint32_t EDX; }; //< cpuid_t cpuid_t cpuid(uint32_t func, uint32_t subfunc) { // Cache up to 4 results struct cpuid_cache_t { // cpuid input uint32_t func; uint32_t subfunc; // cpuid output cpuid_t result; // valid or not in cache bool valid; }; static std::array<cpuid_cache_t, 4> cache = {}; // Check cache for cpuid result for (const auto& cached : cache) { if (cached.valid && cached.func == func && cached.subfunc == subfunc) { return cached.result; } } // Call cpuid // EBX/RBX needs to be preserved depending on the memory model and use of PIC cpuid_t result; asm volatile ("cpuid" : "=a"(result.EAX), "=b"(result.EBX), "=c"(result.ECX), "=d"(result.EDX) : "a"(func), "c"(subfunc)); // Try to find an empty spot in the cache for (auto& cached : cache) { if (!cached.valid) { cached.func = func; cached.subfunc = subfunc; cached.result = result; cached.valid = true; break; } } return result; } } //< namespace bool CPUID::is_amd_cpu() { auto result = cpuid(0, 0); return memcmp(reinterpret_cast<char*>(&result.EBX), "htuA", 4) == 0 && memcmp(reinterpret_cast<char*>(&result.EDX), "itne", 4) == 0 && memcmp(reinterpret_cast<char*>(&result.ECX), "DMAc", 4) == 0; } bool CPUID::is_intel_cpu() { auto result = cpuid(0, 0); return memcmp(reinterpret_cast<char*>(&result.EBX), "Genu", 4) == 0 && memcmp(reinterpret_cast<char*>(&result.EDX), "ineI", 4) == 0 && memcmp(reinterpret_cast<char*>(&result.ECX), "ntel", 4) == 0; } bool CPUID::has_feature(Feature f) { const auto feature_info = get_feature_info(f); const auto cpuid_result = cpuid(feature_info.func, feature_info.subfunc); switch (feature_info.register_) { case Register::EAX: return (cpuid_result.EAX & feature_info.bitmask) != 0; case Register::EBX: return (cpuid_result.EBX & feature_info.bitmask) != 0; case Register::ECX: return (cpuid_result.ECX & feature_info.bitmask) != 0; case Register::EDX: return (cpuid_result.EDX & feature_info.bitmask) != 0; } } #define KVM_CPUID_SIGNATURE 0x40000000 unsigned CPUID::kvm_function() { auto res = cpuid(KVM_CPUID_SIGNATURE, 0); /// "KVMKVMKVM" if (res.EBX == 0x4b4d564b && res.ECX == 0x564b4d56 && res.EDX == 0x4d) return res.EAX; return 0; } bool CPUID::kvm_feature(unsigned id) { unsigned func = kvm_function(); if (func == 0) return false; auto res = cpuid(func, 0); return (res.EAX & (1 << id)) != 0; }
51.495726
136
0.603734
[ "model" ]
b1c1effaee4e0e00caa695cf36f8af99413a4899
2,959
cpp
C++
src/RawComponentWidget.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/RawComponentWidget.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/RawComponentWidget.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
#include "RawComponentWidget.hpp" #include "CustomDataRoles.hpp" #include "../ui/ui_raw_component.h" namespace sempr { namespace gui { RawComponentWidget::RawComponentWidget(QWidget* parent) : UsefulWidget(parent), form_(new Ui::RawComponent) { form_->setupUi(this); connect(form_->btnSave, &QPushButton::clicked, this, &RawComponentWidget::save); } RawComponentWidget::~RawComponentWidget() { delete form_; } void RawComponentWidget::save() { if (!currentIndex_.isValid()) return; if (!model_) return; bool ok = model_->setData(currentIndex_, form_->rawComponentEdit->toPlainText(), Role::ComponentJsonRole); // TODO: what to do when the json is not ok? // just ignore for now, might be that the component type is just not known // ... could add an info label, change the save buttons colour, whatever. // Somehow signal that things... worked, or did not. // Note: We don't tell the model to send the data to the sempr core anymore. // Instead, we keep the change in a kind of "staging area", and will send it // when explicitely called for. This allows for a clearer differentiation // between the models data, and the data in the sempr core, gives us a way // to reset things, etc. } void RawComponentWidget::updateWidget() { if (currentIndex_.isValid()) { auto varJson = model_->data(currentIndex_, Role::ComponentJsonRole); auto varMut = model_->data(currentIndex_, Role::ComponentMutableRole); if (varJson.canConvert<QString>() && varMut.canConvert<bool>()) { bool mut = varMut.value<bool>(); QString json = varJson.value<QString>(); form_->rawComponentEdit->setPlainText(json); // enable text entry and save button only if the component is // mutable! // //this->setEnabled(entry.mutable_); // disabling the edit is a bit too much: Cannot read it properly // anymore due to the grey background, and no selection for // copy & paste is possible anymore. Instead, disable the button, // and set the edit to read only. this->setEnabled(true); form_->btnSave->setEnabled(mut); form_->rawComponentEdit->setReadOnly(!mut); // signal this this widget is useful right now setUseful(true); } else { this->setEnabled(false); // couldn't get a model entry, so clear the edit form_->rawComponentEdit->setPlainText(""); // signal that his widget isn't useful right now setUseful(false); } } else { // nothing selected. form_->rawComponentEdit->setPlainText(""); this->setEnabled(false); // signal that this widget isn't useful right now setUseful(false); } } }}
31.817204
84
0.62048
[ "model" ]
b1c5b7348b51ce06671bbbddcd9eaf60ad44f26b
20,063
cpp
C++
demos/demo.cpp
NikolasGialitsis/NGramGraphParallel
26427e7ff39ba591a8c7eedd0ace458f1821a876
[ "Apache-2.0" ]
1
2021-09-17T08:51:55.000Z
2021-09-17T08:51:55.000Z
demos/demo.cpp
NikolasGialitsis/NGramGraphParallel
26427e7ff39ba591a8c7eedd0ace458f1821a876
[ "Apache-2.0" ]
1
2021-05-24T10:36:50.000Z
2021-05-24T10:36:50.000Z
demos/demo.cpp
NikolasGialitsis/NGramGraphParallel
26427e7ff39ba591a8c7eedd0ace458f1821a876
[ "Apache-2.0" ]
1
2021-05-09T16:00:52.000Z
2021-05-09T16:00:52.000Z
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <tuple> #include <openclParams.hpp> #include "InputParser.hpp" #include "Atom.hpp" #include "NGramGraph.hpp" #include "DocumentClass.hpp" #include "OclUpdatableClass.hpp" #include "StringSplitter.hpp" #include "StringPayload.hpp" #include "GraphComparator.hpp" #include "GraphSimilarity.hpp" #include "ProximityApproach.hpp" #define TABLE_SIZE_DEFAULT_VALUE 5000000 #define SERIAL_CLASS_GRAPHS_RELATIVE_DIR "class_graphs_serial/" #define PARALLEL_CLASS_GRAPHS_RELATIVE_DIR "class_graphs_parallel/" #define TOPICS_RELATIVE_DIR "topics" #define OPENCL_KERNELS_RELATIVE_DIR "opencl_kernels/" /* * Returns the first platform found. */ Platform getPlatform() { std::vector<Platform> all_platforms; Platform::get(&all_platforms); if (all_platforms.size()==0) { cout << "No platforms found. Check OpenCL installation!\n"; exit(1); } return all_platforms[0]; } /* * Returns the deviced specified by the index i on platform. * If display is true, then all of the platforms are listed. */ Device getDevice(Platform platform, cl_device_type type, int i, bool display=false) { std::vector<Device> all_gpus; platform.getDevices(type, &all_gpus); if (all_gpus.size() == 0) { cout << "No devices found. Check OpenCL installation!\n"; exit(1); } if (display) { for (unsigned int j=0; j<all_gpus.size(); j++) printf("Device %d: %s\n", j, all_gpus[j].getInfo<CL_DEVICE_NAME>().c_str()); } return all_gpus[i]; } double compute_elapsed_time(struct timespec *start, struct timespec *finish) { double result = finish->tv_sec - start->tv_sec; result += (finish->tv_nsec - start->tv_nsec) / 1000000000.0; return result; } /* * Returns the class graph of the serial method for a specific topic and the graph construction time if requested. * If the class graph is cached and time measurement is not requested, the edges of the graph are read from a file. * Otherwise, the graph is computed from scratch. * \param topics_dir The directory where the available topics are stored. * \param graphs_dir The directory where the cached class graphs of the serial method are stored. * \param topic The topic for which the caller wants the class graph. * \param count_time Controls whether to measure construction time or not. * \return A pair consisting of the class graph object and the time taken to construct it. */ std::pair<DocumentClass *, double> getSerialClass(std::string topics_dir, std::string graphs_dir, std::string topic, bool count_time) { struct timespec start, finish; double elapsed_time = -1.0; DocumentClass *class_graph = new DocumentClass(); if (graphs_dir.back() != '/') { graphs_dir += "/"; } if (topics_dir.back() != '/') { topics_dir += "/"; } bool cached = FileUtils::fileExists(graphs_dir + topic + ".cg"); // If the caller requested time measurement or the edges of the graph are not cached to a file, create the graph from scratch. if (count_time || !cached) { clock_gettime(CLOCK_MONOTONIC, &start); class_graph->build(topics_dir + topic + "/"); clock_gettime(CLOCK_MONOTONIC, &finish); elapsed_time = compute_elapsed_time(&start, &finish); // In case the class graph was not cached, cache it now so next executions of the program will find it ready. if (!cached) { class_graph->cache(graphs_dir, topic + ".cg"); } } // If the caller did not ask for time measurement and the class graph is cached to a file, read it from there to save time. else { class_graph->restoreFromFile(graphs_dir + topic + ".cg"); } return {class_graph, elapsed_time}; } /* * Returns the class graph of the parallel method for a specific topic and the graph construction time if requested. * If the class graph is cached and time measurement is not requested, the edges of the graph are read from a file. * Otherwise, the graph is computed from scratch. * \param topics_dir The directory where the available topics are stored. * \param graphs_dir The directory where the cached class graphs of the parallel method are stored. * \param topic The topic for which the caller wants the class graph. * \param table_size The size of the hash table to be used. * \param count_time Controls whether to measure construction time or not. * \param c Pointer to OpenCL context. * \param q Pointer to OpenCL command queue. * \param p Pointer to OpenCL program. * \return A pair consisting of the class graph object and the time taken to construct it. */ std::pair<OclUpdatableClass *, double> getParallelClass(std::string topics_dir, std::string graphs_dir, std::string topic, unsigned int table_size, bool count_time, Context *c, CommandQueue *q, Program *p) { struct timespec start, finish; OclUpdatableClass *class_graph = new OclUpdatableClass(table_size); double elapsed_time = -1.0; if (graphs_dir.back() != '/') { graphs_dir += "/"; } if (topics_dir.back() != '/') { topics_dir += "/"; } bool cached = FileUtils::fileExists(graphs_dir + std::to_string(table_size) + "/" + topic + ".cg"); // If the caller requested time measurement or the edges of the graph are not cached to a file, create the graph from scratch. if (count_time || !cached) { clock_gettime(CLOCK_MONOTONIC, &start); class_graph->buildClass(topics_dir + topic + "/", c, q, p); clock_gettime(CLOCK_MONOTONIC, &finish); elapsed_time = compute_elapsed_time(&start, &finish); // In case the class graph was not cached, cache it now so next executions of the program will find it ready. if (!cached) { class_graph->cache(graphs_dir + std::to_string(table_size) + "/", topic + ".cg"); } } // If the caller did not ask for time measurement and the class graph is cached to a file, read it from there to save time. else { class_graph->restoreFromFile(graphs_dir + std::to_string(table_size) + "/" + topic + ".cg"); } return {class_graph, elapsed_time}; } /* * Prints a program usage message. */ void display_usage_message(std::string topics_dir, std::string serial_dir, std::string parallel_dir) { //std::cout << std::endl; std::cout << "A simple program to test the efficacy of the in parallel constructed class graphs " << "in comparison with the ones constructed serially.\n\nThe program accepts the following options/arguments:\n" << "\t -h Prints this message and exits dismissing other options.\n" << "\t -c [serial | serial-parallel] Uses only topics that have their class graphs cached to a file, so they don't\n" << "\t need to be computed during program execution. It can be applied for the serial\n" << "\t method only or for both parallel and serial methods. Default is for serial only.\n" << "\t The available cached class graphs can be seen in the topics '" << serial_dir << "' and \n" << "\t '" << parallel_dir << "' for the serial and parallel method respectively.\n" << "\t -t Reports an execution time comparison between serial and parallel methods.\n" << "\t It is *very* slow, as the class graphs of both methods, serial and parallel, are\n" << "\t computed from scratch (in order to be measured). If this option is not enabled, the graphs\n" << "\t that happen to be cached to a file are read from there.\n" << "\t -f <filename> (Mandatory) Each line of the <filename> file must contain two entries, separated\n" << "\t by a whitespace. The first entry should be the absolute filesystem path to a\n" << "\t text document and the second entry the document's topic. The program\n" << "\t will try to extract the topic of each document using both methods, serial\n" << "\t and parallel, and check if it was right.\n" << "\t The given topics must be one of those in the '" << topics_dir << "' directory.\n" << "\t You can add more topics in that directory in order to be able to include them in the\n" << "\t given topics.\n" << "\t -s <hash_table_size> The hash table size to be used in the parallel method. Default is 5000000.\n"; std::cout << std::endl; } int main(int argc, char **argv) { std::string project_dir(argv[0]); project_dir = project_dir.substr(0, project_dir.find_last_of("/")); // Removes the program name from the filepath project_dir = project_dir.substr(0, project_dir.find_last_of("/")+1); // Removes the 'demos' entry from the path std::string serial_class_graphs_dir(project_dir + SERIAL_CLASS_GRAPHS_RELATIVE_DIR); std::string parallel_class_graphs_dir(project_dir + PARALLEL_CLASS_GRAPHS_RELATIVE_DIR); std::string topics_dir(project_dir + TOPICS_RELATIVE_DIR); std::string kernels_dir(project_dir + OPENCL_KERNELS_RELATIVE_DIR); // Parse command line options and print appropriate messages if something is wrong. InputParser iParser(argc, argv); unsigned int table_size; bool help_asked = iParser.cmdOptionExists("-h"); const std::string& filename = iParser.getCmdOption("-f"); const std::string& number = iParser.getCmdOption("-s"); bool time_comparison = iParser.cmdOptionExists("-t"); bool cached_enabled = iParser.cmdOptionExists("-c"); const std::string& cached_option = iParser.getCmdOption("-c"); if (help_asked) { display_usage_message(topics_dir, serial_class_graphs_dir, parallel_class_graphs_dir); exit(0); } if (!cached_option.empty() && cached_option != "serial" && cached_option != "serial-parallel") { std::cout << "Invalid argument for the -c option. The value of the -c parameter should be either 'serial' or 'serial-parallel'.\n"; exit(1); } if (filename.empty()) { display_usage_message(topics_dir, serial_class_graphs_dir, parallel_class_graphs_dir); exit(1); } if (cached_enabled && time_comparison) { std::cout << "Options -c and -t can't be enabled at the same time.\n"; exit(1); } if (number.empty()) { table_size = TABLE_SIZE_DEFAULT_VALUE; } else { std::istringstream iss(number); iss >> table_size; } /* OpenCL initialization */ Platform platform = getPlatform(); Device gpu = getDevice(platform, CL_DEVICE_TYPE_GPU, 0); Context context({gpu}); CommandQueue queue(context, gpu); Program::Sources sources; std::vector<std::string> kernel_files; std::string kernel_code; FileUtils::read_directory(kernels_dir, kernel_files); for (auto& file : kernel_files) { std::cout << "Reading file " << file << std::endl; kernel_code = FileUtils::read_file_to_string(kernels_dir + file); sources.push_back({kernel_code.c_str(), kernel_code.length()}); } Program program(context, sources); if (program.build({gpu}) != CL_SUCCESS) { std::cout << "Error building: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(gpu) << std::endl; exit(1); } else { std::cout << "OpenCL program was built successfully.\n\n"; } /* OpenCL initialized successfully */ std::vector<std::string> topics; // Read all the available topics in the topics vector. FileUtils::read_directory(topics_dir, topics); // used_topics vector holds the topics that are going to be used among all the available topics. // Some can be excluded if, for example, the user enabled the cached option and there is no cached class graph for all the topics. std::vector<std::string> used_topics = topics; // If the cached option is enabled, reject the topics that don't have a cached class graph. if (cached_enabled) { for (auto& topic : topics) { if (cached_option == "serial-parallel") { if (!FileUtils::fileExists(serial_class_graphs_dir + topic + ".cg")) { std::cout << "Class graph of topic '" << topic << "' for the serial method is not cached." << "Topic '" << topic << "' won't be used.\n"; used_topics.erase(std::remove(used_topics.begin(), used_topics.end(), topic), used_topics.end()); } else if (!FileUtils::fileExists(parallel_class_graphs_dir + std::to_string(table_size) + "/" + topic + ".cg")) { std::cout << "Class graph of topic '" << topic << "' for the parallel method with hash table size of " << table_size << " is not cached. Topic '" << topic << "' won't be used.\n"; used_topics.erase(std::remove(used_topics.begin(), used_topics.end(), topic), used_topics.end()); } } else if (cached_option == "serial" || cached_option.empty()) { if (!FileUtils::fileExists(serial_class_graphs_dir + topic + ".cg")) { std::cout << "Class graph of topic '" << topic << "' for the serial method is not cached." << "Topic '" << topic << "' won't be used.\n"; used_topics.erase(std::remove(used_topics.begin(), used_topics.end(), topic), used_topics.end()); } } } } std::cout << std::endl; std::ifstream iFile(filename); // The input vector will store the information contained in the argument file. std::vector<std::pair<std::string, std::string>> input(0); std::string sample, topic; while (iFile >> sample >> topic) { // If the provided topic is contained in the ones we can use, add the input line to the vector. if (std::find(used_topics.begin(), used_topics.end(), topic) != used_topics.end()) { input.push_back(std::make_pair(sample, topic)); } // Else, dismiss it. else { std::cout << "Topic '" << topic << "' is not available. Document '" << sample << "' will be excluded." << std::endl; } } if (input.size() == 0) { std::cout << std::endl << "The filtered input set is empty. Exiting." << std::endl; exit(0); } // This vector will hold the NGramGraph objects of the given text documents. std::vector<NGramGraph *> sample_graphs(0); NGramGraph *sample_ngg; StringSplitter splitter; StringPayload *payload; ProximityApproach *approach = new SymmetricApproach(); // For every text document, create it's corresponding NGramGraph object and add it to the vector. for (auto& line : input) { sample = line.first; // TODO Check if sample exists payload = new StringPayload(FileUtils::read_file_to_string(sample)); sample_ngg = new NGramGraph(nullptr, &splitter, payload, 4, approach); sample_ngg->createGraph(); sample_graphs.push_back(sample_ngg); } // Holds the current max value similarity for every sample graph (for serial and parallel methods) std::vector<std::pair<double, double>> valueSimilarities(input.size(), std::make_pair(-1.0, -1.0)); // Holds the current extracted topic for every sample graph (for serial and parallel methods) std::vector<std::pair<std::string, std::string>> extractedTopics(input.size()); GraphComparator<std::string, std::string> gComp; GraphSimilarity gSim; DocumentClass *docClass_serial; OclUpdatableClass *docClass_parallel; // Outputs in case the user requested a time comparison. if (time_comparison) { std::cout << std::endl << "Topic\t\t\tSerial Time(secs)\tParallel Time(secs)\tSpeedup\t\tValue Similarity\t" << std::endl; } int sample_cnt; double tempVS, serial_elapsed_time, parallel_elapsed_time; // For every available topic, get it's class graph and compute it's value similarity with every NGramGraph object from // the sample_graphs vector. for (auto& topic : used_topics) { // Outputs if a time comparison was requested. if (time_comparison) { std::cout << topic; if (topic.length() < 8) std::cout << "\t\t\t"; else if (topic.length() < 16) std::cout << "\t\t"; else if (topic.length() < 24) std::cout << "\t"; //else hope topic.length() < 24 std::cout.flush(); } // TODO Check if file for class graph exists. If not, create it. // Get the class graph of the serial method for the current topic. std::tie(docClass_serial, serial_elapsed_time) = getSerialClass(topics_dir, serial_class_graphs_dir, topic, time_comparison); // If asked for, report time for the construction of the class graph. if (time_comparison) { std::cout << std::setprecision(1) << std::fixed << serial_elapsed_time << "\t\t\t"; std::cout.flush(); } // Get the class graph of the parallel method for the current topic. std::tie(docClass_parallel, parallel_elapsed_time) = getParallelClass(topics_dir, parallel_class_graphs_dir, topic, table_size, time_comparison, &context, &queue, &program); // If stats are requested, report time for the parralel construction of the class graph, speedup of the // parallel method and value similarity between serial and parallel class graphs of the same topic. if (time_comparison) { std::cout << std::setprecision(1) << std::fixed << parallel_elapsed_time << "\t\t\t"; // That is the speedup. std::cout << std::setprecision(2) << std::fixed << serial_elapsed_time / parallel_elapsed_time << "\t\t"; std::cout.flush(); // Compute and output value similarity here. gSim = gComp.compare(*docClass_serial, *docClass_parallel); tempVS = (gSim.getSimilarityComponents())["valueSimilarity"]; std::cout << std::setprecision(2) << std::fixed << tempVS << "\t\t\t" << std::endl; } // The serial and parallel class graphs of the current topic have been constructed. // Now compute the value similariy of both with every sample graph and hold the maximum. sample_cnt = 0; for (auto sample_graph : sample_graphs) { // Compare current sample graph with the class graph of the serial method. gSim = gComp.compare(*docClass_serial, *sample_graph); tempVS = (gSim.getSimilarityComponents())["valueSimilarity"]; // If it's bigger than current maximum, replace it and change appropriately the stored extracted topic. if (tempVS > valueSimilarities[sample_cnt].first) { valueSimilarities[sample_cnt].first = tempVS; extractedTopics[sample_cnt].first = topic; } // Repeat the same procedure as above, but with the class graph of the parallel method. gSim = gComp.compare(*docClass_parallel, *sample_graph); tempVS = (gSim.getSimilarityComponents())["valueSimilarity"]; if (tempVS > valueSimilarities[sample_cnt].second) { valueSimilarities[sample_cnt].second = tempVS; extractedTopics[sample_cnt].second = topic; } ++sample_cnt; } // We are done with the class graphs of the current topic, so destroy them to free some memory. delete docClass_serial; delete docClass_parallel; } // NGramGraph objects representing the text documents are of no use anymore, so delete them. for (auto sample_graph : sample_graphs) { delete sample_graph; } sample_graphs.clear(); if (time_comparison) std::cout << std::endl; // Report the topic extraction for both serial and parallel method, so that the user can evaluate how they agree // with each other and with the given topic also. std::cout << std::endl << "Document\t\tSerial Extraction\tOpenCL Extraction\tGiven Topic" << std::endl; sample_cnt = 0; std::string s_topic, p_topic; for (auto& line : input) { sample = line.first.substr(line.first.find_last_of("/")+1); std::cout << sample; if (sample.length() < 8) std::cout << "\t\t\t"; else if (sample.length() < 16) std::cout << "\t\t"; else std::cout << "\t"; // In this we hope sample.length() < 24. s_topic = extractedTopics[sample_cnt].first; std::cout << s_topic; if (s_topic.length() < 8) std::cout << "\t\t\t"; else if (s_topic.length() < 16) std::cout << "\t\t"; else std::cout << "\t"; // In this we hope s_topic.length() < 24. p_topic = extractedTopics[sample_cnt].second; std::cout << p_topic; if (p_topic.length() < 8) std::cout << "\t\t\t"; else if (p_topic.length() < 16) std::cout << "\t\t"; else std::cout << "\t"; // In this we hope p_topic.length() < 24. std::cout << line.second << std::endl; ++sample_cnt; } std::cout << std::endl; return 0; }
43.426407
134
0.686836
[ "object", "vector" ]
b1c7c1e088b7d83e2acdd78ac3028119045ff838
9,697
hpp
C++
include/eos/fitting/nonlinear_camera_estimation.hpp
ckLibra/FaceReconstruction
03b4e83a8287b97e320ccabb4645fc7d09dfabca
[ "Apache-2.0" ]
369
2016-07-19T17:24:44.000Z
2022-03-25T11:51:13.000Z
include/eos/fitting/nonlinear_camera_estimation.hpp
KeeganRen/dlib_eos
03b4e83a8287b97e320ccabb4645fc7d09dfabca
[ "Apache-2.0" ]
2
2018-08-13T12:50:30.000Z
2018-10-23T00:29:53.000Z
include/eos/fitting/nonlinear_camera_estimation.hpp
KeeganRen/FaceReconstruction
03b4e83a8287b97e320ccabb4645fc7d09dfabca
[ "Apache-2.0" ]
124
2016-07-18T06:39:02.000Z
2022-03-02T18:33:00.000Z
/* * Eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/fitting/nonlinear_camera_estimation.hpp * * Copyright 2015 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef NONLINEARCAMERAESTIMATION_HPP_ #define NONLINEARCAMERAESTIMATION_HPP_ #include "eos/fitting/detail/nonlinear_camera_estimation_detail.hpp" #include "glm/gtc/matrix_transform.hpp" #include "Eigen/Geometry" #include "unsupported/Eigen/NonLinearOptimization" #include "opencv2/core/core.hpp" #include <vector> #include <cassert> namespace eos { namespace fitting { /** * @brief A class representing a camera viewing frustum. At the * moment used as orthographic camera only. */ struct Frustum { float l, r, b, t; // optional<float> n, f; }; /** * @brief Represents a set of estimated model parameters (rotation, translation) and * camera parameters (viewing frustum). * * The estimated rotation and translation transform the model from model-space to camera-space, * and, if one wishes to use OpenGL, can be used to build the model-view matrix. * The parameters are the inverse of the camera position in 3D space. * * The camera frustum describes the size of the viewing plane of the camera, and * can be used to build an OpenGL-conformant orthographic projection matrix. * * Together, these parameters fully describe the imaging process of a given model instance * (under an orthographic projection). * * The rotation values are given in radians and estimated using the RPY convention. * Yaw is applied first to the model, then pitch, then roll (R * P * Y * vertex). */ struct OrthographicRenderingParameters { float r_x; // Pitch. float r_y; // Yaw. Positive means subject is looking left (we see her right cheek). float r_z; // Roll. Positive means the subject's right eye is further down than the other one (he tilts his head to the right). float t_x; float t_y; Frustum frustum; }; /** * @brief Converts a glm::mat4x4 to a cv::Mat. * * Note: move to render namespace */ cv::Mat to_mat(const glm::mat4x4& glm_matrix) { // glm stores its matrices in col-major order in memory, OpenCV in row-major order. // Hence we transpose the glm matrix to flip the memory layout, and then point OpenCV // to that location. auto glm_matrix_t = glm::transpose(glm_matrix); cv::Mat opencv_mat(4, 4, CV_32FC1, &glm_matrix_t[0]); // we need to clone because the underlying data of the original goes out of scope return opencv_mat.clone(); }; /** * @brief Creates a 4x4 model-view matrix from given fitting parameters. * * Together with the Frustum information, this describes the full * orthographic rendering parameters of the OpenGL pipeline. * Example: * * @code * fitting::OrthographicRenderingParameters rendering_params = ...; * glm::mat4x4 view_model = get_4x4_modelview_matrix(rendering_params); * glm::mat4x4 ortho_projection = glm::ortho(rendering_params.frustum.l, rendering_params.frustum.r, rendering_params.frustum.b, rendering_params.frustum.t); * glm::vec4 viewport(0, image.rows, image.cols, -image.rows); // flips y, origin top-left, like in OpenCV * * // project a point from 3D to 2D: * glm::vec3 point_3d = ...; // from a mesh for example * glm::vec3 point_2d = glm::project(point_3d, view_model, ortho_projection, viewport); * @endcode */ glm::mat4x4 get_4x4_modelview_matrix(fitting::OrthographicRenderingParameters params) { // rotation order: RPY * P auto rot_mtx_x = glm::rotate(glm::mat4(1.0f), params.r_x, glm::vec3{ 1.0f, 0.0f, 0.0f }); auto rot_mtx_y = glm::rotate(glm::mat4(1.0f), params.r_y, glm::vec3{ 0.0f, 1.0f, 0.0f }); auto rot_mtx_z = glm::rotate(glm::mat4(1.0f), params.r_z, glm::vec3{ 0.0f, 0.0f, 1.0f }); auto t_mtx = glm::translate(glm::mat4(1.0f), glm::vec3{ params.t_x, params.t_y, 0.0f }); auto modelview = t_mtx * rot_mtx_z * rot_mtx_x * rot_mtx_y; return modelview; }; /** * @brief Creates a 3x4 affine camera matrix from given fitting parameters. The * matrix transforms points directly from model-space to screen-space. * * This function is mainly used since the linear shape fitting fitting::fit_shape_to_landmarks_linear * expects one of these 3x4 affine camera matrices, as well as render::extract_texture. */ cv::Mat get_3x4_affine_camera_matrix(fitting::OrthographicRenderingParameters params, int width, int height) { auto view_model = to_mat(get_4x4_modelview_matrix(params)); auto ortho_projection = to_mat(glm::ortho(params.frustum.l, params.frustum.r, params.frustum.b, params.frustum.t)); cv::Mat mvp = ortho_projection * view_model; glm::vec4 viewport(0, height, width, -height); // flips y, origin top-left, like in OpenCV // equivalent to what glm::project's viewport does, but we don't change z and w: cv::Mat viewport_mat = (cv::Mat_<float>(4, 4) << viewport[2] / 2.0f, 0.0f, 0.0f, viewport[2] / 2.0f + viewport[0], 0.0f, viewport[3] / 2.0f, 0.0f, viewport[3] / 2.0f + viewport[1], 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); cv::Mat full_projection_4x4 = viewport_mat * mvp; cv::Mat full_projection_3x4 = full_projection_4x4.rowRange(0, 3); // we take the first 3 rows, but then set the last one to [0 0 0 1] full_projection_3x4.at<float>(2, 0) = 0.0f; full_projection_3x4.at<float>(2, 1) = 0.0f; full_projection_3x4.at<float>(2, 2) = 0.0f; full_projection_3x4.at<float>(2, 3) = 1.0f; return full_projection_3x4; }; /** * @brief Returns a glm/OpenGL compatible viewport vector that flips y and * has the origin on the top-left, like in OpenCV. * * Note: Move to detail namespace / not used at the moment. */ glm::vec4 get_opencv_viewport(int width, int height) { return glm::vec4(0, height, width, -height); }; /** * @brief This algorithm estimates the rotation angles and translation of the model, as * well as the viewing frustum of the camera, given a set of corresponding 2D-3D points. * * It assumes an orthographic camera and estimates 6 parameters, * [r_x, r_y, r_z, t_x, t_y, frustum_scale], where the first five describe how to transform * the model, and the last one describes the cameras viewing frustum (see CameraParameters). * This 2D-3D correspondence problem is solved using Eigen's LevenbergMarquardt algorithm. * * The method is slightly inspired by "Computer Vision: Models Learning and Inference", * Simon J.D. Prince, 2012, but different in a lot of respects. * * Eigen's LM implementation requires at least 6 data points, so we require >= 6 corresponding points. * * Notes/improvements: * The algorithm works reliable as it is, however, it could be improved with the following: * - A better initial guess (see e.g. Prince) * - Using the analytic derivatives instead of Eigen::NumericalDiff - they're easy to calculate. * * @param[in] image_points A list of 2D image points. * @param[in] model_points Corresponding points of a 3D model. * @param[in] width Width of the image (or viewport). * @param[in] height Height of the image (or viewport). * @return The estimated model and camera parameters. */ OrthographicRenderingParameters estimate_orthographic_camera(std::vector<cv::Vec2f> image_points, std::vector<cv::Vec4f> model_points, int width, int height) { using cv::Mat; assert(image_points.size() == model_points.size()); assert(image_points.size() >= 6); // Number of correspondence points given needs to be equal to or larger than 6 const float aspect = static_cast<float>(width) / height; // Set up the initial parameter vector and the cost function: int num_params = 6; // 俯仰值 偏航值 翻滚值 Eigen::VectorXd parameters; // [rot_x_pitch, rot_y_yaw, rot_z_roll, t_x, t_y, frustum_scale] parameters.setConstant(num_params, 0.0); // Set all 6 values to zero (except frustum_scale, see next line) parameters[5] = 110.0; // This is just a rough hand-chosen scaling estimate - we could do a lot better. But it works. detail::OrthographicParameterProjection cost_function(image_points, model_points, width, height); // Note: we have analytical derivatives, so we should use them! Eigen::NumericalDiff<detail::OrthographicParameterProjection> cost_function_with_derivative(cost_function, 0.0001); // I had to change the default value of epsfcn, it works well around 0.0001. It couldn't produce the derivative with the default, I guess the changes in the gradient were too small. Eigen::LevenbergMarquardt<Eigen::NumericalDiff<detail::OrthographicParameterProjection>> lm(cost_function_with_derivative); auto info = lm.minimize(parameters); // we could or should use the return value // 'parameters' contains the solution now. Frustum camera_frustum{ -1.0f * aspect * static_cast<float>(parameters[5]), 1.0f * aspect * static_cast<float>(parameters[5]), -1.0f * static_cast<float>(parameters[5]), 1.0f * static_cast<float>(parameters[5]) }; return OrthographicRenderingParameters{ static_cast<float>(parameters[0]), static_cast<float>(parameters[1]), static_cast<float>(parameters[2]), static_cast<float>(parameters[3]), static_cast<float>(parameters[4]), camera_frustum }; }; } /* namespace fitting */ } /* namespace eos */ #endif /* NONLINEARCAMERAESTIMATION_HPP_ */
44.278539
233
0.736826
[ "mesh", "geometry", "render", "shape", "vector", "model", "transform", "3d" ]
b1c7e125f080eed82b3b5c9d226f1da03f20d91e
1,720
cpp
C++
Verilog/P4/test/gen.cpp
JJLeo/BUAA-CO-2020
1d1a3797f7188530464a1dfbe8a017dd01bb817a
[ "MIT" ]
9
2021-03-04T07:22:24.000Z
2021-11-30T02:56:08.000Z
Verilog/P4/test/gen.cpp
johnnyamazing/BUAA-CO-2020
1d1a3797f7188530464a1dfbe8a017dd01bb817a
[ "MIT" ]
null
null
null
Verilog/P4/test/gen.cpp
johnnyamazing/BUAA-CO-2020
1d1a3797f7188530464a1dfbe8a017dd01bb817a
[ "MIT" ]
3
2021-09-28T07:41:35.000Z
2021-12-14T08:55:28.000Z
#include <bits/stdc++.h> using namespace std; vector<int> r; mt19937 mt(time(0)); uniform_int_distribution<int> imm16(0, (1 << 16) - 1), siz(0, 1023), reg(0, 2), grf(1, 30), I(1, 6), J(7, 8), IJ(1, 8); int cnt; void solve(int); int getR(){ return r[reg(mt)]; } void addu(){ printf("addu $%d, $%d, $%d\n", getR(), getR(), getR()); } void subu(){ printf("subu $%d, $%d, $%d\n", getR(), getR(), getR()); } void ori(){ printf("ori $%d, $%d, %d\n", getR(), getR(), imm16(mt)); } void lw(){ printf("lw $%d, %d($0)\n", getR(), siz(mt) * 4); } void sw(){ printf("sw $%d, %d($0)\n", getR(), siz(mt) * 4); } void lui(){ printf("lui $%d, %d\n", getR(), imm16(mt)); } void beq(){ printf("beq $%d, $%d, label%d\n", getR(), getR(), ++cnt); solve(I(mt)); printf("label%d: ", cnt); solve(I(mt)); } void jaljr(){ printf("jal label%d\n", ++cnt); solve(I(mt)); int x = getR(); printf("label%d: ori $%d, $0, 20\n", cnt, x); printf("addu $%d, $%d, $31\n", x, x); printf("jr $%d\n", x); solve(I(mt)); solve(I(mt)); } void j(){ printf("j label%d\n", ++cnt); solve(I(mt)); solve(I(mt)); printf("label%d: ", cnt); solve(I(mt)); } void solve(int i){ switch(i){ case 1: addu(); break; case 2: subu(); break; case 3: ori(); break; case 4: lw(); break; case 5: sw(); break; case 6: lui(); break; case 7: beq(); break; case 8: jaljr(); break; case 9: j(); break; } } int main(){ r.push_back(grf(mt)), r.push_back(grf(mt)), r.push_back(grf(mt)); freopen("test.asm", "w", stdout); puts("ori $28, $0, 0"); puts("ori $29, $0, 0"); for(int i = 1;i <= 700;i++){ int x = IJ(mt); if(x > 6) i += 5; solve(x); } }
14.700855
66
0.496512
[ "vector" ]
b1cc2ba9749f18bb85e9d8661ddc416dce7d4740
2,495
hxx
C++
src/include/sk/check.hxx
sikol/sk-async
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
3
2021-04-08T12:47:39.000Z
2021-09-25T11:43:41.000Z
src/include/sk/check.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
src/include/sk/check.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef SK_CHECK_HXX #define SK_CHECK_HXX #include <iostream> namespace sk::detail { [[noreturn]] inline auto unexpected(char const *what) noexcept -> void { std::cerr << "sk-cio: fatal internal error: " << what << std::endl; std::abort(); } } // namespace sk::detail /************************************************************************* * SK_CHECK: conditional assert for debug builds. */ #ifndef NDEBUG # define SK_CHECK(cond, msg) \ do { \ if (!(cond)) { \ std::cerr << "sk-cio invariant failure: " << (msg) << '\n'; \ std::abort(); \ } \ } while (0) #else # define SK_CHECK(cond, msg) ((void)0) #endif #endif // SK_CHECK_HXX
38.384615
80
0.591583
[ "object" ]
b1d0797ff16b7a4a2e108860419538fdd5e99df7
5,564
cpp
C++
hphp/runtime/ext/asio/ext_async-generator.cpp
aingram/hhvm
a0c84e34fa96f680660d9a90e8e7637eaa35943b
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/asio/ext_async-generator.cpp
aingram/hhvm
a0c84e34fa96f680660d9a90e8e7637eaa35943b
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/asio/ext_async-generator.cpp
aingram/hhvm
a0c84e34fa96f680660d9a90e8e7637eaa35943b
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/asio/ext_async-generator.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/memory-manager.h" #include "hphp/runtime/ext/asio/asio-session.h" #include "hphp/runtime/ext/asio/async-generator-wait-handle.h" #include "hphp/runtime/ext/asio/static-wait-handle.h" #include "hphp/runtime/vm/bytecode.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/resumable.h" #include "hphp/runtime/vm/runtime.h" #include "hphp/runtime/vm/jit/types.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// void delete_AsyncGenerator(ObjectData* od, const Class*) { auto gen = static_cast<c_AsyncGenerator*>(od); Resumable::Destroy(gen->data()->resumable()->size(), gen); } /////////////////////////////////////////////////////////////////////////////// AsyncGeneratorData::~AsyncGeneratorData() { if (LIKELY(getState() == State::Done)) { return; } assert(getState() != State::Running); // Free locals, but don't trigger the EventHook for FunctionReturn since // the generator has already been exited. We don't want redundant calls. ActRec* ar = actRec(); frame_free_locals_inl_no_hook<false>(ar, ar->m_func->numLocals()); } ObjectData* AsyncGeneratorData::Create(const ActRec* fp, size_t numSlots, jit::TCA resumeAddr, Offset resumeOffset) { assert(fp); assert(!fp->resumed()); assert(fp->func()->isAsyncGenerator()); void* genDataPtr = Resumable::Create<false, sizeof(AsyncGeneratorData) + sizeof(c_AsyncGenerator)>( fp, numSlots, resumeAddr, resumeOffset); AsyncGeneratorData* genData = new (genDataPtr) AsyncGeneratorData(); auto const gen = new (genData + 1) c_AsyncGenerator(); assert(gen->hasExactlyOneRef()); assert(gen->noDestruct()); genData->setState(State::Created); genData->m_waitHandle = nullptr; return static_cast<ObjectData*>(gen); } c_AsyncGeneratorWaitHandle* AsyncGeneratorData::await(Offset resumeOffset, c_WaitableWaitHandle* child) { assert(getState() == State::Running); resumable()->setResumeAddr(nullptr, resumeOffset); if (m_waitHandle) { // Resumed execution. m_waitHandle->await(child); return nullptr; } else { // Eager executon. m_waitHandle = c_AsyncGeneratorWaitHandle::Create(this, child); return m_waitHandle; } } c_StaticWaitHandle* AsyncGeneratorData::yield(Offset resumeOffset, const Cell* key, const Cell value) { assert(getState() == State::Running); resumable()->setResumeAddr(nullptr, resumeOffset); setState(State::Started); auto keyValueTuple = make_packed_array( key ? Variant(tvAsCVarRef(key), Variant::CellCopy()) : init_null_variant, Variant(tvAsCVarRef(&value), Variant::CellCopy())); auto keyValueTupleTV = make_tv<KindOfArray>(keyValueTuple.detach()); if (m_waitHandle) { // Resumed execution. m_waitHandle->ret(*tvAssertCell(&keyValueTupleTV)); m_waitHandle = nullptr; return nullptr; } else { // Eager execution. return c_StaticWaitHandle::CreateSucceeded(keyValueTupleTV); } } c_StaticWaitHandle* AsyncGeneratorData::ret() { assert(getState() == State::Running); setState(State::Done); auto nullTV = make_tv<KindOfNull>(); if (m_waitHandle) { // Resumed execution. m_waitHandle->ret(nullTV); m_waitHandle = nullptr; return nullptr; } else { return c_StaticWaitHandle::CreateSucceeded(nullTV); } } c_StaticWaitHandle* AsyncGeneratorData::fail(ObjectData* exception) { assert(getState() == State::Running); setState(State::Done); if (m_waitHandle) { // Resumed execution. m_waitHandle->fail(exception); m_waitHandle = nullptr; return nullptr; } else { return c_StaticWaitHandle::CreateFailed(exception); } } void AsyncGeneratorData::failCpp() { assert(getState() == State::Running); setState(State::Done); if (m_waitHandle) { // Resumed execution. m_waitHandle->failCpp(); m_waitHandle = nullptr; } } void c_AsyncGenerator::t___construct() {} // Functions with native implementation. void c_AsyncGenerator::t_next() {always_assert(false);} void c_AsyncGenerator::t_send(const Variant& value) {always_assert(false);} void c_AsyncGenerator::t_raise(const Object& exception) {always_assert(false);} /////////////////////////////////////////////////////////////////////////////// }
33.926829
79
0.613408
[ "object" ]
b1d1fb55acdcdd88a186dc37e787eff29b06549e
19,654
hh
C++
ads-df/AsyncRecordParser.hh
lairofthegoldinblair/trecul
41953c22f18f76e5add7a35a13775f70459fcd96
[ "BSD-3-Clause" ]
7
2015-04-24T13:24:22.000Z
2020-01-17T05:47:43.000Z
ads-df/AsyncRecordParser.hh
lairofthegoldinblair/trecul
41953c22f18f76e5add7a35a13775f70459fcd96
[ "BSD-3-Clause" ]
null
null
null
ads-df/AsyncRecordParser.hh
lairofthegoldinblair/trecul
41953c22f18f76e5add7a35a13775f70459fcd96
[ "BSD-3-Clause" ]
4
2015-12-24T16:29:58.000Z
2022-02-04T19:30:18.000Z
#ifndef __ASYNCRECORDPARSER_H__ #define __ASYNCRECORDPARSER_H__ #include <stdint.h> #include <stdexcept> #include <iostream> #include <boost/serialization/serialization.hpp> #include "RecordBuffer.hh" #include "RecordType.hh" #include "RuntimeOperator.hh" #include "FileSystem.hh" #include "FileService.hh" #include "RecordParser.hh" #include "StreamBufferBlock.hh" // Coroutine-ish parser classes class ParserState { private: int32_t mResult; public: static ParserState exhausted() { return ParserState(1); } static ParserState success() { return ParserState(0); } static ParserState error(int32_t errCode) { return ParserState(errCode); } ParserState() : mResult(1) { } ParserState(int32_t result) : mResult(result) { } bool isError() const { return mResult < 0; } bool isExhausted() const { return mResult == 1; } bool isSuccess() const { return mResult == 0; } int32_t result() const { return mResult; } }; class AsyncDataBlock { protected: // Mark for saving data in block uint8_t * mCurrentBlockMark; // Start of the data block uint8_t * mCurrentBlockStart; // End of valid data in the block uint8_t * mCurrentBlockEnd; // Current position within block uint8_t * mCurrentBlockPtr; public: AsyncDataBlock(); AsyncDataBlock(uint8_t * start, uint8_t * end); void rebind(uint8_t * start, uint8_t * end); uint8_t * start() { return mCurrentBlockStart; } uint8_t * begin() { return mCurrentBlockPtr; } uint8_t * end() { return mCurrentBlockEnd; } const uint8_t * begin() const { return mCurrentBlockPtr; } const uint8_t * end() const { return mCurrentBlockEnd; } bool isEmpty() const { return begin() == end(); } void consume(std::size_t sz) { mCurrentBlockPtr += sz; } void consumeAll() { mCurrentBlockPtr = mCurrentBlockEnd; } }; class ImporterDelegate { private: typedef ParserState (*ImporterStub)(void *, AsyncDataBlock&, RecordBuffer); void * mObject; ImporterStub mMethod; template <class _T, ParserState (_T::*_TMethod)(AsyncDataBlock&, RecordBuffer)> static ParserState Stub(void * obj, AsyncDataBlock& source, RecordBuffer target) { _T* p = static_cast<_T*>(obj); return (p->*_TMethod)(source, target); } public: ImporterDelegate() : mObject(NULL), mMethod(NULL) { } template <class _T, ParserState (_T::*_TMethod)(AsyncDataBlock&, RecordBuffer)> static ImporterDelegate fromMethod(_T * obj) { ImporterDelegate d; d.mObject = obj; d.mMethod = &Stub<_T, _TMethod>; return d; } ParserState operator()(AsyncDataBlock& targetOffset, RecordBuffer size) { return (*mMethod)(mObject, targetOffset, size); } }; class ImporterSpec { private: // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { } protected: ImporterSpec() { } public: virtual ~ImporterSpec() {} virtual ImporterDelegate makeObject(void * buf) const =0; virtual std::size_t objectSize() const =0; virtual std::size_t objectAlignment() const =0; virtual bool isConsumeOnly() const { return false; } static void createDefaultImport(const RecordType * recordType, const RecordType * baseRecordType, char fieldDelim, char recordDelim, std::vector<ImporterSpec*>& importers); }; class ConsumeTerminatedString { private: enum State { START, READ }; State mState; uint8_t mTerm; bool importInternal(AsyncDataBlock& source, RecordBuffer target) { uint8_t * start = source.begin(); uint8_t * found = (uint8_t *) memchr((char *) source.begin(), mTerm, (std::size_t) (source.end()-source.begin())); if(found) { source.consume(std::size_t(found - start) + 1); return true; } else { source.consumeAll(); return false; } } public: ConsumeTerminatedString(uint8_t term); ParserState import(AsyncDataBlock& source, RecordBuffer target); }; class ConsumeTerminatedStringSpec : public ImporterSpec { private: uint8_t mTerm; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(ImporterSpec); ar & BOOST_SERIALIZATION_NVP(mTerm); } ConsumeTerminatedStringSpec() : mTerm(0) { } public: ConsumeTerminatedStringSpec(uint8_t term) : mTerm(term) { } ImporterDelegate makeObject(void * buf) const { ConsumeTerminatedString * obj = new (buf) ConsumeTerminatedString(mTerm); return ImporterDelegate::fromMethod<ConsumeTerminatedString, &ConsumeTerminatedString::import>(obj); } std::size_t objectSize() const { return sizeof(ConsumeTerminatedString); } std::size_t objectAlignment() const { return boost::alignment_of<ConsumeTerminatedString>::value; } bool isConsumeOnly() const { return true; } }; class ImportDecimalInt32 { private: FieldAddress mTargetOffset; enum State { START, READ_FIRST, READ_DIGITS }; State mState; int32_t mValue; uint8_t mTerm; bool mNeg; bool importInternal(AsyncDataBlock& source, RecordBuffer target) { int32_t val = mValue; uint8_t * start = source.begin(); uint8_t * end = source.end(); for(uint8_t * s = start; s != end; ++s) { if (*s > '9' || *s < '0') { // TODO: Right now assuming and not validating a single delimiter character // TODO: Protect against overflow mTargetOffset.setInt32(mNeg ? -val : val, target); source.consume(std::size_t(s - start)); mValue = 0; mNeg = false; return true; } val = val * 10 + (*s - '0'); } mValue = val; source.consumeAll(); return false; } public: ImportDecimalInt32(const FieldAddress& targetOffset, uint8_t term); ParserState import(AsyncDataBlock& source, RecordBuffer target); }; class ImportDecimalInt32Spec : public ImporterSpec { private: FieldAddress mTargetOffset; uint8_t mTerm; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(ImporterSpec); ar & BOOST_SERIALIZATION_NVP(mTargetOffset); ar & BOOST_SERIALIZATION_NVP(mTerm); } ImportDecimalInt32Spec() : mTerm(0) { } public: ImportDecimalInt32Spec(const FieldAddress & targetOffset, uint8_t term) : mTargetOffset(targetOffset), mTerm(term) { } ImporterDelegate makeObject(void * buf) const { ImportDecimalInt32 * obj = new (buf) ImportDecimalInt32(mTargetOffset, mTerm); return ImporterDelegate::fromMethod<ImportDecimalInt32, &ImportDecimalInt32::import>(obj); } std::size_t objectSize() const { return sizeof(ImportDecimalInt32); } std::size_t objectAlignment() const { return boost::alignment_of<ImportDecimalInt32>::value; } }; class ImportDouble { private: FieldAddress mTargetOffset; enum State { START, READ }; State mState; std::vector<uint8_t> * mLocal; uint8_t mTerm; public: ImportDouble(const FieldAddress& targetOffset, uint8_t term); ParserState import(AsyncDataBlock& source, RecordBuffer target); }; class ImportDoubleSpec : public ImporterSpec { private: FieldAddress mTargetOffset; uint8_t mTerm; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(ImporterSpec); ar & BOOST_SERIALIZATION_NVP(mTargetOffset); ar & BOOST_SERIALIZATION_NVP(mTerm); } ImportDoubleSpec() : mTerm(0) { } public: ImportDoubleSpec(const FieldAddress & targetOffset, uint8_t term) : mTargetOffset(targetOffset), mTerm(term) { } ImporterDelegate makeObject(void * buf) const { ImportDouble * obj = new (buf) ImportDouble(mTargetOffset, mTerm); return ImporterDelegate::fromMethod<ImportDouble, &ImportDouble::import>(obj); } std::size_t objectSize() const { return sizeof(ImportDouble); } std::size_t objectAlignment() const { return boost::alignment_of<ImportDouble>::value; } }; class ImportFixedLengthString { private: FieldAddress mTargetOffset; enum State { START, READ }; State mState; int32_t mSize; // For slow path (partial reads); where in the target // are we. int32_t mRead; public: ImportFixedLengthString(const FieldAddress& targetOffset, int32_t size); ParserState import(AsyncDataBlock& source, RecordBuffer target); }; class ImportFixedLengthStringSpec : public ImporterSpec { private: FieldAddress mTargetOffset; int32_t mSize; uint8_t mTerm; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(ImporterSpec); ar & BOOST_SERIALIZATION_NVP(mTargetOffset); ar & BOOST_SERIALIZATION_NVP(mSize); ar & BOOST_SERIALIZATION_NVP(mTerm); } ImportFixedLengthStringSpec() : mTerm(0) { } public: ImportFixedLengthStringSpec(const FieldAddress & targetOffset, int32_t sz, uint8_t term) : mTargetOffset(targetOffset), mSize(sz), mTerm(term) { } ImporterDelegate makeObject(void * buf) const { ImportFixedLengthString * obj = new (buf) ImportFixedLengthString(mTargetOffset, mSize); return ImporterDelegate::fromMethod<ImportFixedLengthString, &ImportFixedLengthString::import>(obj); } std::size_t objectSize() const { return sizeof(ImportFixedLengthString); } std::size_t objectAlignment() const { return boost::alignment_of<ImportFixedLengthString>::value; } }; class LogicalAsyncParser : public LogicalOperator { private: const RecordType * mFormat; std::string mStringFormat; std::string mMode; bool mSkipHeader; char mFieldSeparator; char mRecordSeparator; std::string mCommentLine; public: LogicalAsyncParser(); ~LogicalAsyncParser(); void check(PlanCheckContext& log); void create(class RuntimePlanBuilder& plan); }; class GenericAsyncParserOperatorType : public RuntimeOperatorType { friend class GenericAsyncParserOperator; private: typedef ImporterSpec* field_importer_type; typedef std::vector<ImporterSpec*>::const_iterator field_importer_const_iterator; // Importer instructions std::vector<field_importer_type> mImporters; // Importer to read to end of line (when skipping over non "r" log lines). field_importer_type mSkipImporter; // Access to stream buffer StreamBufferBlock mStreamBlock; // Create new records RecordTypeMalloc mStreamMalloc; RecordTypeMalloc mMalloc; RecordTypeFree mFree; // What am I importing const RecordType * mRecordType; // Is there a header to skip? bool mSkipHeader; // Skip lines starting with this. std::string mCommentLine; // Hack perf testing FieldAddress mAkidOffset; FieldAddress mCreDateOffset; FieldAddress mCoopIdOffset; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(RuntimeOperatorType); ar & BOOST_SERIALIZATION_NVP(mImporters); ar & BOOST_SERIALIZATION_NVP(mSkipImporter); ar & BOOST_SERIALIZATION_NVP(mStreamBlock); ar & BOOST_SERIALIZATION_NVP(mStreamMalloc); ar & BOOST_SERIALIZATION_NVP(mMalloc); ar & BOOST_SERIALIZATION_NVP(mFree); ar & BOOST_SERIALIZATION_NVP(mSkipHeader); ar & BOOST_SERIALIZATION_NVP(mCommentLine); } GenericAsyncParserOperatorType() { } public: GenericAsyncParserOperatorType(char fieldSeparator, char recordSeparator, const RecordType * inputStreamType, const RecordType * recordType, const RecordType * baseRecordType=NULL, const char * commentLine = ""); ~GenericAsyncParserOperatorType(); void setSkipHeader(bool value) { mSkipHeader = value; } RuntimeOperator * create(RuntimeOperator::Services & services) const; }; class GenericRecordImporter { public: typedef std::vector<ImporterDelegate>::iterator iterator; private: // The importer objects themselves uint8_t * mImporterObjects; // Importer delegates std::vector<ImporterDelegate> mImporters; public: GenericRecordImporter(std::vector<ImporterSpec*>::const_iterator begin, std::vector<ImporterSpec*>::const_iterator end); ~GenericRecordImporter(); iterator begin() { return mImporters.begin(); } iterator end() { return mImporters.end(); } }; class LogicalBlockRead : public LogicalOperator { private: const RecordType * mStreamBlock; std::string mFile; int32_t mBufferCapacity; bool mBucketed; public: LogicalBlockRead(); ~LogicalBlockRead(); void check(PlanCheckContext& log); void create(class RuntimePlanBuilder& plan); }; template<class _OpType> class GenericAsyncReadOperator : public RuntimeOperator { private: typedef _OpType operator_type; enum State { START, OPEN_FILE, READ_BLOCK, WRITE_BLOCK, WRITE_EOF }; State mState; // The list of files from which I read; retrieved // by calling my operator type. std::vector<boost::shared_ptr<FileChunk> > mFiles; // The file am I working on std::vector<boost::shared_ptr<FileChunk> >::const_iterator mFileIt; // File Service for async IO FileService * mFileService; // File handle that is currently open FileServiceFile * mFileHandle; // Record buffer I am importing into RecordBuffer mOutput; const operator_type & getLogParserType() { return *static_cast<const operator_type *>(&getOperatorType()); } public: GenericAsyncReadOperator(RuntimeOperator::Services& services, const RuntimeOperatorType& opType) : RuntimeOperator(services, opType), mFileService(NULL), mFileHandle(NULL) { } ~GenericAsyncReadOperator() { if (mFileService) { FileService::release(mFileService); } } /** * intialize. */ void start() { mFiles.clear(); // What file(s) am I parsing? typename _OpType::chunk_strategy_type chunkFiles; // Expand file name globbing, then get files for this // partition. chunkFiles.expand(getLogParserType().mFileInput, getNumPartitions()); chunkFiles.getFilesForPartition(getPartition(), mFiles); mState = START; mFileService = FileService::get(); onEvent(NULL); } void onEvent(RuntimePort * port) { switch(mState) { case START: for(mFileIt = mFiles.begin(); mFileIt != mFiles.end(); ++mFileIt) { BOOST_ASSERT(mFileHandle == NULL); // Allocate a new input buffer for the file in question. if ((*mFileIt)->getBegin() > 0) { throw std::runtime_error("Not implemented yet"); // mInputBuffer = DataBlock::get((*mFileIt)->getFilename().c_str(), // 64*1024, // (*mFileIt)->getBegin()-1, // (*mFileIt)->getEnd()); // RecordBuffer nullRecord; // getLogParserType().mSkipImporter.Import(*mInputBuffer, nullRecord); } else { // mInputBuffer = DataBlock::get((*mFileIt)->getFilename().c_str(), // 64*1024, // (*mFileIt)->getBegin(), // (*mFileIt)->getEnd()); mFileService->requestOpenForRead((*mFileIt)->getFilename().c_str(), (*mFileIt)->getBegin(), (*mFileIt)->getEnd(), getCompletionPorts()[0]); requestCompletion(0); mState = OPEN_FILE; return; case OPEN_FILE: { RecordBuffer buf; read(port, buf); mFileHandle = mFileService->getOpenResponse(buf); } } // Read all of the record in the file. while(true) { mOutput = getLogParserType().mMalloc.malloc(); // If empty read a block; it is OK to exhaust a file // here but not while in the middle of a record, so // we make a separate read attempt here. mFileService->requestRead(mFileHandle, (uint8_t *) getLogParserType().mBufferAddress.getCharPtr(mOutput), getLogParserType().mBufferCapacity, getCompletionPorts()[0]); requestCompletion(0); mState = READ_BLOCK; return; case READ_BLOCK: { RecordBuffer buf; read(port, buf); int32_t bytesRead = mFileService->getReadBytes(buf); if (0 == bytesRead) { getLogParserType().mFree.free(mOutput); mOutput = RecordBuffer(); // TODO: Send a message indicating file boundary potentially // Decompressors may need this to resync state (or maybe not). break; } getLogParserType().mBufferSize.setInt32(bytesRead, mOutput); } // Done cause we had good record // Flush always and write through to // avoid local queue; these are big chunks of memory requestWriteThrough(0); mState = WRITE_BLOCK; return; case WRITE_BLOCK: write(port, mOutput, true); } // Either EOF or parse failure. In either // case done with this file. // TODO: FIXME // delete mFileHandle; mFileHandle = NULL; } // Done with the last file so output EOS. requestWrite(0); mState = WRITE_EOF; return; case WRITE_EOF: write(port, RecordBuffer(), true); return; } } void shutdown() { } }; template <class _ChunkStrategy = ExplicitChunkStrategy > class GenericAsyncReadOperatorType : public RuntimeOperatorType { // Don't really know how to do friends between templates. public: typedef _ChunkStrategy chunk_strategy_type; typedef typename _ChunkStrategy::file_input file_input_type; typedef ImporterSpec* field_importer_type; typedef std::vector<ImporterSpec*>::const_iterator field_importer_const_iterator; // What file(s) am I parsing? file_input_type mFileInput; // Create new records RecordTypeMalloc mMalloc; RecordTypeFree mFree; // Accessors into buffer (size INTEGER, buffer CHAR(N)) FieldAddress mBufferSize; FieldAddress mBufferAddress; // Size of buffer to allocate int32_t mBufferCapacity; // Serialization friend class boost::serialization::access; template <class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(RuntimeOperatorType); ar & BOOST_SERIALIZATION_NVP(mFileInput); ar & BOOST_SERIALIZATION_NVP(mMalloc); ar & BOOST_SERIALIZATION_NVP(mFree); ar & BOOST_SERIALIZATION_NVP(mBufferSize); ar & BOOST_SERIALIZATION_NVP(mBufferAddress); ar & BOOST_SERIALIZATION_NVP(mBufferCapacity); } GenericAsyncReadOperatorType() { } public: GenericAsyncReadOperatorType(const typename _ChunkStrategy::file_input& file, const RecordType * streamBlockType) : RuntimeOperatorType("GenericAsyncReadOperatorType"), mFileInput(file), mMalloc(streamBlockType->getMalloc()), mFree(streamBlockType->getFree()), mBufferSize(streamBlockType->getFieldAddress("size")), mBufferAddress(streamBlockType->getFieldAddress("buffer")), mBufferCapacity(streamBlockType->getMember("buffer").GetType()->GetSize()) { } ~GenericAsyncReadOperatorType() { } int32_t numServiceCompletionPorts() const { return 1; } RuntimeOperator * create(RuntimeOperator::Services & services) const; }; template <class _ChunkStrategy> RuntimeOperator * GenericAsyncReadOperatorType<_ChunkStrategy>::create(RuntimeOperator::Services & services) const { return new GenericAsyncReadOperator<GenericAsyncReadOperatorType<_ChunkStrategy> >(services, *this); } #endif
24.722013
114
0.704284
[ "vector" ]
b1d24c065cf5f0205e50077e012dd25bcdce9ed5
9,402
cc
C++
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_client_ssl.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
3
2019-01-11T06:16:40.000Z
2021-02-24T23:48:21.000Z
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_client_ssl.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
2
2018-12-04T02:20:52.000Z
2018-12-22T06:16:30.000Z
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_client_ssl.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
18
2017-01-12T09:28:44.000Z
2019-04-18T20:47:42.000Z
/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include <boost/bind.hpp> #include <base/logging.h> #include <oper/agent_sandesh.h> #include <ovsdb_types.h> #include <ovsdb_client_ssl.h> #include <ovsdb_client_connection_state.h> #include <ovs_tor_agent/tor_agent_param.h> using OVSDB::OvsdbClientSession; using OVSDB::OvsdbClientSsl; using OVSDB::OvsdbClientSslSession; using OVSDB::OvsdbClientTcpSessionReader; using OVSDB::ConnectionStateTable; OvsdbClientSsl::OvsdbClientSsl(Agent *agent, IpAddress tor_ip, int tor_port, IpAddress tsn_ip, int keepalive_interval, int ha_stale_route_interval, const std::string &ssl_cert, const std::string &ssl_privkey, const std::string &ssl_cacert, OvsPeerManager *manager) : SslServer(agent->event_manager(), boost::asio::ssl::context::tlsv1_server), OvsdbClient(manager, keepalive_interval, ha_stale_route_interval), agent_(agent), ssl_server_port_(tor_port), tsn_ip_(tsn_ip.to_v4()), shutdown_(false) { // Get SSL context from base class and update boost::asio::ssl::context *ctx = context(); boost::system::error_code ec; // Verify peer to have a valid certificate ctx->set_verify_mode((boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert), ec); assert(ec.value() == 0); ctx->use_certificate_chain_file(ssl_cert, ec); if (ec.value() != 0) { LOG(ERROR, "Error : " << ec.message() << ", while using cert file : " << ssl_cert); exit(EINVAL); } ctx->use_private_key_file(ssl_privkey, boost::asio::ssl::context::pem, ec); if (ec.value() != 0) { LOG(ERROR, "Error : " << ec.message() << ", while using privkey file : " << ssl_privkey); exit(EINVAL); } ctx->load_verify_file(ssl_cacert, ec); if (ec.value() != 0) { LOG(ERROR, "Error : " << ec.message() << ", while using cacert file : " << ssl_cacert); exit(EINVAL); } } OvsdbClientSsl::~OvsdbClientSsl() { } void OvsdbClientSsl::RegisterClients() { RegisterConnectionTable(agent_); Initialize(ssl_server_port_); } SslSession *OvsdbClientSsl::AllocSession(SslSocket *socket) { SslSession *session = new OvsdbClientSslSession(agent_, peer_manager_, this, socket); session->set_observer(boost::bind(&OvsdbClientSsl::OnSessionEvent, this, _1, _2)); return session; } void OvsdbClientSsl::OnSessionEvent(TcpSession *session, TcpSession::Event event) { OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(session); ssl->EnqueueEvent(event); } const std::string OvsdbClientSsl::protocol() { return "PSSL"; } const std::string OvsdbClientSsl::server() { return LocalEndpoint().address().to_string(); } uint16_t OvsdbClientSsl::port() { return LocalEndpoint().port(); } Ip4Address OvsdbClientSsl::tsn_ip() { return tsn_ip_; } void OvsdbClientSsl::shutdown() { if (shutdown_) return; shutdown_ = true; OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(NextSession(NULL)); while (ssl != NULL) { if (!ssl->IsClosed()) { ssl->TriggerClose(); } ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl)); } } OvsdbClientSession *OvsdbClientSsl::FindSession(Ip4Address ip, uint16_t port) { SessionKey key(ip, port); SessionMap::iterator it; if (port != 0) { it = session_map_.find(key); } else { it = session_map_.upper_bound(key); } if (it != session_map_.end() && it->first.first == ip) { return it->second; } return NULL; } OvsdbClientSession *OvsdbClientSsl::NextSession(OvsdbClientSession *session) { SessionMap::iterator it; if (session == NULL) { it = session_map_.begin(); } else { OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(session); SessionKey key(ssl->remote_endpoint().address().to_v4(), ssl->remote_endpoint().port()); it = session_map_.upper_bound(key); } if (it != session_map_.end()) { return it->second; } return NULL; } void OvsdbClientSsl::AddSessionInfo(SandeshOvsdbClient &client) { SandeshOvsdbClientSession session; std::vector<SandeshOvsdbClientSession> session_list; OvsdbClientSslSession *ssl = static_cast<OvsdbClientSslSession *>(NextSession(NULL)); while (ssl != NULL) { ssl->AddSessionInfo(session); session_list.push_back(session); ssl = static_cast<OvsdbClientSslSession *>(NextSession(ssl)); } client.set_sessions(session_list); } // AcceptSession callback from SSLserver, to accept a session bool OvsdbClientSsl::AcceptSession(TcpSession *session) { if (shutdown_) { // don't accept session while shutting down return false; } return true; } OvsdbClientSslSession::OvsdbClientSslSession(Agent *agent, OvsPeerManager *manager, OvsdbClientSsl *server, SslSocket *sock, bool async_ready) : OvsdbClientSession(agent, manager), SslSession(server, sock, async_ready), status_("Init") { reader_ = new OvsdbClientTcpSessionReader(this, boost::bind(&OvsdbClientSslSession::RecvMsg, this, _1, _2)); // Process session events in KSync workqueue task context, session_event_queue_ = new WorkQueue<OvsdbSessionEvent>( agent->task_scheduler()->GetTaskId("Agent::KSync"), 0, boost::bind(&OvsdbClientSslSession::ProcessSessionEvent, this, _1)); session_event_queue_->set_name("OVSDB ssl session event queue"); } OvsdbClientSslSession::~OvsdbClientSslSession() { delete reader_; session_event_queue_->Shutdown(); delete session_event_queue_; } void OvsdbClientSslSession::OnRead(Buffer buffer) { reader_->OnRead(buffer); } void OvsdbClientSslSession::SendMsg(u_int8_t *buf, std::size_t len) { OVSDB_PKT_TRACE(Trace, "Sending: " + std::string((char *)buf, len)); Send(buf, len, NULL); } bool OvsdbClientSslSession::RecvMsg(const u_int8_t *buf, std::size_t len) { OVSDB_PKT_TRACE(Trace, "Received: " + std::string((const char*)buf, len)); MessageProcess(buf, len); return true; } int OvsdbClientSslSession::keepalive_interval() { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); return ovs_server->keepalive_interval(); } const boost::system::error_code & OvsdbClientSslSession::ovsdb_close_reason() const { return close_reason(); } ConnectionStateTable *OvsdbClientSslSession::connection_table() { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); return ovs_server->connection_table(); } KSyncObjectManager *OvsdbClientSslSession::ksync_obj_manager() { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); return ovs_server->ksync_obj_manager(); } Ip4Address OvsdbClientSslSession::tsn_ip() { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); return ovs_server->tsn_ip(); } void OvsdbClientSslSession::OnCleanup() { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); ovs_server->DeleteSession(this); } void OvsdbClientSslSession::TriggerClose() { // Close the session and return Close(); // SSL session will not notify event for self closed session // generate explicit event EnqueueEvent(TcpSession::CLOSE); } Ip4Address OvsdbClientSslSession::remote_ip() const { return remote_endpoint().address().to_v4(); } uint16_t OvsdbClientSslSession::remote_port() const { return remote_endpoint().port(); } bool OvsdbClientSslSession::ProcessSessionEvent(OvsdbSessionEvent ovs_event) { boost::system::error_code ec; switch (ovs_event.event) { case TcpSession::CLOSE: { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); boost::asio::ip::tcp::endpoint ep = remote_endpoint(); OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port()); ovs_server->session_map_.erase(key); OnClose(); } break; case TcpSession::ACCEPT: { OvsdbClientSsl *ovs_server = static_cast<OvsdbClientSsl *>(server()); boost::asio::ip::tcp::endpoint ep = remote_endpoint(); OvsdbClientSsl::SessionKey key(ep.address().to_v4(), ep.port()); std::pair<OvsdbClientSsl::SessionMap::iterator, bool> ret = ovs_server->session_map_.insert (std::pair<OvsdbClientSsl::SessionKey, OvsdbClientSslSession *>(key, this)); // assert if entry already exists assert(ret.second == true); } set_status("Established"); OnEstablish(); break; default: assert(false); break; } return true; } void OvsdbClientSslSession::EnqueueEvent(TcpSession::Event event) { OvsdbSessionEvent ovs_event; ovs_event.event = event; session_event_queue_->Enqueue(ovs_event); }
32.088737
89
0.653478
[ "vector" ]
b1d5bf0655647e580094836c4ad80409c3fec9bb
2,067
cc
C++
src/parser_perftest.cc
mathstuf/ninja
abd33d5e3b11ae5470f62cbce49723a4cf62870d
[ "Apache-2.0" ]
1
2016-10-12T23:11:30.000Z
2016-10-12T23:11:30.000Z
src/parser_perftest.cc
luvit/ninja
62d3b116bb93360bc13600e2ab972504a958d476
[ "Apache-2.0" ]
null
null
null
src/parser_perftest.cc
luvit/ninja
62d3b116bb93360bc13600e2ab972504a958d476
[ "Apache-2.0" ]
null
null
null
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include "depfile_parser.h" #include "util.h" int main(int argc, char* argv[]) { if (argc < 2) { printf("usage: %s <file1> <file2...>\n", argv[0]); return 1; } vector<float> times; for (int i = 1; i < argc; ++i) { const char* filename = argv[i]; for (int limit = 1 << 10; limit < (1<<20); limit *= 2) { int64_t start = GetTimeMillis(); for (int rep = 0; rep < limit; ++rep) { string buf; string err; if (ReadFile(filename, &buf, &err) < 0) { printf("%s: %s\n", filename, err.c_str()); return 1; } DepfileParser parser; if (!parser.Parse(&buf, &err)) { printf("%s: %s\n", filename, err.c_str()); return 1; } } int64_t end = GetTimeMillis(); if (end - start > 100) { int delta = (int)(end - start); float time = delta*1000 / (float)limit; printf("%s: %.1fus\n", filename, time); times.push_back(time); break; } } } if (!times.empty()) { float min = times[0]; float max = times[0]; float total = 0; for (size_t i = 0; i < times.size(); ++i) { total += times[i]; if (times[i] < min) min = times[i]; else if (times[i] > max) max = times[i]; } printf("min %.1fus max %.1fus avg %.1fus\n", min, max, total / times.size()); } return 0; }
26.844156
75
0.563135
[ "vector" ]
b1d9452433078a4d0a3a89f62360aa4c3f6803a8
3,784
cpp
C++
cxx/osrmjl.cpp
mattwigway/TransitRouter.jl
2ca102a7a33a9c47269bd80a56f5537c4d891d85
[ "Apache-2.0" ]
null
null
null
cxx/osrmjl.cpp
mattwigway/TransitRouter.jl
2ca102a7a33a9c47269bd80a56f5537c4d891d85
[ "Apache-2.0" ]
9
2021-03-11T05:24:41.000Z
2021-03-20T04:17:33.000Z
cxx/osrmjl.cpp
mattwigway/TransitRouter.jl
2ca102a7a33a9c47269bd80a56f5537c4d891d85
[ "Apache-2.0" ]
null
null
null
#include <osrm/table_parameters.hpp> #include <osrm/engine_config.hpp> #include <osrm/coordinate.hpp> #include <osrm/status.hpp> #include <osrm/json_container.hpp> #include <osrm/osrm.hpp> #include <math.h> #include <cstdlib> // set up wrapper functions so we can use ccall in julia to call out to cpp osrm // see https://isocpp.org/wiki/faq/mixing-c-and-cpp#overview-mixing-langs /** * Start up an OSRM Engine, and return an opaque pointer to it (on the Julia side, it can be a Ptr{Any}). * Pass in the path to a built OSRM graph, and the string for whether you are using multi-level Dijkstra (MLD) * or contraction hierarchies (CH) */ extern "C" struct osrm::OSRM * init_osrm (char * osrm_path, char * algorithm) { using namespace osrm; EngineConfig config; config.storage_config = {osrm_path}; config.use_shared_memory = false; // TODO this may have something to do with thread safety if (strcmp(algorithm, "ch") == 0) config.algorithm = EngineConfig::Algorithm::CH; else if (strcmp(algorithm, "mld") == 0) config.algorithm = EngineConfig::Algorithm::MLD; else throw std::runtime_error("algorithm must be 'ch' or 'mld'"); osrm::OSRM * engn = new osrm::OSRM(config); return engn; } /** * Compute a distance matrix from origins to destinations, using the specified OSRM instance (an opaque Ptr{Any} returned * by init_osrm on the Julia side). Write results into the durations and distances arrays. */ extern "C" int distance_matrix(struct osrm::OSRM * osrm, size_t n_origins, double * origin_lats, double * origin_lons, size_t n_destinations, double * destination_lats, double * destination_lons, double * durations, double * distances) { using namespace osrm; // Create table parameters. concatenate origins and destinations into coordinates, set origin/destination references. TableParameters params; for (size_t i = 0; i < n_origins; i++) { params.sources.push_back(i); params.coordinates.push_back({util::FloatLongitude{origin_lons[i]}, util::FloatLatitude{origin_lats[i]}}); } for (size_t i = 0; i < n_destinations; i++) { params.destinations.push_back(i + n_origins); params.coordinates.push_back({util::FloatLongitude{destination_lons[i]}, util::FloatLatitude{destination_lats[i]}}); } params.annotations = TableParameters::AnnotationsType::All; engine::api::ResultT result = json::Object(); Status stat = osrm->Table(params, result); if (stat != Status::Ok) return -1; auto &json_result = result.get<json::Object>(); std::vector<json::Value> jdurations = json_result.values["durations"].get<json::Array>().values; std::vector<json::Value> jdistances = json_result.values["distances"].get<json::Array>().values; // copy it into the result array // jdurations, jdistances are multidimensional arrays for (size_t destination = 0; destination < n_destinations; destination++) { for (size_t origin = 0; origin < n_origins; origin++) { // julia arrays: col-major order const size_t off = destination * n_origins + origin; const auto duration = jdurations.at(origin).get<json::Array>().values.at(destination); if (duration.is<json::Null>()) durations[off] = NAN; else durations[off] = double(duration.get<json::Number>().value); const auto distance = jdistances.at(origin).get<json::Array>().values.at(destination); if (distance.is<json::Null>()) distances[off] = NAN; else distances[off] = double(distance.get<json::Number>().value); } } return 0; } /** * Shut down an OSRM engine when it is no longer needed. */ extern "C" void stop_osrm (struct osrm::OSRM * engn) { delete engn; }
40.688172
124
0.684989
[ "object", "vector" ]
b1db7368d30f44039c2adc21160e6fe43b18ce9f
11,626
cc
C++
ui/wm/core/window_animations_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
ui/wm/core/window_animations_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
ui/wm/core/window_animations_unittest.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2016-12-23T04:21:10.000Z
2020-06-18T13:52:33.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_animations.h" #include "base/time/time.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/gfx/animation/animation_container_element.h" #include "ui/gfx/vector2d.h" #include "ui/wm/core/transient_window_manager.h" #include "ui/wm/core/transient_window_stacking_client.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/animation_host.h" using aura::Window; using ui::Layer; namespace wm { namespace { template<typename T>int GetZPosition(const T* child) { const T* parent = child->parent(); const std::vector<T*> children = parent->children(); typename std::vector<T*>::const_iterator iter = std::find(children.begin(), children.end(), child); DCHECK(iter != children.end()); return iter - children.begin(); } int GetWindowZPosition(const aura::Window* child) { return GetZPosition<aura::Window>(child); } int GetLayerZPosition(const ui::Layer* child) { return GetZPosition<ui::Layer>(child); } } // namespace class WindowAnimationsTest : public aura::test::AuraTestBase { public: WindowAnimationsTest() {} virtual void TearDown() override { AuraTestBase::TearDown(); } private: DISALLOW_COPY_AND_ASSIGN(WindowAnimationsTest); }; TEST_F(WindowAnimationsTest, LayerTargetVisibility) { scoped_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); // Layer target visibility changes according to Show/Hide. window->Show(); EXPECT_TRUE(window->layer()->GetTargetVisibility()); window->Hide(); EXPECT_FALSE(window->layer()->GetTargetVisibility()); window->Show(); EXPECT_TRUE(window->layer()->GetTargetVisibility()); } TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateShow) { // Tests if opacity and transform are reset when only show animation is // enabled. See also LayerTargetVisibility_AnimateHide. // Since the window is not visible after Hide() is called, opacity and // transform shouldn't matter in case of ANIMATE_SHOW, but we reset them // to keep consistency. scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_SHOW); // Layer target visibility and opacity change according to Show/Hide. window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); window->Hide(); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_FALSE(window->layer()->GetTargetVisibility()); EXPECT_EQ(0, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); } TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateHide) { // Tests if opacity and transform are reset when only hide animation is // enabled. Hide animation changes opacity and transform in addition to // visibility, so we need to reset not only visibility but also opacity // and transform to show the window. scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_HIDE); // Layer target visibility and opacity change according to Show/Hide. window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); window->Hide(); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_FALSE(window->layer()->GetTargetVisibility()); EXPECT_EQ(0, window->layer()->opacity()); window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); } TEST_F(WindowAnimationsTest, HideAnimationDetachLayers) { scoped_ptr<aura::Window> parent(aura::test::CreateTestWindowWithId(0, NULL)); scoped_ptr<aura::Window> other( aura::test::CreateTestWindowWithId(1, parent.get())); scoped_ptr<aura::Window> animating_window( aura::test::CreateTestWindowWithId(2, parent.get())); SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); EXPECT_EQ(0, GetWindowZPosition(other.get())); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(0, GetLayerZPosition(other->layer())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); ui::Layer* animating_layer = animating_window->layer(); animating_window->Hide(); EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( animating_window.get(), false)); EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); EXPECT_FALSE(animating_layer->delegate()); // Make sure the Hide animation create another layer, and both are in // the parent layer. EXPECT_NE(animating_window->layer(), animating_layer); EXPECT_TRUE( std::find(parent->layer()->children().begin(), parent->layer()->children().end(), animating_layer) != parent->layer()->children().end()); EXPECT_TRUE( std::find(parent->layer()->children().begin(), parent->layer()->children().end(), animating_window->layer()) != parent->layer()->children().end()); // Current layer must be already hidden. EXPECT_FALSE(animating_window->layer()->visible()); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(2, GetLayerZPosition(animating_layer)); parent->StackChildAtTop(other.get()); EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetWindowZPosition(other.get())); EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(1, GetLayerZPosition(other->layer())); // Make sure the animating layer is on top. EXPECT_EQ(2, GetLayerZPosition(animating_layer)); // Animating layer must be gone animating_layer->GetAnimator()->StopAnimating(); EXPECT_TRUE( std::find(parent->layer()->children().begin(), parent->layer()->children().end(), animating_layer) == parent->layer()->children().end()); } } TEST_F(WindowAnimationsTest, HideAnimationDetachLayersWithTransientChildren) { TransientWindowStackingClient transient_stacking_client; scoped_ptr<aura::Window> parent(aura::test::CreateTestWindowWithId(0, NULL)); scoped_ptr<aura::Window> other( aura::test::CreateTestWindowWithId(1, parent.get())); scoped_ptr<aura::Window> animating_window( aura::test::CreateTestWindowWithId(2, parent.get())); SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); scoped_ptr<aura::Window> transient1( aura::test::CreateTestWindowWithId(3, parent.get())); scoped_ptr<aura::Window> transient2( aura::test::CreateTestWindowWithId(4, parent.get())); TransientWindowManager::Get(animating_window.get()); AddTransientChild(animating_window.get(), transient1.get()); AddTransientChild(animating_window.get(), transient2.get()); EXPECT_EQ(0, GetWindowZPosition(other.get())); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(2, GetWindowZPosition(transient1.get())); EXPECT_EQ(3, GetWindowZPosition(transient2.get())); { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); ui::Layer* animating_layer = animating_window->layer(); animating_window->Hide(); EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( animating_window.get(), false)); EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); EXPECT_FALSE(animating_layer->delegate()); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(2, GetWindowZPosition(transient1.get())); EXPECT_EQ(3, GetWindowZPosition(transient2.get())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(2, GetLayerZPosition(transient1->layer())); EXPECT_EQ(3, GetLayerZPosition(transient2->layer())); EXPECT_EQ(4, GetLayerZPosition(animating_layer)); parent->StackChildAtTop(other.get()); EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetWindowZPosition(transient1.get())); EXPECT_EQ(2, GetWindowZPosition(transient2.get())); EXPECT_EQ(3, GetWindowZPosition(other.get())); EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(1, GetLayerZPosition(transient1->layer())); EXPECT_EQ(2, GetLayerZPosition(transient2->layer())); EXPECT_EQ(3, GetLayerZPosition(other->layer())); // Make sure the animating layer is on top of all windows. EXPECT_EQ(4, GetLayerZPosition(animating_layer)); } } // A simple AnimationHost implementation for the NotifyHideCompleted test. class NotifyHideCompletedAnimationHost : public aura::client::AnimationHost { public: NotifyHideCompletedAnimationHost() : hide_completed_(false) {} virtual ~NotifyHideCompletedAnimationHost() {} // Overridden from TestWindowDelegate: virtual void OnWindowHidingAnimationCompleted() override { hide_completed_ = true; } virtual void SetHostTransitionOffsets( const gfx::Vector2d& top_left, const gfx::Vector2d& bottom_right) override {} bool hide_completed() const { return hide_completed_; } private: bool hide_completed_; DISALLOW_COPY_AND_ASSIGN(NotifyHideCompletedAnimationHost); }; TEST_F(WindowAnimationsTest, NotifyHideCompleted) { NotifyHideCompletedAnimationHost animation_host; scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); aura::client::SetAnimationHost(window.get(), &animation_host); wm::SetWindowVisibilityAnimationType( window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_FADE); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->visible()); EXPECT_FALSE(animation_host.hide_completed()); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_TRUE(animation_host.hide_completed()); } // The rotation animation for hiding a window should not leak the animation // observer. TEST_F(WindowAnimationsTest, RotateHideNoLeak) { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); ui::Layer* animating_layer = window->layer(); wm::SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); AnimateOnChildWindowVisibilityChanged(window.get(), true); AnimateOnChildWindowVisibilityChanged(window.get(), false); animating_layer->GetAnimator()->StopAnimating(); } } // namespace wm
37.624595
80
0.733786
[ "vector", "transform" ]
b1dc70abbf785110653556dbdd097f6b5f70a569
8,379
cpp
C++
samples/snippets/cpp/VS_Snippets_Winforms/DataGridColumnStyle Overview/CPP/timecolumn.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Winforms/DataGridColumnStyle Overview/CPP/timecolumn.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Winforms/DataGridColumnStyle Overview/CPP/timecolumn.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
//<snippet1> #using <System.dll> #using <System.Data.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> #using <System.Xml.dll> using namespace System; using namespace System::Data; using namespace System::Windows::Forms; using namespace System::Drawing; using namespace System::Security::Permissions; // This example shows how to create your own column style that // hosts a control, in this case, a DateTimePicker. public ref class CustomDateTimePicker : public DateTimePicker { protected: [SecurityPermission(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)] virtual bool ProcessKeyMessage( Message% m ) override { // Keep all the keys for the DateTimePicker. return ProcessKeyEventArgs( m ); } }; public ref class DataGridTimePickerColumn : public DataGridColumnStyle { private: CustomDateTimePicker^ customDateTimePicker1; // The isEditing field tracks whether or not the user is // editing data with the hosted control. bool isEditing; public: DataGridTimePickerColumn() { customDateTimePicker1 = gcnew CustomDateTimePicker; customDateTimePicker1->Visible = false; } protected: virtual void Abort( int /*rowNum*/ ) override { isEditing = false; customDateTimePicker1->ValueChanged -= gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged ); Invalidate(); } virtual bool Commit( CurrencyManager^ dataSource, int rowNum ) override { customDateTimePicker1->Bounds = Rectangle::Empty; customDateTimePicker1->ValueChanged -= gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged ); if ( !isEditing ) return true; isEditing = false; try { DateTime value = customDateTimePicker1->Value; SetColumnValueAtRow( dataSource, rowNum, value ); } catch ( Exception^ ) { Abort( rowNum ); return false; } Invalidate(); return true; } virtual void Edit( CurrencyManager^ source, int rowNum, Rectangle bounds, bool /*readOnly*/, String^ /*displayText*/, bool cellIsVisible ) override { DateTime value = (DateTime) GetColumnValueAtRow( source, rowNum ); if ( cellIsVisible ) { customDateTimePicker1->Bounds = Rectangle( bounds.X + 2, bounds.Y + 2, bounds.Width - 4, bounds.Height - 4 ); customDateTimePicker1->Value = value; customDateTimePicker1->Visible = true; customDateTimePicker1->ValueChanged += gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged ); } else { customDateTimePicker1->Value = value; customDateTimePicker1->Visible = false; } if ( customDateTimePicker1->Visible ) DataGridTableStyle->DataGrid->Invalidate( bounds ); customDateTimePicker1->Focus(); } virtual System::Drawing::Size GetPreferredSize( Graphics^ /*g*/, Object^ /*value*/ ) override { return Size( 100, customDateTimePicker1->PreferredHeight + 4); } virtual int GetMinimumHeight() override { return customDateTimePicker1->PreferredHeight + 4; } virtual int GetPreferredHeight( Graphics^ /*g*/, Object^ /*value*/ ) override { return customDateTimePicker1->PreferredHeight + 4; } virtual void Paint( Graphics^ g, Rectangle bounds, CurrencyManager^ source, int rowNum ) override { Paint( g, bounds, source, rowNum, false ); } virtual void Paint( Graphics^ g, Rectangle bounds, CurrencyManager^ source, int rowNum, bool alignToRight ) override { Paint( g, bounds, source, rowNum, Brushes::Red, Brushes::Blue, alignToRight ); } virtual void Paint( Graphics^ g, Rectangle bounds, CurrencyManager^ source, int rowNum, Brush^ backBrush, Brush^ foreBrush, bool /*alignToRight*/ ) override { DateTime date = (DateTime) GetColumnValueAtRow( source, rowNum ); Rectangle rect = bounds; g->FillRectangle( backBrush, rect ); rect.Offset( 0, 2 ); rect.Height -= 2; g->DrawString( date.ToString( "d" ), this->DataGridTableStyle->DataGrid->Font, foreBrush, rect ); } virtual void SetDataGridInColumn( DataGrid^ value ) override { DataGridColumnStyle::SetDataGridInColumn( value ); if ( customDateTimePicker1->Parent != nullptr ) { customDateTimePicker1->Parent->Controls->Remove ( customDateTimePicker1 ); } if ( value != nullptr ) { value->Controls->Add( customDateTimePicker1 ); } } private: void TimePickerValueChanged( Object^ /*sender*/, EventArgs^ /*e*/ ) { // Remove the handler to prevent it from being called twice in a row. customDateTimePicker1->ValueChanged -= gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged ); this->isEditing = true; DataGridColumnStyle::ColumnStartedEditing( customDateTimePicker1 ); } }; public ref class MyForm: public Form { private: DataTable^ namesDataTable; DataGrid^ grid; public: MyForm() { grid = gcnew DataGrid; InitForm(); namesDataTable = gcnew DataTable( "NamesTable" ); namesDataTable->Columns->Add( gcnew DataColumn( "Name" ) ); DataColumn^ dateColumn = gcnew DataColumn ( "Date",DateTime::typeid ); dateColumn->DefaultValue = DateTime::Today; namesDataTable->Columns->Add( dateColumn ); DataSet^ namesDataSet = gcnew DataSet; namesDataSet->Tables->Add( namesDataTable ); grid->DataSource = namesDataSet; grid->DataMember = "NamesTable"; AddGridStyle(); AddData(); } private: void AddGridStyle() { DataGridTableStyle^ myGridStyle = gcnew DataGridTableStyle; myGridStyle->MappingName = "NamesTable"; DataGridTextBoxColumn^ nameColumnStyle = gcnew DataGridTextBoxColumn; nameColumnStyle->MappingName = "Name"; nameColumnStyle->HeaderText = "Name"; myGridStyle->GridColumnStyles->Add( nameColumnStyle ); DataGridTimePickerColumn^ timePickerColumnStyle = gcnew DataGridTimePickerColumn; timePickerColumnStyle->MappingName = "Date"; timePickerColumnStyle->HeaderText = "Date"; timePickerColumnStyle->Width = 100; myGridStyle->GridColumnStyles->Add( timePickerColumnStyle ); grid->TableStyles->Add( myGridStyle ); } void AddData() { DataRow^ dRow = namesDataTable->NewRow(); dRow->default[ "Name" ] = "Name 1"; dRow->default[ "Date" ] = DateTime(2001,12,01); namesDataTable->Rows->Add( dRow ); dRow = namesDataTable->NewRow(); dRow->default[ "Name" ] = "Name 2"; dRow->default[ "Date" ] = DateTime(2001,12,04); namesDataTable->Rows->Add( dRow ); dRow = namesDataTable->NewRow(); dRow->default[ "Name" ] = "Name 3"; dRow->default[ "Date" ] = DateTime(2001,12,29); namesDataTable->Rows->Add( dRow ); dRow = namesDataTable->NewRow(); dRow->default[ "Name" ] = "Name 4"; dRow->default[ "Date" ] = DateTime(2001,12,13); namesDataTable->Rows->Add( dRow ); dRow = namesDataTable->NewRow(); dRow->default[ "Name" ] = "Name 5"; dRow->default[ "Date" ] = DateTime(2001,12,21); namesDataTable->Rows->Add( dRow ); namesDataTable->AcceptChanges(); } void InitForm() { this->Size = System::Drawing::Size( 500, 500 ); grid->Size = System::Drawing::Size( 350, 250 ); grid->TabStop = true; grid->TabIndex = 1; this->StartPosition = FormStartPosition::CenterScreen; this->Controls->Add( grid ); } }; [STAThread] int main() { Application::Run( gcnew MyForm ); } //</snippet1>
28.59727
94
0.613438
[ "object" ]
b1e46aa0af1fac8d6b5c0d2fcb44d67ab8b51064
36,210
cc
C++
content/browser/gpu/gpu_blacklist_unittest.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
2
2020-06-10T07:15:26.000Z
2020-12-13T19:44:12.000Z
content/browser/gpu/gpu_blacklist_unittest.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
content/browser/gpu/gpu_blacklist_unittest.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/base_paths.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/version.h" #include "content/browser/gpu/gpu_blacklist.h" #include "content/public/common/gpu_info.h" #include "testing/gtest/include/gtest/gtest.h" using content::GpuFeatureType; using content::GpuSwitchingOption; class GpuBlacklistTest : public testing::Test { public: GpuBlacklistTest() { } virtual ~GpuBlacklistTest() { } const content::GPUInfo& gpu_info() const { return gpu_info_; } GpuBlacklist* Create() { GpuBlacklist* rt = new GpuBlacklist(); // Set up machine model to avoid triggering collection code on Mac. rt->SetCurrentMachineModelInfoForTesting("Test", "1.0"); return rt; } protected: void SetUp() { gpu_info_.gpu.vendor_id = 0x10de; gpu_info_.gpu.device_id = 0x0640; gpu_info_.driver_vendor = "NVIDIA"; gpu_info_.driver_version = "1.6.18"; gpu_info_.driver_date = "7-14-2009"; gpu_info_.gl_vendor = "NVIDIA Corporation"; gpu_info_.gl_renderer = "NVIDIA GeForce GT 120 OpenGL Engine"; gpu_info_.performance_stats.graphics = 5.0; gpu_info_.performance_stats.gaming = 5.0; gpu_info_.performance_stats.overall = 5.0; } void TearDown() { } private: content::GPUInfo gpu_info_; }; TEST_F(GpuBlacklistTest, CurrentBlacklistValidation) { FilePath data_file; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &data_file)); data_file = data_file.Append(FILE_PATH_LITERAL("content")) .Append(FILE_PATH_LITERAL("browser")) .Append(FILE_PATH_LITERAL("gpu")) .Append(FILE_PATH_LITERAL("software_rendering_list.json")); ASSERT_TRUE(file_util::PathExists(data_file)); int64 data_file_size64 = 0; ASSERT_TRUE(file_util::GetFileSize(data_file, &data_file_size64)); int data_file_size = static_cast<int>(data_file_size64); scoped_array<char> data(new char[data_file_size]); ASSERT_EQ(file_util::ReadFile(data_file, data.get(), data_file_size), data_file_size); std::string json_string(data.get(), data_file_size); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( json_string, GpuBlacklist::kAllOs)); EXPECT_FALSE(blacklist->contains_unknown_fields()); } TEST_F(GpuBlacklistTest, DefaultBlacklistSettings) { Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); // Default blacklist settings: all feature are allowed. GpuBlacklist::Decision decision = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()); EXPECT_EQ(decision.blacklisted_features, 0); EXPECT_EQ(decision.gpu_switching, content::GPU_SWITCHING_OPTION_UNKNOWN); } TEST_F(GpuBlacklistTest, EmptyBlacklist) { // Empty list: all features are allowed. const std::string empty_list_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"2.5\",\n" " \"entries\": [\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( empty_list_json, GpuBlacklist::kAllOs)); EXPECT_EQ(blacklist->GetVersion(), std::string("2.5")); GpuBlacklist::Decision decision = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()); EXPECT_EQ(decision.blacklisted_features, 0); EXPECT_EQ(decision.gpu_switching, content::GPU_SWITCHING_OPTION_UNKNOWN); } TEST_F(GpuBlacklistTest, DetailedEntryAndInvalidJson) { // Blacklist accelerated_compositing with exact setting. const std::string exact_list_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 5,\n" " \"os\": {\n" " \"type\": \"macosx\",\n" " \"version\": {\n" " \"op\": \"=\",\n" " \"number\": \"10.6.4\"\n" " }\n" " },\n" " \"vendor_id\": \"0x10de\",\n" " \"device_id\": [\"0x0640\"],\n" " \"driver_version\": {\n" " \"op\": \"=\",\n" " \"number\": \"1.6.18\"\n" " },\n" " \"blacklist\": [\n" " \"accelerated_compositing\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( exact_list_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING); // Invalid json input should not change the current blacklist settings. const std::string invalid_json = "invalid"; EXPECT_FALSE(blacklist->LoadGpuBlacklist( invalid_json, GpuBlacklist::kAllOs)); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING); std::vector<uint32> entries; bool disabled = false; blacklist->GetDecisionEntries(entries, disabled); EXPECT_EQ(entries.size(), 1u); EXPECT_EQ(entries[0], 5u); EXPECT_EQ(blacklist->max_entry_id(), 5u); } TEST_F(GpuBlacklistTest, VendorOnAllOsEntry) { // Blacklist a vendor on all OS. const std::string vendor_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"vendor_id\": \"0x10de\",\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); // Blacklist entries won't be filtered to the current OS only upon loading. EXPECT_TRUE(blacklist->LoadGpuBlacklist( vendor_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_MACOSX) || \ defined(OS_OPENBSD) // Blacklist entries will be filtered to the current OS only upon loading. EXPECT_TRUE(blacklist->LoadGpuBlacklist( vendor_json, GpuBlacklist::kCurrentOsOnly)); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); #endif } TEST_F(GpuBlacklistTest, VendorOnLinuxEntry) { // Blacklist a vendor on Linux only. const std::string vendor_linux_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"vendor_id\": \"0x10de\",\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( vendor_linux_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS); } TEST_F(GpuBlacklistTest, AllExceptNVidiaOnLinuxEntry) { // Blacklist all cards in Linux except NVIDIA. const std::string linux_except_nvidia_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"exceptions\": [\n" " {\n" " \"vendor_id\": \"0x10de\"\n" " }\n" " ],\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( linux_except_nvidia_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); } TEST_F(GpuBlacklistTest, AllExceptIntelOnLinuxEntry) { // Blacklist all cards in Linux except Intel. const std::string linux_except_intel_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"exceptions\": [\n" " {\n" " \"vendor_id\": \"0x8086\"\n" " }\n" " ],\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( linux_except_intel_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS); } TEST_F(GpuBlacklistTest, DateOnWindowsEntry) { // Blacklist all drivers earlier than 2010-01 in Windows. const std::string date_windows_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"win\"\n" " },\n" " \"driver_date\": {\n" " \"op\": \"<\",\n" " \"number\": \"2010.1\"\n" " },\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( date_windows_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS); } TEST_F(GpuBlacklistTest, MultipleDevicesEntry) { const std::string devices_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"vendor_id\": \"0x10de\",\n" " \"device_id\": [\"0x1023\", \"0x0640\"],\n" " \"blacklist\": [\n" " \"multisampling\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( devices_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_MULTISAMPLING); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_MULTISAMPLING); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_MULTISAMPLING); } TEST_F(GpuBlacklistTest, ChromeOSEntry) { const std::string devices_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"chromeos\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( devices_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsChromeOS, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); } TEST_F(GpuBlacklistTest, ChromeVersionEntry) { const std::string browser_version_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"browser_version\": {\n" " \"op\": \">=\",\n" " \"number\": \"10\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist9(Create()); EXPECT_TRUE(blacklist9->LoadGpuBlacklist( "9.0", browser_version_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist9->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); scoped_ptr<GpuBlacklist> blacklist10(Create()); EXPECT_TRUE(blacklist10->LoadGpuBlacklist( "10.0", browser_version_json, GpuBlacklist::kAllOs)); type = blacklist10->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, MalformedVendor) { // vendor_id is defined as list instead of string. const std::string malformed_vendor_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"vendor_id\": \"[0x10de]\",\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " }\n" " ]\n" "}"; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_FALSE(blacklist->LoadGpuBlacklist( malformed_vendor_json, GpuBlacklist::kAllOs)); } TEST_F(GpuBlacklistTest, UnknownField) { const std::string unknown_field_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"unknown_field\": 0,\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " },\n" " {\n" " \"id\": 2,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( unknown_field_json, GpuBlacklist::kAllOs)); EXPECT_EQ(1u, blacklist->num_entries()); EXPECT_TRUE(blacklist->contains_unknown_fields()); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, UnknownExceptionField) { const std::string unknown_exception_field_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"unknown_field\": 0,\n" " \"blacklist\": [\n" " \"accelerated_compositing\"\n" " ]\n" " },\n" " {\n" " \"id\": 2,\n" " \"exceptions\": [\n" " {\n" " \"unknown_field\": 0\n" " }\n" " ],\n" " \"blacklist\": [\n" " \"accelerated_2d_canvas\"\n" " ]\n" " },\n" " {\n" " \"id\": 3,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( unknown_exception_field_json, GpuBlacklist::kAllOs)); EXPECT_EQ(1u, blacklist->num_entries()); EXPECT_TRUE(blacklist->contains_unknown_fields()); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, UnknownFeature) { const std::string unknown_feature_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"blacklist\": [\n" " \"accelerated_something\",\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( unknown_feature_json, GpuBlacklist::kAllOs)); EXPECT_EQ(1u, blacklist->num_entries()); EXPECT_TRUE(blacklist->contains_unknown_fields()); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, GlVendor) { const std::string gl_vendor_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"gl_vendor\": {\n" " \"op\": \"beginwith\",\n" " \"value\": \"NVIDIA\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( gl_vendor_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, GlRenderer) { const std::string gl_renderer_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"gl_renderer\": {\n" " \"op\": \"contains\",\n" " \"value\": \"GeForce\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( gl_renderer_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, PerfGraphics) { const std::string json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"perf_graphics\": {\n" " \"op\": \"<\",\n" " \"value\": \"6.0\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist(json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, PerfGaming) { const std::string json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"perf_gaming\": {\n" " \"op\": \"<=\",\n" " \"value\": \"4.0\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist(json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); } TEST_F(GpuBlacklistTest, PerfOverall) { const std::string json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"perf_overall\": {\n" " \"op\": \"between\",\n" " \"value\": \"1.0\",\n" " \"value2\": \"9.0\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist(json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, DisabledEntry) { const std::string disabled_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"disabled\": true,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( disabled_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, 0); std::vector<uint32> flag_entries; bool disabled = false; blacklist->GetDecisionEntries(flag_entries, disabled); EXPECT_EQ(flag_entries.size(), 0u); disabled = true; blacklist->GetDecisionEntries(flag_entries, disabled); EXPECT_EQ(flag_entries.size(), 1u); } TEST_F(GpuBlacklistTest, Optimus) { const std::string optimus_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"multi_gpu_style\": \"optimus\",\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); content::GPUInfo gpu_info; gpu_info.optimus = true; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( optimus_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, AMDSwitchable) { const std::string amd_switchable_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"macosx\"\n" " },\n" " \"multi_gpu_style\": \"amd_switchable\",\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); content::GPUInfo gpu_info; gpu_info.amd_switchable = true; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( amd_switchable_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, LexicalDriverVersion) { const std::string lexical_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"vendor_id\": \"0x1002\",\n" " \"driver_version\": {\n" " \"op\": \"<\",\n" " \"style\": \"lexical\",\n" " \"number\": \"8.201\"\n" " },\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); content::GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x1002; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( lexical_json, GpuBlacklist::kAllOs)); gpu_info.driver_version = "8.109"; GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); gpu_info.driver_version = "8.2"; type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); gpu_info.driver_version = "8.21"; type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, 0); gpu_info.driver_version = "8.2010"; type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, 0); } TEST_F(GpuBlacklistTest, MultipleGPUsAny) { const std::string multi_gpu_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"macosx\"\n" " },\n" " \"vendor_id\": \"0x8086\",\n" " \"device_id\": [\"0x0166\"],\n" " \"multi_gpu_category\": \"any\",\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); content::GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0fd5; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( multi_gpu_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, 0); content::GPUInfo::GPUDevice gpu_device; gpu_device.vendor_id = 0x8086; gpu_device.device_id = 0x0166; gpu_info.secondary_gpus.push_back(gpu_device); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, MultipleGPUsSecondary) { const std::string multi_gpu_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"macosx\"\n" " },\n" " \"vendor_id\": \"0x8086\",\n" " \"device_id\": [\"0x0166\"],\n" " \"multi_gpu_category\": \"secondary\",\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); content::GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0fd5; scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( multi_gpu_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, 0); content::GPUInfo::GPUDevice gpu_device; gpu_device.vendor_id = 0x8086; gpu_device.device_id = 0x0166; gpu_info.secondary_gpus.push_back(gpu_device); type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL); } TEST_F(GpuBlacklistTest, GpuSwitching) { const std::string gpu_switching_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"macosx\"\n" " },\n" " \"gpu_switching\": \"force_discrete\"\n" " },\n" " {\n" " \"id\": 2,\n" " \"os\": {\n" " \"type\": \"win\"\n" " },\n" " \"gpu_switching\": \"force_integrated\"\n" " },\n" " {\n" " \"id\": 3,\n" " \"os\": {\n" " \"type\": \"linux\"\n" " },\n" " \"gpu_switching\": \"automatic\"\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( gpu_switching_json, GpuBlacklist::kAllOs)); GpuSwitchingOption switching = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).gpu_switching; EXPECT_EQ(switching, content::GPU_SWITCHING_OPTION_FORCE_DISCRETE); std::vector<uint32> entries; bool disabled = false; blacklist->GetDecisionEntries(entries, disabled); EXPECT_EQ(entries.size(), 1u); EXPECT_EQ(entries[0], 1u); blacklist.reset(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( gpu_switching_json, GpuBlacklist::kAllOs)); switching = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsWin, &os_version, gpu_info()).gpu_switching; EXPECT_EQ(switching, content::GPU_SWITCHING_OPTION_FORCE_INTEGRATED); blacklist->GetDecisionEntries(entries, disabled); EXPECT_EQ(entries.size(), 1u); EXPECT_EQ(entries[0], 2u); blacklist.reset(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( gpu_switching_json, GpuBlacklist::kAllOs)); switching = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsLinux, &os_version, gpu_info()).gpu_switching; EXPECT_EQ(switching, content::GPU_SWITCHING_OPTION_AUTOMATIC); blacklist->GetDecisionEntries(entries, disabled); EXPECT_EQ(entries.size(), 1u); EXPECT_EQ(entries[0], 3u); } TEST_F(GpuBlacklistTest, VideoDecode) { const std::string video_decode_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"os\": {\n" " \"type\": \"macosx\"\n" " },\n" " \"vendor_id\": \"0x10de\",\n" " \"device_id\": [\"0x0640\"],\n" " \"blacklist\": [\n" " \"accelerated_video_decode\"\n" " ]\n" " }\n" " ]\n" "}"; Version os_version("10.6.4"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist( video_decode_json, GpuBlacklist::kAllOs)); GpuFeatureType type = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info()).blacklisted_features; EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE); } TEST_F(GpuBlacklistTest, DualGpuModel) { const std::string model_json = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"0.1\",\n" " \"entries\": [\n" " {\n" " \"id\": 5,\n" " \"os\": {\n" " \"type\": \"macosx\",\n" " \"version\": {\n" " \"op\": \">=\",\n" " \"number\": \"10.7\"\n" " }\n" " },\n" " \"machine_model\": {\n" " \"name\": {\n" " \"op\": \"=\",\n" " \"value\": \"MacBookPro\"\n" " },\n" " \"version\": {\n" " \"op\": \"<\",\n" " \"number\": \"8\"\n" " }\n" " },\n" " \"gpu_count\": {\n" " \"op\": \"=\",\n" " \"value\": \"2\"\n" " },\n" " \"gpu_switching\": \"force_discrete\"\n" " }\n" " ]\n" "}"; Version os_version("10.7"); scoped_ptr<GpuBlacklist> blacklist(Create()); EXPECT_TRUE(blacklist->LoadGpuBlacklist(model_json, GpuBlacklist::kAllOs)); // Setup model name and version. blacklist->SetCurrentMachineModelInfoForTesting("MacBookPro", "7.1"); // Insert a second GPU. content::GPUInfo gpu_info; gpu_info.secondary_gpus.push_back(content::GPUInfo::GPUDevice()); GpuSwitchingOption switching = blacklist->MakeBlacklistDecision( GpuBlacklist::kOsMacosx, &os_version, gpu_info).gpu_switching; EXPECT_EQ(switching, content::GPU_SWITCHING_OPTION_FORCE_DISCRETE); }
31.652098
77
0.567385
[ "vector", "model" ]
b1e603447faff7146de7f945032fd4d4c3fa4b7f
4,227
cpp
C++
tools/cpp/testModel.cpp
shiyuan0806/MNN
0726ce33cc9f6c843c38c3e76f7e4621fcbf1303
[ "Apache-2.0" ]
null
null
null
tools/cpp/testModel.cpp
shiyuan0806/MNN
0726ce33cc9f6c843c38c3e76f7e4621fcbf1303
[ "Apache-2.0" ]
null
null
null
tools/cpp/testModel.cpp
shiyuan0806/MNN
0726ce33cc9f6c843c38c3e76f7e4621fcbf1303
[ "Apache-2.0" ]
null
null
null
// // testModel.cpp // MNN // // Created by MNN on 2019/01/22. // Copyright © 2018, Alibaba Group Holding Limited // #define MNN_OPEN_TIME_TRACE #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fstream> #include <map> #include <sstream> #include <MNN/AutoTime.hpp> #include "core/Backend.hpp" #include <MNN/Interpreter.hpp> #include <MNN/MNNDefine.h> #include "core/Macro.h" #include <MNN/Tensor.hpp> #include "core/TensorUtils.hpp" #define NONE "\e[0m" #define RED "\e[0;31m" #define GREEN "\e[0;32m" #define L_GREEN "\e[1;32m" #define BLUE "\e[0;34m" #define L_BLUE "\e[1;34m" #define BOLD "\e[1m" MNN::Tensor* createTensor(const MNN::Tensor* shape, const char* path) { std::ifstream stream(path); if (stream.fail()) { return NULL; } auto result = new MNN::Tensor(shape, shape->getDimensionType()); auto data = result->host<float>(); for (int i = 0; i < result->elementSize(); ++i) { double temp = 0.0f; stream >> temp; data[i] = temp; } stream.close(); return result; } int main(int argc, const char* argv[]) { // check given & expect const char* modelPath = argv[1]; const char* givenName = argv[2]; const char* expectName = argv[3]; MNN_PRINT("Testing model %s, input: %s, output: %s\n", modelPath, givenName, expectName); // create net auto type = MNN_FORWARD_CPU; if (argc > 4) { type = (MNNForwardType)::atoi(argv[4]); } auto tolerance = 0.1f; if (argc > 5) { tolerance = ::atof(argv[5]); } std::shared_ptr<MNN::Interpreter> net = std::shared_ptr<MNN::Interpreter>(MNN::Interpreter::createFromFile(modelPath)); // create session MNN::ScheduleConfig config; config.type = type; MNN::BackendConfig backendConfig; backendConfig.precision = MNN::BackendConfig::Precision_High; config.backendConfig = &backendConfig; auto session = net->createSession(config); auto allInput = net->getSessionInputAll(session); for (auto& iter : allInput) { auto size = iter.second->size(); auto ptr = iter.second->host<void>(); std::shared_ptr<MNN::Tensor> tempTensor; if (nullptr == ptr) { tempTensor = std::shared_ptr<MNN::Tensor>(MNN::Tensor::createHostTensorFromDevice(iter.second, false), [&iter](void* t) { auto hostTensor = (MNN::Tensor*)t; iter.second->copyFromHostTensor(hostTensor); delete hostTensor; }); ptr = tempTensor->host<float>(); } ::memset(ptr, 0, size); } // write input tensor auto inputTensor = net->getSessionInput(session, NULL); auto givenTensor = createTensor(inputTensor, givenName); if (!givenTensor) { #if defined(_MSC_VER) printf("Failed to open input file %s.\n", givenName); #else printf(RED "Failed to open input file %s.\n" NONE, givenName); #endif return -1; } inputTensor->copyFromHostTensor(givenTensor); delete givenTensor; // infer net->runSession(session); // read expect tensor auto outputTensor = net->getSessionOutput(session, NULL); std::shared_ptr<MNN::Tensor> expectTensor(createTensor(outputTensor, expectName)); if (!expectTensor.get()) { #if defined(_MSC_VER) printf("Failed to open expect file %s.\n", expectName); #else printf(RED "Failed to open expect file %s.\n" NONE, expectName); #endif return -1; } // compare output with expect bool correct = MNN::TensorUtils::compareTensors(outputTensor, expectTensor.get(), tolerance, true); if (correct) { #if defined(_MSC_VER) printf("Test %s Correct!\n", modelPath); #else printf(GREEN BOLD "Test %s Correct!\n" NONE, modelPath); #endif } else { #if defined(_MSC_VER) printf("Test Failed %s!\n", modelPath); #else printf(RED "Test Failed %s!\n" NONE, modelPath); #endif } return 0; }
29.978723
114
0.594275
[ "shape", "model" ]
b1ebb0200b30cc9bddbe1c19fa26bd156a050d2d
1,911
cpp
C++
chapter_3_generic_programming/ex_3_generic_stack.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_3_generic_programming/ex_3_generic_stack.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_3_generic_programming/ex_3_generic_stack.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
// // Created by Josh Levy-Kramer on 25/03/2020. // #include <memory> #include <vector> #include <exception> // Exercises 3 and 8 class EmptyStack: public std::exception { virtual const char* what() const throw() { return "The stack is empty."; } } emptystack; class FullStack: public std::exception { virtual const char* what() const throw() { return "The stack is full."; } } fullstack; template <typename T> class GenericStack { public: GenericStack (unsigned int max_size = 4096): max_size(max_size) { stack = std::unique_ptr<T[]>(new T[max_size]); size = 0; } T& top () { if (size == 0) { throw emptystack; } return stack[size-1]; } void pop () { if (size == 0) { throw emptystack; } size = size -1; } void push (T e) { if (size == max_size) { throw fullstack; } size = size + 1; stack[size] = e; } void clear () { if (size == 0) { throw emptystack; } size = 0; } auto sizeOf () { return size; } bool full () { return size == max_size; } bool empty () { return size == 0; } private: unsigned int max_size; unsigned int size; std::unique_ptr<T[]> stack; // Using a unique_pointer array instead of vector to make it harder }; // Explicit instantiation of class for different types template class GenericStack<double>; template class GenericStack<bool>; template class GenericStack<std::vector<double>>; int main () { GenericStack<bool> bool_stack = GenericStack<bool>(10); bool_stack.push(1); return 0; }
20.771739
103
0.508634
[ "vector" ]
b1ec1dc37f85307c83adbb1eb2d603238b4a8747
37,031
cpp
C++
llvm/lib/Transforms/Tapir/OpenCilkABI.cpp
JacobMarksLANL/kitsune
8f00e5c73f3bcb8984dfdc97a3173c0896579805
[ "MIT" ]
null
null
null
llvm/lib/Transforms/Tapir/OpenCilkABI.cpp
JacobMarksLANL/kitsune
8f00e5c73f3bcb8984dfdc97a3173c0896579805
[ "MIT" ]
null
null
null
llvm/lib/Transforms/Tapir/OpenCilkABI.cpp
JacobMarksLANL/kitsune
8f00e5c73f3bcb8984dfdc97a3173c0896579805
[ "MIT" ]
null
null
null
//===- OpenCilkABI.cpp - Interface to the OpenCilk runtime system------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the OpenCilk ABI to converts Tapir instructions to calls // into the OpenCilk runtime system. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Tapir/OpenCilkABI.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringSet.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/TapirTaskInfo.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Linker/Linker.h" #include "llvm/Support/Process.h" #include "llvm/Transforms/Tapir/CilkRTSCilkFor.h" #include "llvm/Transforms/Tapir/Outline.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/EscapeEnumerator.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Transforms/Utils/TapirUtils.h" #include "llvm/Support/Process.h" using namespace llvm; #define DEBUG_TYPE "opencilk" extern cl::opt<bool> DebugABICalls; static cl::opt<bool> UseOpenCilkRuntimeBC( "use-opencilk-runtime-bc", cl::init(true), cl::desc("Use a bitcode file for the OpenCilk runtime ABI"), cl::Hidden); static cl::opt<std::string> ClOpenCilkRuntimeBCPath( "opencilk-runtime-bc-path", cl::init(""), cl::desc("Path to the bitcode file for the OpenCilk runtime ABI"), cl::Hidden); #define CILKRTS_FUNC(name) Get__cilkrts_##name() static const StringRef StackFrameName = "__cilkrts_sf"; OpenCilkABI::OpenCilkABI(Module &M) : TapirTarget(M) {} // Helper function to fix the implementation of __cilk_sync. In particular, // this fixup ensures that __cilk_sync, and specific __cilkrts method calls // therein, appear that they may throw an exception. Since the bitcode-ABI file // is built from C code, it won't necessarily be marked appropriately for // exception handling. static void fixCilkSyncFn(Module &M, Function *Fn) { Fn->removeFnAttr(Attribute::NoUnwind); Function *ExceptionRaiseFn = M.getFunction("__cilkrts_check_exception_raise"); Function *ExceptionResumeFn = M.getFunction("__cilkrts_check_exception_resume"); for (Instruction &I : instructions(Fn)) if (CallBase *CB = dyn_cast<CallBase>(&I)) if (CB->getCalledFunction() == ExceptionRaiseFn || CB->getCalledFunction() == ExceptionResumeFn) CB->removeAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind); } // Structure recording information about Cilk ABI functions. struct CilkRTSFnDesc { StringRef FnName; FunctionType *FnType; FunctionCallee &FnCallee; }; void OpenCilkABI::setOptions(const TapirTargetOptions &Options) { if (!isa<OpenCilkABIOptions>(Options)) return; const OpenCilkABIOptions &OptionsCast = cast<OpenCilkABIOptions>(Options); // Get the path to the runtime bitcode file. RuntimeBCPath = OptionsCast.getRuntimeBCPath(); } void OpenCilkABI::prepareModule() { LLVMContext &C = M.getContext(); Type *Int8Ty = Type::getInt8Ty(C); Type *Int16Ty = Type::getInt16Ty(C); Type *Int32Ty = Type::getInt32Ty(C); Type *Int64Ty = Type::getInt64Ty(C); if (UseOpenCilkRuntimeBC) { // If a runtime bitcode path is given via the command line, use it. if ("" != ClOpenCilkRuntimeBCPath) RuntimeBCPath = ClOpenCilkRuntimeBCPath; Optional<std::string> path; if("" == RuntimeBCPath){ path = sys::Process::FindInEnvPath("LD_LIBRARY_PATH", "libopencilk-abi.bc"); if (! path.hasValue()) // TODO: This is an in-tree build solution for now... #if defined(OPENCILK_BC_PATH) path = OPENCILK_BC_PATH; #else report_fatal_error("Could not find OpenCilk runtime bitcode file " "(libopencilk-abi.bc) in LD_LIBRARY_PATH."); #endif } else { path = ClOpenCilkRuntimeBCPath.getValue(); } LLVM_DEBUG(dbgs() << "Using external bitcode file for OpenCilk ABI: " << path << "\n"); SMDiagnostic SMD; // Parse the bitcode file. This call imports structure definitions, but not // function definitions. std::unique_ptr<Module> ExternalModule = parseIRFile(RuntimeBCPath, SMD, C); if (!ExternalModule) C.emitError("OpenCilkABI: Failed to parse bitcode ABI file: " + Twine(RuntimeBCPath)); // Strip any debug info from the external module. For convenience, this // Tapir target synthesizes some helper functions, like // __cilk_parent_epilogue, that contain calls to these functions, but don't // necessarily have debug info. As a result, debug info in the external // module causes failures during subsequent inlining. StripDebugInfo(*ExternalModule); // Link the external module into the current module, copying over global // values. // // TODO: Consider restructuring the import process to use // Linker::Flags::LinkOnlyNeeded to copy over only the necessary contents // from the external module. bool Fail = Linker::linkModules( M, std::move(ExternalModule), Linker::Flags::None, [](Module &M, const StringSet<> &GVS) { for (StringRef GVName : GVS.keys()) { LLVM_DEBUG(dbgs() << "Linking global value " << GVName << "\n"); if (Function *Fn = M.getFunction(GVName)) { if (!Fn->isDeclaration()) // We set the function's linkage as available_externally, so // that subsequent optimizations can remove these definitions // from the module. We don't want this module redefining any of // these symbols, even if they aren't inlined, because the // OpenCilk runtime library will provide those definitions // later. Fn->setLinkage(Function::AvailableExternallyLinkage); } } }); if (Fail) C.emitError("OpenCilkABI: Failed to link bitcode ABI file: " + Twine(RuntimeBCPath)); } // Get or create local definitions of Cilk RTS structure types. const char *StackFrameName = "struct.__cilkrts_stack_frame"; StackFrameTy = StructType::lookupOrCreate(C, StackFrameName); WorkerTy = StructType::lookupOrCreate(C, "struct.__cilkrts_worker"); PointerType *StackFramePtrTy = PointerType::getUnqual(StackFrameTy); Type *VoidTy = Type::getVoidTy(C); // Define the types of the CilkRTS functions. FunctionType *CilkRTSFnTy = FunctionType::get(VoidTy, {StackFramePtrTy}, false); FunctionType *CilkPrepareSpawnFnTy = FunctionType::get(Int32Ty, {StackFramePtrTy}, false); FunctionType *CilkRTSEnterLandingpadFnTy = FunctionType::get(VoidTy, {StackFramePtrTy, Int32Ty}, false); FunctionType *CilkRTSPauseFrameFnTy = FunctionType::get( VoidTy, {StackFramePtrTy, PointerType::getInt8PtrTy(C)}, false); FunctionType *Grainsize8FnTy = FunctionType::get(Int8Ty, {Int8Ty}, false); FunctionType *Grainsize16FnTy = FunctionType::get(Int16Ty, {Int16Ty}, false); FunctionType *Grainsize32FnTy = FunctionType::get(Int32Ty, {Int32Ty}, false); FunctionType *Grainsize64FnTy = FunctionType::get(Int64Ty, {Int64Ty}, false); // Create an array of CilkRTS functions, with their associated types and // FunctionCallee member variables in the OpenCilkABI class. SmallVector<CilkRTSFnDesc, 17> CilkRTSFunctions({ {"__cilkrts_enter_frame", CilkRTSFnTy, CilkRTSEnterFrame}, {"__cilkrts_enter_frame_helper", CilkRTSFnTy, CilkRTSEnterFrameHelper}, {"__cilkrts_detach", CilkRTSFnTy, CilkRTSDetach}, {"__cilkrts_leave_frame", CilkRTSFnTy, CilkRTSLeaveFrame}, {"__cilkrts_leave_frame_helper", CilkRTSFnTy, CilkRTSLeaveFrameHelper}, {"__cilk_prepare_spawn", CilkPrepareSpawnFnTy, CilkPrepareSpawn}, {"__cilk_sync", CilkRTSFnTy, CilkSync}, {"__cilk_sync_nothrow", CilkRTSFnTy, CilkSyncNoThrow}, {"__cilk_parent_epilogue", CilkRTSFnTy, CilkParentEpilogue}, {"__cilk_helper_epilogue", CilkRTSFnTy, CilkHelperEpilogue}, {"__cilkrts_enter_landingpad", CilkRTSEnterLandingpadFnTy, CilkRTSEnterLandingpad}, {"__cilkrts_pause_frame", CilkRTSPauseFrameFnTy, CilkRTSPauseFrame}, {"__cilk_helper_epilogue_exn", CilkRTSPauseFrameFnTy, CilkHelperEpilogueExn}, {"__cilkrts_cilk_for_grainsize_8", Grainsize8FnTy, CilkRTSCilkForGrainsize8}, {"__cilkrts_cilk_for_grainsize_16", Grainsize16FnTy, CilkRTSCilkForGrainsize16}, {"__cilkrts_cilk_for_grainsize_32", Grainsize32FnTy, CilkRTSCilkForGrainsize32}, {"__cilkrts_cilk_for_grainsize_64", Grainsize64FnTy, CilkRTSCilkForGrainsize64}, }); if (UseOpenCilkRuntimeBC) { // Add attributes to internalized functions. for (CilkRTSFnDesc FnDesc : CilkRTSFunctions) { assert(!FnDesc.FnCallee && "Redefining Cilk function"); FnDesc.FnCallee = M.getOrInsertFunction(FnDesc.FnName, FnDesc.FnType); assert(isa<Function>(FnDesc.FnCallee.getCallee()) && "Cilk function is not a function"); Function *Fn = cast<Function>(FnDesc.FnCallee.getCallee()); // Because __cilk_sync is a C function that can throw an exception, update // its attributes specially. No other CilkRTS functions can throw an // exception. if ("__cilk_sync" == FnDesc.FnName) fixCilkSyncFn(M, Fn); else Fn->setDoesNotThrow(); // Unless we're debugging, mark the function as always_inline. This // attribute is required for some functions, but is helpful for all // functions. if (!DebugABICalls) Fn->addFnAttr(Attribute::AlwaysInline); else Fn->removeFnAttr(Attribute::AlwaysInline); } } else if (DebugABICalls) { if (StackFrameTy->isOpaque()) { // Create a dummy __cilkrts_stack_frame structure, for debugging purposes // only. StackFrameTy->setBody(Int64Ty); } // Create declarations of all CilkRTS functions, and add basic attributes to // those declarations. for (CilkRTSFnDesc FnDesc : CilkRTSFunctions) { assert(!FnDesc.FnCallee && "Redefining Cilk function"); FnDesc.FnCallee = M.getOrInsertFunction(FnDesc.FnName, FnDesc.FnType); assert(isa<Function>(FnDesc.FnCallee.getCallee()) && "Cilk function is not a function"); Function *Fn = cast<Function>(FnDesc.FnCallee.getCallee()); // Mark all CilkRTS functions nounwind, except for __cilk_sync. if ("__cilk_sync" == FnDesc.FnName) Fn->removeFnAttr(Attribute::NoUnwind); else Fn->setDoesNotThrow(); } } else { // The OpenCilkABI target requires the use of a bitcode ABI file to generate // correct code. C.emitError( "OpenCilkABI: Bitcode ABI file required for correct code generation."); } } void OpenCilkABI::addHelperAttributes(Function &Helper) { // Use a fast calling convention for the helper. Helper.setCallingConv(CallingConv::Fast); // Inlining the helper function is not legal. Helper.removeFnAttr(Attribute::AlwaysInline); Helper.addFnAttr(Attribute::NoInline); // If the helper uses an argument structure, then it is not a write-only // function. if (getArgStructMode() != ArgStructMode::None) { Helper.removeFnAttr(Attribute::WriteOnly); Helper.removeFnAttr(Attribute::ArgMemOnly); Helper.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly); } // Note that the address of the helper is unimportant. Helper.setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // The helper is internal to this module. We use internal linkage, rather // than private linkage, so that tools can still reference the helper // function. Helper.setLinkage(GlobalValue::InternalLinkage); } void OpenCilkABI::remapAfterOutlining(BasicBlock *TFEntry, ValueToValueMapTy &VMap) { if (TapirRTCalls[TFEntry].empty()) return; // Update the set of tapir.runtime.{start,end} intrinsics in the taskframe // rooted at TFEntry to process. SmallVector<IntrinsicInst *, 4> OldTapirRTCalls(TapirRTCalls[TFEntry]); TapirRTCalls[TFEntry].clear(); for (IntrinsicInst *II : OldTapirRTCalls) TapirRTCalls[TFEntry].push_back(cast<IntrinsicInst>(VMap[II])); } // Check whether the allocation of a __cilkrts_stack_frame can be inserted after // instruction \p I. static bool skipInstruction(const Instruction &I) { if (isa<AllocaInst>(I)) return true; if (isa<DbgInfoIntrinsic>(I)) return true; if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) { // Skip simple intrinsics switch(II->getIntrinsicID()) { case Intrinsic::annotation: case Intrinsic::assume: case Intrinsic::sideeffect: case Intrinsic::invariant_start: case Intrinsic::invariant_end: case Intrinsic::launder_invariant_group: case Intrinsic::strip_invariant_group: case Intrinsic::is_constant: case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: case Intrinsic::objectsize: case Intrinsic::ptr_annotation: case Intrinsic::var_annotation: case Intrinsic::experimental_gc_result: case Intrinsic::experimental_gc_relocate: case Intrinsic::experimental_noalias_scope_decl: case Intrinsic::syncregion_start: case Intrinsic::taskframe_create: return true; default: return false; } } return false; } // Scan the basic block \p B to find a point to insert the allocation of a // __cilkrts_stack_frame. static Instruction *getStackFrameInsertPt(BasicBlock &B) { BasicBlock::iterator BI(B.getFirstInsertionPt()); BasicBlock::const_iterator BE(B.end()); // Scan the basic block for the first instruction we should not skip. while (BI != BE) { if (!skipInstruction(*BI)) { return &*BI; } ++BI; } // We reached the end of the basic block; return the terminator. return B.getTerminator(); } /// Create the __cilkrts_stack_frame for the spawning function. Value *OpenCilkABI::CreateStackFrame(Function &F) { const DataLayout &DL = F.getParent()->getDataLayout(); Type *SFTy = StackFrameTy; IRBuilder<> B(getStackFrameInsertPt(F.getEntryBlock())); AllocaInst *SF = B.CreateAlloca(SFTy, DL.getAllocaAddrSpace(), /*ArraySize*/ nullptr, /*Name*/ StackFrameName); SF->setAlignment(Align(8)); return SF; } Value* OpenCilkABI::GetOrCreateCilkStackFrame(Function &F) { if (DetachCtxToStackFrame.count(&F)) return DetachCtxToStackFrame[&F]; Value *SF = CreateStackFrame(F); DetachCtxToStackFrame[&F] = SF; return SF; } // Insert a call in Function F to __cilkrts_detach at DetachPt, which must be // after the allocation of the __cilkrts_stack_frame in F. void OpenCilkABI::InsertDetach(Function &F, Instruction *DetachPt) { Instruction *SF = cast<Instruction>(GetOrCreateCilkStackFrame(F)); assert(SF && "No Cilk stack frame for Cilk function."); Value *Args[1] = {SF}; // Scan function to see if it detaches. LLVM_DEBUG({ bool SimpleHelper = !canDetach(&F); if (!SimpleHelper) dbgs() << "NOTE: Detachable helper function itself detaches.\n"; }); // Call __cilkrts_detach IRBuilder<> IRB(DetachPt); IRB.CreateCall(CILKRTS_FUNC(detach), Args); } // Insert a call in Function F to __cilkrts_enter_frame{_helper} to initialize // the __cilkrts_stack_frame in F. If TaskFrameCreate is nonnull, the call to // __cilkrts_enter_frame{_helper} is inserted at TaskFramecreate. CallInst *OpenCilkABI::InsertStackFramePush(Function &F, Instruction *TaskFrameCreate, bool Helper) { Instruction *SF = cast<Instruction>(GetOrCreateCilkStackFrame(F)); BasicBlock::iterator InsertPt = ++SF->getIterator(); IRBuilder<> B(&(F.getEntryBlock()), InsertPt); if (TaskFrameCreate) B.SetInsertPoint(TaskFrameCreate); Value *Args[1] = {SF}; if (Helper) return B.CreateCall(CILKRTS_FUNC(enter_frame_helper), Args); else return B.CreateCall(CILKRTS_FUNC(enter_frame), Args); } // Insert a call in Function F to the appropriate epilogue function. // // - A call to __cilk_parent_epilogue() is inserted at a return from a // spawning function. // // - A call to __cilk_helper_epilogue() is inserted at a return from a // spawn-helper function. // // - A call to __cilk_helper_epiluge_exn() is inserted at a resume from a // spawn-helper function. // // PromoteCallsToInvokes dictates whether call instructions that can throw are // promoted to invoke instructions prior to inserting the epilogue-function // calls. void OpenCilkABI::InsertStackFramePop(Function &F, bool PromoteCallsToInvokes, bool InsertPauseFrame, bool Helper) { Value *SF = GetOrCreateCilkStackFrame(F); SmallPtrSet<ReturnInst *, 8> Returns; SmallPtrSet<ResumeInst *, 8> Resumes; // Add eh cleanup that returns control to the runtime EscapeEnumerator EE(F, "cilkrabi_cleanup", PromoteCallsToInvokes); while (IRBuilder<> *Builder = EE.Next()) { if (ResumeInst *RI = dyn_cast<ResumeInst>(Builder->GetInsertPoint())) Resumes.insert(RI); else if (ReturnInst *RI = dyn_cast<ReturnInst>(Builder->GetInsertPoint())) Returns.insert(RI); } for (ReturnInst *RI : Returns) { if (Helper) { CallInst::Create(GetCilkHelperEpilogueFn(), {SF}, "", RI); } else { CallInst::Create(GetCilkParentEpilogueFn(), {SF}, "", RI); } } for (ResumeInst *RI : Resumes) { if (InsertPauseFrame) { Value *Exn = ExtractValueInst::Create(RI->getValue(), {0}, "", RI); // If throwing an exception, pass the exception object to the epilogue // function. CallInst::Create(GetCilkHelperEpilogueExnFn(), {SF, Exn}, "", RI); } } } // Lower any calls to tapir.runtime.{start,end} that need to be processed. void OpenCilkABI::LowerTapirRTCalls(Function &F, BasicBlock *TFEntry) { Instruction *SF = cast<Instruction>(GetOrCreateCilkStackFrame(F)); for (IntrinsicInst *II : TapirRTCalls[TFEntry]) { IRBuilder<> Builder(II); if (Intrinsic::tapir_runtime_start == II->getIntrinsicID()) { // Lower calls to tapir.runtime.start to __cilkrts_enter_frame. Builder.CreateCall(CILKRTS_FUNC(enter_frame), {SF}); // Find all tapir.runtime.ends that use this tapir.runtime.start, and // lower them to calls to __cilk_parent_epilogue. for (Use &U : II->uses()) if (IntrinsicInst *UII = dyn_cast<IntrinsicInst>(U.getUser())) if (Intrinsic::tapir_runtime_end == UII->getIntrinsicID()) { Builder.SetInsertPoint(UII); Builder.CreateCall(GetCilkParentEpilogueFn(), {SF}); } } } } void OpenCilkABI::MarkSpawner(Function &F) { // If the spawner F might throw, then we mark F with the Cilk personality // function, which ensures that the Cilk stack frame of F is properly unwound. if (!F.doesNotThrow()) { LLVMContext &C = M.getContext(); // Get the type of the Cilk personality function the same way that clang and // EscapeEnumerator get the type of a personality function. Function *Personality = cast<Function>( M.getOrInsertFunction("__cilk_personality_v0", FunctionType::get(Type::getInt32Ty(C), true)) .getCallee()); F.setPersonalityFn(Personality); } // Mark this function as stealable. F.addFnAttr(Attribute::Stealable); F.removeFnAttr(Attribute::ArgMemOnly); } /// Lower a call to get the grainsize of a Tapir loop. Value *OpenCilkABI::lowerGrainsizeCall(CallInst *GrainsizeCall) { Value *Limit = GrainsizeCall->getArgOperand(0); IRBuilder<> Builder(GrainsizeCall); // Select the appropriate __cilkrts_grainsize function, based on the type. FunctionCallee CilkRTSGrainsizeCall; if (GrainsizeCall->getType()->isIntegerTy(8)) CilkRTSGrainsizeCall = CILKRTS_FUNC(cilk_for_grainsize_8); else if (GrainsizeCall->getType()->isIntegerTy(16)) CilkRTSGrainsizeCall = CILKRTS_FUNC(cilk_for_grainsize_16); else if (GrainsizeCall->getType()->isIntegerTy(32)) CilkRTSGrainsizeCall = CILKRTS_FUNC(cilk_for_grainsize_32); else if (GrainsizeCall->getType()->isIntegerTy(64)) CilkRTSGrainsizeCall = CILKRTS_FUNC(cilk_for_grainsize_64); else llvm_unreachable("No CilkRTSGrainsize call matches type for Tapir loop."); Value *Grainsize = Builder.CreateCall(CilkRTSGrainsizeCall, Limit); // Replace uses of grainsize intrinsic call with this grainsize value. GrainsizeCall->replaceAllUsesWith(Grainsize); return Grainsize; } // Lower a sync instruction SI. void OpenCilkABI::lowerSync(SyncInst &SI) { Function &Fn = *SI.getFunction(); if (!DetachCtxToStackFrame[&Fn]) // If we have not created a stackframe for this function, then we don't need // to handle the sync. return; Value *SF = GetOrCreateCilkStackFrame(Fn); Value *Args[] = { SF }; assert(Args[0] && "sync used in function without frame!"); Instruction *SyncUnwind = nullptr; BasicBlock *SyncCont = SI.getSuccessor(0); BasicBlock *SyncUnwindDest = nullptr; // Determine whether a sync.unwind immediately follows SI. if (InvokeInst *II = dyn_cast<InvokeInst>(SyncCont->getFirstNonPHIOrDbgOrLifetime())) { if (isSyncUnwind(II)) { SyncUnwind = II; SyncCont = II->getNormalDest(); SyncUnwindDest = II->getUnwindDest(); } } CallBase *CB; if (!SyncUnwindDest) { if (Fn.doesNotThrow()) CB = CallInst::Create(GetCilkSyncNoThrowFn(), Args, "", /*insert before*/ &SI); else CB = CallInst::Create(GetCilkSyncFn(), Args, "", /*insert before*/ &SI); BranchInst::Create(SyncCont, CB->getParent()); } else { CB = InvokeInst::Create(GetCilkSyncFn(), SyncCont, SyncUnwindDest, Args, "", /*insert before*/ &SI); for (PHINode &PN : SyncCont->phis()) PN.addIncoming(PN.getIncomingValueForBlock(SyncUnwind->getParent()), SI.getParent()); for (PHINode &PN : SyncUnwindDest->phis()) PN.addIncoming(PN.getIncomingValueForBlock(SyncUnwind->getParent()), SI.getParent()); } CB->setDebugLoc(SI.getDebugLoc()); SI.eraseFromParent(); // Remember to inline this call later. CallsToInline.insert(CB); // Mark this function as stealable. Fn.addFnAttr(Attribute::Stealable); } void OpenCilkABI::preProcessOutlinedTask(Function &F, Instruction *DetachPt, Instruction *TaskFrameCreate, bool IsSpawner, BasicBlock *TFEntry) { // If the outlined task F itself performs spawns, set up F to support stealing // continuations. if (IsSpawner) MarkSpawner(F); CallInst *EnterFrame = InsertStackFramePush(F, TaskFrameCreate, /*Helper*/ true); InsertDetach(F, (DetachPt ? DetachPt : &*(++EnterFrame->getIterator()))); } void OpenCilkABI::postProcessOutlinedTask(Function &F, Instruction *DetachPt, Instruction *TaskFrameCreate, bool IsSpawner, BasicBlock *TFEntry) { // Because F is a spawned task, we want to insert landingpads for all calls // that can throw, so we can pop the stackframe correctly if they do throw. // In particular, popping the stackframe of a spawned task may discover that // the parent was stolen, in which case we want to save the exception for // later reduction. InsertStackFramePop(F, /*PromoteCallsToInvokes*/ true, /*InsertPauseFrame*/ true, /*Helper*/ true); // TODO: If F is itself a spawner, see if we need to ensure that the Cilk // personality function does not pop an already-popped frame. We might be // able to do this by checking if sf->call_parent == NULL before performing a // pop in the personality function. } void OpenCilkABI::preProcessRootSpawner(Function &F, BasicBlock *TFEntry) { MarkSpawner(F); if (TapirRTCalls[TFEntry].empty()) { InsertStackFramePush(F); } else { LowerTapirRTCalls(F, TFEntry); } Value *SF = DetachCtxToStackFrame[&F]; for (BasicBlock &BB : F) { if (BB.isLandingPad()) { LandingPadInst *LPad = BB.getLandingPadInst(); Instruction *InsertPt = &*BB.getFirstInsertionPt(); IRBuilder<> Builder(InsertPt); Value *Sel = Builder.CreateExtractValue(LPad, 1, "sel"); Builder.CreateCall(CILKRTS_FUNC(enter_landingpad), {SF, Sel}); } } } void OpenCilkABI::postProcessRootSpawner(Function &F, BasicBlock *TFEntry) { // F is a root spawner, not itself a spawned task. We don't need to promote // calls to invokes, since the Cilk personality function will take care of // popping the frame if no landingpad exists for a given call. if (TapirRTCalls[TFEntry].empty()) InsertStackFramePop(F, /*PromoteCallsToInvokes*/ false, /*InsertPauseFrame*/ false, /*Helper*/ false); } void OpenCilkABI::processSubTaskCall(TaskOutlineInfo &TOI, DominatorTree &DT) { Instruction *ReplStart = TOI.ReplStart; Instruction *ReplCall = TOI.ReplCall; Function &F = *ReplCall->getFunction(); Value *SF = DetachCtxToStackFrame[&F]; assert(SF && "No frame found for spawning task"); // Split the basic block containing the detach replacement just before the // start of the detach-replacement instructions. BasicBlock *DetBlock = ReplStart->getParent(); BasicBlock *CallBlock = SplitBlock(DetBlock, ReplStart, &DT); // Emit a __cilk_spawn_prepare at the end of the block preceding the split-off // detach replacement. Instruction *SpawnPt = DetBlock->getTerminator(); IRBuilder<> B(SpawnPt); CallBase *SpawnPrepCall = B.CreateCall(GetCilkPrepareSpawnFn(), {SF}); // Remember to inline this call later. CallsToInline.insert(SpawnPrepCall); // Get the ordinary continuation of the detach. BasicBlock *CallCont; if (InvokeInst *II = dyn_cast<InvokeInst>(ReplCall)) CallCont = II->getNormalDest(); else // isa<CallInst>(CallSite) CallCont = CallBlock->getSingleSuccessor(); // Insert a conditional branch, based on the result of the // __cilk_spawn_prepare, to either the detach replacement or the continuation. Value *SpawnPrepRes = B.CreateICmpEQ( SpawnPrepCall, ConstantInt::get(SpawnPrepCall->getType(), 0)); B.CreateCondBr(SpawnPrepRes, CallBlock, CallCont); for (PHINode &PN : CallCont->phis()) PN.addIncoming(PN.getIncomingValueForBlock(CallBlock), DetBlock); SpawnPt->eraseFromParent(); } // Helper function to inline calls to compiler-generated Cilk Plus runtime // functions when possible. This inlining is necessary to properly implement // some Cilk runtime "calls," such as __cilk_sync(). static inline void inlineCilkFunctions( Function &F, SmallPtrSetImpl<CallBase *> &CallsToInline) { for (CallBase *CB : CallsToInline) { InlineFunctionInfo IFI; InlineFunction(*CB, IFI); } CallsToInline.clear(); } // For the taskframe at \p TFEntry containing blocks \p TFBlocks, find all // outermost tapir.runtime.{start,end} intrinsics, which are not enclosed // between other tapir.runtime.{start,end} intrinsics in this traksframe. // Furthermore, record and successor taskframes in \p SuccessorTFs that are not // enclosed between tapir.runtime.{start,end} intrinsics. static bool findOutermostTapirRTCallsForTaskFrame( SmallVectorImpl<IntrinsicInst *> &TapirRTCalls, BasicBlock *TFEntry, SmallPtrSetImpl<BasicBlock *> &TFBlocks, SmallPtrSetImpl<Spindle *> &SuccessorTFs, TaskInfo &TI) { SmallVector<BasicBlock::iterator, 8> Worklist; SmallPtrSet<BasicBlock *, 8> Visited; Worklist.push_back(TFEntry->begin()); while (!Worklist.empty()) { BasicBlock::iterator Iter = Worklist.pop_back_val(); BasicBlock *BB = Iter->getParent(); bool FoundTapirRTStart = false; bool FoundTapirRTEnd = false; SmallVector<BasicBlock::iterator, 4> EndIters; // Scan the BB for tapir_runtime calls. for (BasicBlock::iterator It = Iter, E = BB->end(); It != E; ++It) { Instruction *I = &*It; if (isTapirIntrinsic(Intrinsic::tapir_runtime_start, I)) { FoundTapirRTStart = true; TapirRTCalls.push_back(cast<IntrinsicInst>(I)); // Examine corresponding tapir_runtime_end intrinsics to find blocks // from which to continue search. for (Use &U : I->uses()) { if (Instruction *UI = dyn_cast<Instruction>(U.getUser())) { FoundTapirRTEnd = true; BasicBlock *EndBB = UI->getParent(); assert(TFBlocks.count(EndBB) && "tapir_runtime_end not in same " "taskframe as tapir_runtime_begin"); EndIters.push_back(++UI->getIterator()); } } if (FoundTapirRTEnd) // We found a tapir_runtime_begin in this block, so stop searching. break; } } // If we didn't find a tapir_runtime_start in this block, treat this block // as an end block, so we examine its direct successors. if (!FoundTapirRTStart) EndIters.push_back(BB->getTerminator()->getIterator()); // Examine all end blocks to 1) check if a spawn occurs, and 2) add // successors within the taskframe for further search. for (BasicBlock::iterator Iter : EndIters) { if (isa<DetachInst>(*Iter)) { // We found a spawn terminating a block in this taskframe. This spawn // is not contained between outermost tapir_runtime_{start,end} calls in // the taskframe. Therefore, we should fall back to default behavior // for inserting enter_frame and leave_frame calls for this taskframe. TapirRTCalls.clear(); return true; } BasicBlock *EndBB = Iter->getParent(); if (EndBB->getTerminator() != &*Iter) { Worklist.push_back(Iter); continue; } // Add the successors of this block for further search. for (BasicBlock *Succ : successors(EndBB)) { if (TFBlocks.count(Succ) && Visited.insert(Succ).second) // For successors within the taskframe, add them to the search. Worklist.push_back(Succ->begin()); else { // For successors in other taskframes, add the subtaskframe for // processing. Spindle *SuccSpindle = TI.getSpindleFor(Succ); if (SuccSpindle->getTaskFrameCreate()) SuccessorTFs.insert(SuccSpindle); } } } } return false; } // Find all tapir.runtime.{start,end} intrinsics to process for the taskframe // rooted at spindle \p TaskFrame and any subtaskframes thereof. void OpenCilkABI::GetTapirRTCalls(Spindle *TaskFrame, bool IsRootTask, TaskInfo &TI) { BasicBlock *TFEntry = TaskFrame->getEntry(); SmallPtrSet<BasicBlock *, 8> TFBlocks; SmallVector<Spindle *, 4> SubTFs; if (IsRootTask) { // We have to compute the effective taskframe blocks for the root task, // since these blocks are not automatically identified by TapirTaskInfo. // // Note: We could generalize TapirTaskInfo to compute these taskframe blocks // directly, but this computation seems to be the only place that set of // blocks is needed. SmallPtrSet<Spindle *, 4> ExcludedSpindles; // Exclude all spindles in unassociated taskframes under the root task. for (Spindle *TFRoot : TI.getRootTask()->taskframe_roots()) { if (!TFRoot->getTaskFromTaskFrame()) SubTFs.push_back(TFRoot); for (Spindle *TFSpindle : depth_first<TaskFrames<Spindle *>>(TFRoot)) { if (TFSpindle->getTaskFromTaskFrame()) continue; for (Spindle *S : TFSpindle->taskframe_spindles()) ExcludedSpindles.insert(S); } } // Iterate over the spindles in the root task, and add all spindle blocks to // TFBlocks as long as those blocks don't belong to a nested taskframe. for (Spindle *S : depth_first<InTask<Spindle *>>(TI.getRootTask()->getEntrySpindle())) { if (ExcludedSpindles.count(S)) continue; TFBlocks.insert(S->block_begin(), S->block_end()); } } else { // Add all blocks in all spindles associated with this taskframe. for (Spindle *S : TaskFrame->taskframe_spindles()) TFBlocks.insert(S->block_begin(), S->block_end()); for (Spindle *SubTF : TaskFrame->subtaskframes()) if (!SubTF->getTaskFromTaskFrame()) SubTFs.push_back(SubTF); } // Find the outermost tapir_runtime_{start,end} calls in this taskframe. // Record in SuccessorTFs any subtaskframes that are not enclosed in // tapir.runtime.{start,end} intrinsics. SmallPtrSet<Spindle *, 4> SuccessorTFs; bool TaskFrameSpawns = findOutermostTapirRTCallsForTaskFrame( TapirRTCalls[TFEntry], TFEntry, TFBlocks, SuccessorTFs, TI); // If this taskframe spawns outside of tapir_runtime_{start,end} pairs, then // the taskframe will start/end the runtime when executed. Hence there's no // need to evaluate subtaskframes. if (TaskFrameSpawns) return; // Process subtaskframes recursively. for (Spindle *SubTF : SubTFs) { // Skip any subtaskframes that are already enclosed in // tapir.runtime.{start,end} intrinsics. if (!SuccessorTFs.count(SubTF)) continue; // Skip any taskframes that are associated with subtasks. assert(!SubTF->getTaskFromTaskFrame() && "Should not be processing spawned taskframes."); GetTapirRTCalls(SubTF, false, TI); } } void OpenCilkABI::preProcessFunction(Function &F, TaskInfo &TI, bool ProcessingTapirLoops) { if (ProcessingTapirLoops) // Don't do any preprocessing when outlining Tapir loops. return; // Find all Tapir-runtime calls in this function that may be translated to // enter_frame/leave_frame calls. GetTapirRTCalls(TI.getRootTask()->getEntrySpindle(), true, TI); if (!TI.isSerial() || TapirRTCalls[&F.getEntryBlock()].empty()) return; MarkSpawner(F); LowerTapirRTCalls(F, &F.getEntryBlock()); } void OpenCilkABI::postProcessFunction(Function &F, bool ProcessingTapirLoops) { if (ProcessingTapirLoops) // Don't do any postprocessing when outlining Tapir loops. return; if (!DebugABICalls) inlineCilkFunctions(F, CallsToInline); } /// Process the Tapir instructions in an ordinary (non-spawning and not spawned) /// function \p F directly. bool OpenCilkABI::processOrdinaryFunction(Function &F, BasicBlock *TFEntry) { // Get the simple Tapir instructions to process, including syncs and // loop-grainsize calls. SmallVector<CallInst *, 8> GrainsizeCalls; SmallVector<CallInst *, 8> TaskFrameAddrCalls; for (BasicBlock &BB : F) { for (Instruction &I : BB) { // Record calls to get Tapir-loop grainsizes. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) if (Intrinsic::tapir_loop_grainsize == II->getIntrinsicID()) GrainsizeCalls.push_back(II); // Record calls to task_frameaddr intrinsics. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) if (Intrinsic::task_frameaddress == II->getIntrinsicID()) TaskFrameAddrCalls.push_back(II); } } // Lower simple Tapir instructions in this function. Collect the set of // helper functions generated by this process. bool Changed = false; // Lower calls to get Tapir-loop grainsizes. while (!GrainsizeCalls.empty()) { CallInst *GrainsizeCall = GrainsizeCalls.pop_back_val(); LLVM_DEBUG(dbgs() << "Lowering grainsize call " << *GrainsizeCall << "\n"); lowerGrainsizeCall(GrainsizeCall); Changed = true; } // Lower calls to task_frameaddr intrinsics. while (!TaskFrameAddrCalls.empty()) { CallInst *TaskFrameAddrCall = TaskFrameAddrCalls.pop_back_val(); LLVM_DEBUG(dbgs() << "Lowering task_frameaddr call " << *TaskFrameAddrCall << "\n"); lowerTaskFrameAddrCall(TaskFrameAddrCall); Changed = true; } // If any calls to tapir.runtime.{start,end} were found in this taskframe that // need processing, lower them now. if (!TapirRTCalls[TFEntry].empty()) LowerTapirRTCalls(F, TFEntry); return Changed; } void OpenCilkABI::postProcessHelper(Function &F) {} LoopOutlineProcessor * OpenCilkABI::getLoopOutlineProcessor(const TapirLoopInfo *TL) const { if (UseRuntimeCilkFor) return new RuntimeCilkFor(M); return nullptr; }
39.227754
82
0.688153
[ "object" ]
b1ef91eeaf0c4f5aed1230cbfb0f0c7a84c466f6
1,399
cpp
C++
PC_TercerExamen_23-dic-21/P12_Button_Bashing/P12_Button_Bashing.cpp
MisaelVM/ProgComp2021B
6134ae425a4c1a4f087bc1e14615d1f06979beff
[ "BSD-3-Clause" ]
null
null
null
PC_TercerExamen_23-dic-21/P12_Button_Bashing/P12_Button_Bashing.cpp
MisaelVM/ProgComp2021B
6134ae425a4c1a4f087bc1e14615d1f06979beff
[ "BSD-3-Clause" ]
null
null
null
PC_TercerExamen_23-dic-21/P12_Button_Bashing/P12_Button_Bashing.cpp
MisaelVM/ProgComp2021B
6134ae425a4c1a4f087bc1e14615d1f06979beff
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> #include <unordered_map> std::pair<int, int> bash_buttons(const std::vector<int>& buttons, int goal) { std::unordered_map<int, bool> visited; visited[0] = true; visited[goal] = false; std::queue<int> search; search.push(0); int moves = 0; int min_extra = INT_MAX; int min_moves = INT_MAX; int nodes_in_current_depth = 1; int nodes_in_next_depth = 0; while (!search.empty()) { int curr = search.front(); search.pop(); if (curr > goal && curr < min_extra) { min_extra = curr - goal; min_moves = moves; } if (curr == goal) return { moves, 0 }; for (auto& i : buttons) { int neighbour = (curr + i > 3600) ? 3600 : ((curr + i < 0) ? 0 : curr + i); if (!visited[neighbour]) { visited[neighbour] = true; search.push(neighbour); ++nodes_in_next_depth; } } --nodes_in_current_depth; if (!nodes_in_current_depth) { nodes_in_current_depth = nodes_in_next_depth; nodes_in_next_depth = 0; ++moves; } } return { min_moves, min_extra }; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int TC, n, t; std::cin >> TC; for (int i = 0; i < TC; ++i) { std::cin >> n >> t; std::vector<int> buttons(n); for (int j = 0; j < n; ++j) std::cin >> buttons[j]; auto press = bash_buttons(buttons, t); std::cout << press.first << " " << press.second << "\n"; } return 0; }
21.19697
78
0.611866
[ "vector" ]
b1f0a0f04cb6cf85e20435f3dff05c1ded4eeb5d
1,899
cc
C++
components/assist_ranker/quantized_nn_classifier.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/assist_ranker/quantized_nn_classifier.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/assist_ranker/quantized_nn_classifier.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/assist_ranker/quantized_nn_classifier.h" #include "components/assist_ranker/nn_classifier.h" namespace assist_ranker { namespace quantized_nn_classifier { namespace { // Dequantized a set of unsigned 8-bit weights using the specified scaling // factor and base value. void DequantizeVector(const std::string& s, float scale, float low, FloatVector* v) { for (const unsigned char ch : s) { v->mutable_values()->Add(scale * ch + low); } } // Dequantizes a quantized NN layer. void DequantizeLayer(const QuantizedNNLayer& quantized, NNLayer* layer) { const float low = quantized.low(); const float scale = (quantized.high() - low) / 256; DequantizeVector(quantized.biases(), scale, low, layer->mutable_biases()); for (const std::string& s : quantized.weights()) { auto* p = layer->mutable_weights()->Add(); DequantizeVector(s, scale, low, p); } } bool ValidateLayer(const QuantizedNNLayer& layer) { // The quantization low value must always be less than the high value. return layer.low() < layer.high(); } } // namespace NNClassifierModel Dequantize(const QuantizedNNClassifierModel& quantized) { NNClassifierModel model; DequantizeLayer(quantized.hidden_layer(), model.mutable_hidden_layer()); DequantizeLayer(quantized.logits_layer(), model.mutable_logits_layer()); return model; } bool Validate(const QuantizedNNClassifierModel& quantized) { if (!ValidateLayer(quantized.hidden_layer()) || !ValidateLayer(quantized.logits_layer())) { return false; } return nn_classifier::Validate(Dequantize(quantized)); } } // namespace quantized_nn_classifier } // namespace assist_ranker
32.186441
76
0.716166
[ "model" ]
b1f196682f4efc23df2c5a5c8a12810e1cd46312
18,175
cc
C++
RecoJets/FFTJetProducers/plugins/FFTJetPatRecoProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoJets/FFTJetProducers/plugins/FFTJetPatRecoProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoJets/FFTJetProducers/plugins/FFTJetPatRecoProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: FFTJetProducers // Class: FFTJetPatRecoProducer // /**\class FFTJetPatRecoProducer FFTJetPatRecoProducer.cc RecoJets/FFTJetProducer/plugins/FFTJetPatRecoProducer.cc Description: Runs FFTJet pattern recognition stage and saves the results Implementation: [Notes on implementation] */ // // Original Author: Igor Volobouev // Created: Tue Jun 15 12:45:45 CDT 2010 // // #include <fstream> // FFTJet headers #include "fftjet/ProximityClusteringTree.hh" #include "fftjet/ClusteringSequencer.hh" #include "fftjet/ClusteringTreeSparsifier.hh" #include "fftjet/FrequencyKernelConvolver.hh" #include "fftjet/FrequencySequentialConvolver.hh" #include "fftjet/DiscreteGauss1d.hh" #include "fftjet/DiscreteGauss2d.hh" // framework include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/Common/interface/View.h" #include "DataFormats/JetReco/interface/CaloJetCollection.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/BasicJetCollection.h" #include "DataFormats/JetReco/interface/TrackJetCollection.h" #include "DataFormats/Candidate/interface/Candidate.h" // Energy flow object #include "DataFormats/JetReco/interface/DiscretizedEnergyFlow.h" // parameter parser header #include "RecoJets/FFTJetProducers/interface/FFTJetParameterParser.h" // functions which manipulate storable trees #include "RecoJets/FFTJetAlgorithms/interface/clusteringTreeConverters.h" // functions which manipulate energy discretization grids #include "RecoJets/FFTJetAlgorithms/interface/gridConverters.h" // useful utilities collected in the second base #include "RecoJets/FFTJetProducers/interface/FFTJetInterface.h" using namespace fftjetcms; // // class declaration // class FFTJetPatRecoProducer : public FFTJetInterface { public: explicit FFTJetPatRecoProducer(const edm::ParameterSet&); ~FFTJetPatRecoProducer() override; protected: // Useful local typedefs typedef fftjet::ProximityClusteringTree<fftjet::Peak,long> ClusteringTree; typedef fftjet::SparseClusteringTree<fftjet::Peak,long> SparseTree; typedef fftjet::ClusteringSequencer<Real> Sequencer; typedef fftjet::ClusteringTreeSparsifier<fftjet::Peak,long> Sparsifier; // methods void beginJob() override ; void produce(edm::Event&, const edm::EventSetup&) override; void endJob() override ; void buildKernelConvolver(const edm::ParameterSet&); fftjet::PeakFinder buildPeakFinder(const edm::ParameterSet&); template<class Real> void buildSparseProduct(edm::Event&) const; template<class Real> void buildDenseProduct(edm::Event&) const; // The complete clustering tree ClusteringTree* clusteringTree; // Basically, we need to create FFTJet objects // ClusteringSequencer and ClusteringTreeSparsifier // which will subsequently perform most of the work std::unique_ptr<Sequencer> sequencer; std::unique_ptr<Sparsifier> sparsifier; // The FFT engine(s) std::unique_ptr<MyFFTEngine> engine; std::unique_ptr<MyFFTEngine> anotherEngine; // The pattern recognition kernel(s) std::unique_ptr<fftjet::AbsFrequencyKernel> kernel2d; std::unique_ptr<fftjet::AbsFrequencyKernel1d> etaKernel; std::unique_ptr<fftjet::AbsFrequencyKernel1d> phiKernel; // The kernel convolver std::unique_ptr<fftjet::AbsConvolverBase<Real> > convolver; // The peak selector for the clustering tree std::unique_ptr<fftjet::Functor1<bool,fftjet::Peak> > peakSelector; // Distance calculator for the clustering tree std::unique_ptr<fftjet::AbsDistanceCalculator<fftjet::Peak> > distanceCalc; // The sparse clustering tree SparseTree sparseTree; // The following parameters will define the behavior // of the algorithm wrt insertion of the complete event // into the clustering tree const double completeEventDataCutoff; // Are we going to make clustering trees? const bool makeClusteringTree; // Are we going to verify the data conversion for double precision // storage? const bool verifyDataConversion; // Are we going to store the discretization grid? const bool storeDiscretizationGrid; // Sparsify the clustering tree? const bool sparsify; private: FFTJetPatRecoProducer() = delete; FFTJetPatRecoProducer(const FFTJetPatRecoProducer&) = delete; FFTJetPatRecoProducer& operator=(const FFTJetPatRecoProducer&) = delete; // Members needed for storing grids externally std::ofstream externalGridStream; bool storeGridsExternally; fftjet::Grid2d<float>* extGrid; }; // // constructors and destructor // FFTJetPatRecoProducer::FFTJetPatRecoProducer(const edm::ParameterSet& ps) : FFTJetInterface(ps), clusteringTree(nullptr), completeEventDataCutoff(ps.getParameter<double>("completeEventDataCutoff")), makeClusteringTree(ps.getParameter<bool>("makeClusteringTree")), verifyDataConversion(ps.getUntrackedParameter<bool>("verifyDataConversion",false)), storeDiscretizationGrid(ps.getParameter<bool>("storeDiscretizationGrid")), sparsify(ps.getParameter<bool>("sparsify")), extGrid(nullptr) { // register your products if (makeClusteringTree) { if (storeInSinglePrecision()) produces<reco::PattRecoTree<float,reco::PattRecoPeak<float> > >(outputLabel); else produces<reco::PattRecoTree<double,reco::PattRecoPeak<double> > >(outputLabel); } if (storeDiscretizationGrid) produces<reco::DiscretizedEnergyFlow>(outputLabel); // Check if we want to write the grids into an external file const std::string externalGridFile(ps.getParameter<std::string>("externalGridFile")); storeGridsExternally = !externalGridFile.empty(); if (storeGridsExternally) { externalGridStream.open(externalGridFile.c_str(), std::ios_base::out | std::ios_base::binary); if (!externalGridStream.is_open()) throw cms::Exception("FFTJetBadConfig") << "FFTJetPatRecoProducer failed to open file " << externalGridFile << std::endl; } if (!makeClusteringTree && !storeDiscretizationGrid && !storeGridsExternally) { throw cms::Exception("FFTJetBadConfig") << "FFTJetPatRecoProducer is not configured to produce anything" << std::endl; } // now do whatever other initialization is needed // Build the discretization grid energyFlow = fftjet_Grid2d_parser( ps.getParameter<edm::ParameterSet>("GridConfiguration")); checkConfig(energyFlow, "invalid discretization grid"); // Build the FFT engine(s), pattern recognition kernel(s), // and the kernel convolver buildKernelConvolver(ps); // Build the peak selector peakSelector = fftjet_PeakSelector_parser( ps.getParameter<edm::ParameterSet>("PeakSelectorConfiguration")); checkConfig(peakSelector, "invalid peak selector"); // Build the initial set of pattern recognition scales std::unique_ptr<std::vector<double> > iniScales = fftjet_ScaleSet_parser( ps.getParameter<edm::ParameterSet>("InitialScales")); checkConfig(iniScales, "invalid set of scales"); // Do we want to use the adaptive clustering tree algorithm? const unsigned maxAdaptiveScales = ps.getParameter<unsigned>("maxAdaptiveScales"); const double minAdaptiveRatioLog = ps.getParameter<double>("minAdaptiveRatioLog"); if (minAdaptiveRatioLog <= 0.0) throw cms::Exception("FFTJetBadConfig") << "bad adaptive ratio logarithm limit" << std::endl; // Make sure that all standard scales are larger than the // complete event scale if (getEventScale() > 0.0) { const double cs = getEventScale(); const unsigned nscales = iniScales->size(); for (unsigned i=0; i<nscales; ++i) if (cs >= (*iniScales)[i]) throw cms::Exception("FFTJetBadConfig") << "incompatible scale for complete event" << std::endl; } // At this point we are ready to build the clustering sequencer sequencer = std::unique_ptr<Sequencer>(new Sequencer( convolver.get(), peakSelector.get(), buildPeakFinder(ps), *iniScales, maxAdaptiveScales, minAdaptiveRatioLog)); // Build the clustering tree sparsifier const edm::ParameterSet& SparsifierConfiguration( ps.getParameter<edm::ParameterSet>("SparsifierConfiguration")); sparsifier = fftjet_ClusteringTreeSparsifier_parser( SparsifierConfiguration); checkConfig(sparsifier, "invalid sparsifier parameters"); // Build the distance calculator for the clustering tree const edm::ParameterSet& TreeDistanceCalculator( ps.getParameter<edm::ParameterSet>("TreeDistanceCalculator")); distanceCalc = fftjet_DistanceCalculator_parser(TreeDistanceCalculator); checkConfig(distanceCalc, "invalid tree distance calculator"); // Build the clustering tree itself clusteringTree = new ClusteringTree(distanceCalc.get()); } void FFTJetPatRecoProducer::buildKernelConvolver(const edm::ParameterSet& ps) { // Check the parameter named "etaDependentScaleFactors". If the vector // of scales is empty we will use 2d kernel, otherwise use 1d kernels const std::vector<double> etaDependentScaleFactors( ps.getParameter<std::vector<double> >("etaDependentScaleFactors")); // Make sure that the number of scale factors provided is correct const bool use2dKernel = etaDependentScaleFactors.empty(); if (!use2dKernel) if (etaDependentScaleFactors.size() != energyFlow->nEta()) throw cms::Exception("FFTJetBadConfig") << "invalid number of eta-dependent scale factors" << std::endl; // Get the eta and phi scales for the kernel(s) double kernelEtaScale = ps.getParameter<double>("kernelEtaScale"); const double kernelPhiScale = ps.getParameter<double>("kernelPhiScale"); if (kernelEtaScale <= 0.0 || kernelPhiScale <= 0.0) throw cms::Exception("FFTJetBadConfig") << "invalid kernel scale" << std::endl; // FFT assumes that the grid extent in eta is 2*Pi. Adjust the // kernel scale in eta to compensate. kernelEtaScale *= (2.0*M_PI/(energyFlow->etaMax() - energyFlow->etaMin())); // Are we going to try to fix the efficiency near detector edges? const bool fixEfficiency = ps.getParameter<bool>("fixEfficiency"); // Minimum and maximum eta bin for the convolver unsigned convolverMinBin = 0, convolverMaxBin = 0; if (fixEfficiency || !use2dKernel) { convolverMinBin = ps.getParameter<unsigned>("convolverMinBin"); convolverMaxBin = ps.getParameter<unsigned>("convolverMaxBin"); } if (use2dKernel) { // Build the FFT engine engine = std::unique_ptr<MyFFTEngine>( new MyFFTEngine(energyFlow->nEta(), energyFlow->nPhi())); // 2d kernel kernel2d = std::unique_ptr<fftjet::AbsFrequencyKernel>( new fftjet::DiscreteGauss2d( kernelEtaScale, kernelPhiScale, energyFlow->nEta(), energyFlow->nPhi())); // 2d convolver convolver = std::unique_ptr<fftjet::AbsConvolverBase<Real> >( new fftjet::FrequencyKernelConvolver<Real,Complex>( engine.get(), kernel2d.get(), convolverMinBin, convolverMaxBin)); } else { // Need separate FFT engines for eta and phi engine = std::unique_ptr<MyFFTEngine>( new MyFFTEngine(1, energyFlow->nEta())); anotherEngine = std::unique_ptr<MyFFTEngine>( new MyFFTEngine(1, energyFlow->nPhi())); // 1d kernels etaKernel = std::unique_ptr<fftjet::AbsFrequencyKernel1d>( new fftjet::DiscreteGauss1d(kernelEtaScale, energyFlow->nEta())); phiKernel = std::unique_ptr<fftjet::AbsFrequencyKernel1d>( new fftjet::DiscreteGauss1d(kernelPhiScale, energyFlow->nPhi())); // Sequential convolver convolver = std::unique_ptr<fftjet::AbsConvolverBase<Real> >( new fftjet::FrequencySequentialConvolver<Real,Complex>( engine.get(), anotherEngine.get(), etaKernel.get(), phiKernel.get(), etaDependentScaleFactors, convolverMinBin, convolverMaxBin, fixEfficiency)); } } fftjet::PeakFinder FFTJetPatRecoProducer::buildPeakFinder(const edm::ParameterSet& ps) { const double peakFinderMaxEta = ps.getParameter<double>("peakFinderMaxEta"); if (peakFinderMaxEta <= 0.0) throw cms::Exception("FFTJetBadConfig") << "invalid peak finder eta cut" << std::endl; const double maxMagnitude = ps.getParameter<double>("peakFinderMaxMagnitude"); int minBin = energyFlow->getEtaBin(-peakFinderMaxEta); if (minBin < 0) minBin = 0; int maxBin = energyFlow->getEtaBin(peakFinderMaxEta) + 1; if (maxBin < 0) maxBin = 0; return fftjet::PeakFinder(maxMagnitude, true, minBin, maxBin); } FFTJetPatRecoProducer::~FFTJetPatRecoProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) delete clusteringTree; delete extGrid; } // // member functions // template<class Real> void FFTJetPatRecoProducer::buildSparseProduct(edm::Event& ev) const { typedef reco::PattRecoTree<Real,reco::PattRecoPeak<Real> > StoredTree; auto tree = std::make_unique<StoredTree>(); sparsePeakTreeToStorable(sparseTree, sequencer->maxAdaptiveScales(), tree.get()); // Check that we can restore the tree if (verifyDataConversion && !storeInSinglePrecision()) { SparseTree check; const std::vector<double>& scalesUsed(sequencer->getInitialScales()); sparsePeakTreeFromStorable(*tree, &scalesUsed, getEventScale(), &check); if (sparseTree != check) throw cms::Exception("FFTJetInterface") << "Data conversion failed for sparse clustering tree" << std::endl; } ev.put(std::move(tree), outputLabel); } template<class Real> void FFTJetPatRecoProducer::buildDenseProduct(edm::Event& ev) const { typedef reco::PattRecoTree<Real,reco::PattRecoPeak<Real> > StoredTree; auto tree = std::make_unique<StoredTree>(); densePeakTreeToStorable(*clusteringTree, sequencer->maxAdaptiveScales(), tree.get()); // Check that we can restore the tree if (verifyDataConversion && !storeInSinglePrecision()) { ClusteringTree check(distanceCalc.get()); const std::vector<double>& scalesUsed(sequencer->getInitialScales()); densePeakTreeFromStorable(*tree, &scalesUsed, getEventScale(), &check); if (*clusteringTree != check) throw cms::Exception("FFTJetInterface") << "Data conversion failed for dense clustering tree" << std::endl; } ev.put(std::move(tree), outputLabel); } // ------------ method called to produce the data ------------ void FFTJetPatRecoProducer::produce( edm::Event& iEvent, const edm::EventSetup& iSetup) { loadInputCollection(iEvent); discretizeEnergyFlow(); if (makeClusteringTree) { sequencer->run(*energyFlow, clusteringTree); if (getEventScale() > 0.0) sequencer->insertCompleteEvent(getEventScale(), *energyFlow, clusteringTree, completeEventDataCutoff); if (sparsify) { sparsifier->sparsify(*clusteringTree, &sparseTree); // Do not call the "sortNodes" method of the sparse tree here. // Currently, the nodes are sorted by daughter number. // This is the way we want it in storage because the stored // tree does not include daughter ordering info explicitly. if (storeInSinglePrecision()) buildSparseProduct<float>(iEvent); else buildSparseProduct<double>(iEvent); } else { if (storeInSinglePrecision()) buildDenseProduct<float>(iEvent); else buildDenseProduct<double>(iEvent); } } if (storeDiscretizationGrid) { const fftjet::Grid2d<Real>& g(*energyFlow); auto flow = std::make_unique<reco::DiscretizedEnergyFlow>( g.data(), g.title(), g.etaMin(), g.etaMax(), g.phiBin0Edge(), g.nEta(), g.nPhi()); if (verifyDataConversion) { fftjet::Grid2d<Real> check( flow->nEtaBins(), flow->etaMin(), flow->etaMax(), flow->nPhiBins(), flow->phiBin0Edge(), flow->title()); check.blockSet(flow->data(), flow->nEtaBins(), flow->nPhiBins()); assert(g == check); } iEvent.put(std::move(flow), outputLabel); } if (storeGridsExternally) { if (extGrid) copy_Grid2d_data(extGrid, *energyFlow); else extGrid = convert_Grid2d_to_float(*energyFlow); if (!extGrid->write(externalGridStream)) { throw cms::Exception("FFTJetPatRecoProducer::produce") << "Failed to write grid data into an external file" << std::endl; } } } // ------------ method called once each job just before starting event loop void FFTJetPatRecoProducer::beginJob() { } // ------------ method called once each job just after ending the event loop void FFTJetPatRecoProducer::endJob() { if (storeGridsExternally) externalGridStream.close(); } //define this as a plug-in DEFINE_FWK_MODULE(FFTJetPatRecoProducer);
35.567515
113
0.677304
[ "object", "vector" ]
b1f27a8c9c5700f807e13bc958538b1fe5c0de23
8,342
cpp
C++
example/mysql_c++/mysqlclient_press.cpp
yanglimingchn/brpc
0f9ff69d0519b567d4ca603894a694b4ba253c84
[ "Apache-2.0" ]
null
null
null
example/mysql_c++/mysqlclient_press.cpp
yanglimingchn/brpc
0f9ff69d0519b567d4ca603894a694b4ba253c84
[ "Apache-2.0" ]
null
null
null
example/mysql_c++/mysqlclient_press.cpp
yanglimingchn/brpc
0f9ff69d0519b567d4ca603894a694b4ba253c84
[ "Apache-2.0" ]
1
2020-05-13T03:44:24.000Z
2020-05-13T03:44:24.000Z
// Copyright (c) 2014 Baidu, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // A brpc based command-line interface to talk with mysql-server #include <sstream> #include <gflags/gflags.h> #include <butil/logging.h> extern "C" { #include <mysql/mysql.h> } #include <brpc/controller.h> #include <bvar/bvar.h> #include <bthread/bthread.h> #include <brpc/server.h> DEFINE_string(server, "127.0.0.1", "IP Address of server"); DEFINE_int32(port, 3306, "Port of server"); DEFINE_string(user, "brpcuser", "user name"); DEFINE_string(password, "12345678", "password"); DEFINE_string(schema, "brpc_test", "schema"); DEFINE_string(params, "", "params"); DEFINE_string(data, "ABCDEF", "data"); DEFINE_int32(thread_num, 50, "Number of threads to send requests"); DEFINE_bool(use_bthread, false, "Use bthread to send requests"); DEFINE_int32(dummy_port, -1, "port of dummy server(for monitoring)"); DEFINE_int32(op_type, 0, "CRUD operation, 0:INSERT, 1:SELECT, 3:UPDATE"); DEFINE_bool(dont_fail, false, "Print fatal when some call failed"); bvar::LatencyRecorder g_latency_recorder("client"); bvar::Adder<int> g_error_count("client_error_count"); struct SenderArgs { int base_index; MYSQL* mysql_conn; }; const std::string insert = "insert into mysqlclient_press(col1,col2,col3,col4) values " "('" "ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCA" "BCABCABCABCABCABCABCA', '" + FLAGS_data + "' ,1.5, " "now())"; // Send `command' to mysql-server via `channel' static void* sender(void* void_args) { SenderArgs* args = (SenderArgs*)void_args; std::stringstream command; if (FLAGS_op_type == 0) { command << insert; } else if (FLAGS_op_type == 1) { command << "select * from mysqlclient_press where id = " << args->base_index + 1; } else if (FLAGS_op_type == 2) { command << "update brpc_press set col2 = '" + FLAGS_data + "' where id = " << args->base_index + 1; } else { LOG(ERROR) << "wrong op type " << FLAGS_op_type; } std::string command_str = command.str(); while (!brpc::IsAskedToQuit()) { const int64_t begin_time_us = butil::cpuwide_time_us(); const int rc = mysql_real_query(args->mysql_conn, command_str.c_str(), command_str.size()); if (rc != 0) { goto ERROR; } if (mysql_errno(args->mysql_conn) == 0) { if (FLAGS_op_type == 0) { CHECK_EQ(mysql_affected_rows(args->mysql_conn), 1); } else if (FLAGS_op_type == 1) { MYSQL_RES* res = mysql_store_result(args->mysql_conn); if (res == NULL) { LOG(INFO) << "not found"; } else { CHECK_EQ(mysql_num_rows(res), 1); mysql_free_result(res); } } else if (FLAGS_op_type == 2) { } const int64_t elp = butil::cpuwide_time_us() - begin_time_us; g_latency_recorder << elp; } else { goto ERROR; } if (false) { ERROR: const int64_t elp = butil::cpuwide_time_us() - begin_time_us; g_error_count << 1; CHECK(brpc::IsAskedToQuit() || !FLAGS_dont_fail) << "error=" << mysql_error(args->mysql_conn) << " latency=" << elp; // We can't connect to the server, sleep a while. Notice that this // is a specific sleeping to prevent this thread from spinning too // fast. You should continue the business logic in a production // server rather than sleeping. bthread_usleep(50000); } } return NULL; } int main(int argc, char* argv[]) { // Parse gflags. We recommend you to use gflags as well. GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_dummy_port >= 0) { brpc::StartDummyServerAt(FLAGS_dummy_port); } MYSQL* conn = mysql_init(NULL); if (!mysql_real_connect(conn, FLAGS_server.c_str(), FLAGS_user.c_str(), FLAGS_password.c_str(), FLAGS_schema.c_str(), FLAGS_port, NULL, 0)) { LOG(ERROR) << mysql_error(conn); return -1; } // create table mysqlclient_press { const char* sql = "CREATE TABLE IF NOT EXISTS `mysqlclient_press`(`id` INT UNSIGNED AUTO_INCREMENT, " "`col1` " "VARCHAR(100) NOT NULL, `col2` VARCHAR(1024) NOT NULL, `col3` decimal(10,0) NOT " "NULL, `col4` DATE, PRIMARY KEY ( `id` )) ENGINE=InnoDB DEFAULT CHARSET=utf8;"; const int rc = mysql_real_query(conn, sql, strlen(sql)); if (rc != 0) { LOG(ERROR) << "Fail to execute sql, " << mysql_error(conn); return -1; } if (mysql_errno(conn) != 0) { LOG(ERROR) << "Fail to store result, " << mysql_error(conn); return -1; } } // truncate table { const char* sql = "truncate table mysqlclient_press"; const int rc = mysql_real_query(conn, sql, strlen(sql)); if (rc != 0) { LOG(ERROR) << "Fail to execute sql, " << mysql_error(conn); return -1; } if (mysql_errno(conn) != 0) { LOG(ERROR) << "Fail to store result, " << mysql_error(conn); return -1; } } // prepare data for select, update if (FLAGS_op_type != 0) { for (int i = 0; i < FLAGS_thread_num; ++i) { const int rc = mysql_real_query(conn, insert.c_str(), insert.size()); if (rc != 0) { LOG(ERROR) << "Fail to execute sql, " << mysql_error(conn); return -1; } if (mysql_errno(conn) != 0) { LOG(ERROR) << "Fail to store result, " << mysql_error(conn); return -1; } } } // test CRUD operations std::vector<bthread_t> bids; std::vector<pthread_t> pids; bids.resize(FLAGS_thread_num); pids.resize(FLAGS_thread_num); std::vector<SenderArgs> args; args.resize(FLAGS_thread_num); for (int i = 0; i < FLAGS_thread_num; ++i) { MYSQL* conn = mysql_init(NULL); if (!mysql_real_connect(conn, FLAGS_server.c_str(), FLAGS_user.c_str(), FLAGS_password.c_str(), FLAGS_schema.c_str(), FLAGS_port, NULL, 0)) { LOG(ERROR) << mysql_error(conn); return -1; } args[i].base_index = i; args[i].mysql_conn = conn; if (!FLAGS_use_bthread) { if (pthread_create(&pids[i], NULL, sender, &args[i]) != 0) { LOG(ERROR) << "Fail to create pthread"; return -1; } } else { if (bthread_start_background(&bids[i], NULL, sender, &args[i]) != 0) { LOG(ERROR) << "Fail to create bthread"; return -1; } } } while (!brpc::IsAskedToQuit()) { sleep(1); LOG(INFO) << "Accessing mysql-server at qps=" << g_latency_recorder.qps(1) << " latency=" << g_latency_recorder.latency(1); } LOG(INFO) << "mysql_client is going to quit"; for (int i = 0; i < FLAGS_thread_num; ++i) { if (!FLAGS_use_bthread) { pthread_join(pids[i], NULL); } else { bthread_join(bids[i], NULL); } } return 0; }
34.758333
99
0.552865
[ "vector" ]
b1f2f38e7970ba22bbefb39a6c9540ff28598a3d
29,626
cpp
C++
src/unpackertool/plugins/mpress/mpress.cpp
LaudateCorpus1/retdec
4a5d9ef75cc050b27f926fab49881cc771688109
[ "Zlib", "Apache-2.0", "MIT" ]
4,816
2017-12-12T18:07:09.000Z
2019-04-17T02:01:04.000Z
src/unpackertool/plugins/mpress/mpress.cpp
LaudateCorpus1/retdec
4a5d9ef75cc050b27f926fab49881cc771688109
[ "Zlib", "Apache-2.0", "MIT" ]
514
2017-12-12T18:22:52.000Z
2019-04-16T16:07:11.000Z
src/unpackertool/plugins/mpress/mpress.cpp
LaudateCorpus1/retdec
4a5d9ef75cc050b27f926fab49881cc771688109
[ "Zlib", "Apache-2.0", "MIT" ]
579
2017-12-12T18:38:02.000Z
2019-04-11T13:32:53.000Z
/** * @file src/unpackertool/plugins/mpress/mpress.cpp * @brief Unpacker plugin for MPRESS packer. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <algorithm> #include <cstdint> #include <memory> #include "retdec/loader/loader.h" #include "retdec/unpacker/plugin.h" #include "retdec/unpacker/decompression/lzma/lzma_data.h" #include "retdec/unpacker/decompression/lzmat/lzmat_data.h" #include "retdec/unpacker/unpacker_exception.h" #include "unpackertool/plugins/mpress/mpress.h" #include "unpackertool/plugins/mpress/mpress_exceptions.h" #include "retdec/fileformat/fileformat.h" #include "retdec/pelib/PeFile.h" using namespace retdec::utils; using namespace retdec::unpacker; namespace retdec { namespace unpackertool { namespace mpress { namespace { const MpressUnpackerStubData mpressUnpackerStubData[MPRESS_UNPACKER_STUB_UNKNOWN] = { { 0x2B6, 0x2BC, 0x2B8, 0x2C8, 0x2C0, COMPRESSION_LZMAT }, // MPRESS_UNPACKER_STUB_101_105 { 0x29E, 0x2A4, 0x2A0, 0x2B0, 0x2A8, COMPRESSION_LZMAT }, // MPRESS_UNPACKER_STUB_107_127 { 0x299, 0x29F, 0x29B, 0x2AB, 0x2A3, COMPRESSION_LZMAT }, // MPRESS_UNPACKER_STUB_201 { 0xB57, 0xB5D, 0xB59, 0xB61, 0xB69, COMPRESSION_LZMA }, // MPRESS_UNPACKER_STUB_205_LZMA { 0x29C, 0x2A2, 0x29E, 0x2A6, 0x2AE, COMPRESSION_LZMAT }, // MPRESS_UNPACKER_STUB_205_LZMAT { 0xB5A, 0xB60, 0xB5C, 0xB64, 0xB6C, COMPRESSION_LZMA }, // MPRESS_UNPACKER_STUB_212_219_LZMA { 0x29F, 0x2A5, 0x2A1, 0x2A9, 0x2B1, COMPRESSION_LZMAT } // MPRESS_UNPACKER_STUB_212_219_LZMAT }; const MpressFixStubData mpressFixStubData[MPRESS_FIX_STUB_UNKNOWN] = { { 0x8B, 0xC1, 0xBD }, // MPRESS_FIX_STUB_10x { 0x45, 0x138, 0x134 }, // MPRESS_FIX_STUB_127_20x { 0x35, 0x128, 0x124 } // MPRESS_FIX_STUB_21x }; } /** * Constructor. */ MpressPlugin::MpressPlugin() : _file(), _peFile(nullptr), _unpackerStub(MPRESS_UNPACKER_STUB_UNKNOWN), _fixStub(MPRESS_FIX_STUB_UNKNOWN), _packedContentSect(nullptr), _addedSectionCount(0), _iatVa(0), _iatSize(0), _oepVa(0), _importHintsOffset(0) { info.name = "MPRESS"; info.pluginVersion = "0.99"; info.packerVersion = R"/([12]\..{2})/"; // 1.xx or 2.xx info.author = "Marek Milkovic"; } /** * Destructor. */ MpressPlugin::~MpressPlugin() { cleanup(); } /** * Performs preparation of unpacking. */ void MpressPlugin::prepare() { _file = retdec::loader::createImage(getStartupArguments()->inputFile); if (!_file) throw UnsupportedFileException(); _peFile = new PeLib::PeFileT(getStartupArguments()->inputFile); if(_peFile->loadPeHeaders() != PeLib::ERROR_NONE) throw UnsupportedFileException(); // We currently don't support PE32+ as the decompiler doesn't support them anyways if (_peFile->imageLoader().getImageBitability() != 32) throw UnsupportedFileException(); if (!_file->getEpSegment()) throw NoEntryPointException(); // Detect the version of the used MPRESS packer and the compression used if (detectUnpackerStubVersion() == MPRESS_UNPACKER_STUB_UNKNOWN) throw UnsupportedStubException(); } /** * Starts unpacking in the current plugin. */ void MpressPlugin::unpack() { // Find the section which contains the packed content std::uint64_t ep; std::vector<std::uint8_t> packedContentSectAddrBytes; _file->getFileFormat()->getEpAddress(ep); _file->getEpSegment()->getBytes(packedContentSectAddrBytes, ep - _file->getEpSegment()->getAddress() + mpressUnpackerStubData[_unpackerStub].packedContentOffset, 4); DynamicBuffer packedContentSectAddrBuffer(packedContentSectAddrBytes, _file->getFileFormat()->getEndianness()); std::uint32_t packedContentSectAddr = ep + mpressUnpackerStubData[_unpackerStub].packedContentOffset + packedContentSectAddrBuffer.read<std::int32_t>(0); _packedContentSect = _file->getSegmentFromAddress(packedContentSectAddr); if (_packedContentSect == nullptr) throw PackedDataSectionNotFoundException(); std::vector<std::uint8_t> packedContent; _packedContentSect->getBytes(packedContent); DynamicBuffer packedContentBuffer(packedContent, _file->getFileFormat()->getEndianness()); // First 6 bytes contains metadata about the packed content // 2 bytes == size of the section with packed content shifted right by 0xC // 4 bytes == actual size of the packed content std::uint32_t unpackedSize = packedContentBuffer.read<std::uint16_t>(0) << 0xC; std::uint32_t packedSize = packedContentBuffer.read<std::uint32_t>(2); // Remove the header of the packed data from the buffer packedContentBuffer.erase(0, 6); if (packedSize > packedContentBuffer.getRealDataSize()) throw CorruptedUnpackingStubException(); // Remove tail of the packed data packedContentBuffer.erase(packedSize, packedContentBuffer.getRealDataSize() - packedSize); // Decode the content of .MPRESS1 section which is compressed with LZMAT algorithm DynamicBuffer unpackedContent(unpackedSize, _file->getFileFormat()->getEndianness()); if (!decompressData(packedContentBuffer, unpackedContent)) throw DecompressionFailedException(); // Fix JMP and CALL instructions with correction of their offsets fixJumpsAndCalls(unpackedContent); // Detect the version of fix stub here if (detectFixStubVersion(unpackedContent) == MPRESS_FIX_STUB_UNKNOWN) throw UnsupportedStubException(); // Fix imports & EP fixImportsAndEp(unpackedContent); // Fix relocations fixRelocations(); // Split the unpacked section as much as possible into individual sections based on the known offsets offsetAnalysis(unpackedContent); // Perform section trailing bytes analysis trailingBytesAnalysis(unpackedContent); // Save the new file saveFile(getStartupArguments()->outputFile, unpackedContent); } /** * Performs freeing of all owned resources. */ void MpressPlugin::cleanup() { delete _peFile; _peFile = nullptr; } bool MpressPlugin::decompressData(DynamicBuffer& compressedContent, DynamicBuffer& decompressedContent) { if (mpressUnpackerStubData[_unpackerStub].compression == COMPRESSION_LZMAT) { LzmatData lzmatData(compressedContent); if (!lzmatData.decompress(decompressedContent)) { error("Unable to decompress LZMAT compressed content"); return false; } } else if (mpressUnpackerStubData[_unpackerStub].compression == COMPRESSION_LZMA) { // Decode the LZMA properties and remove them from the compressedContent std::uint8_t pb, lp, lc; decodeLzmaProperties(compressedContent, pb, lp, lc); LzmaData lzmaData(compressedContent, pb, lp, lc); if (!lzmaData.decompress(decompressedContent)) { error("Unable to decompress LZMA compressed content"); return false; } } else { error("Unable to decompressed content"); return false; } return true; } void MpressPlugin::decodeLzmaProperties(DynamicBuffer& compressedContent, std::uint8_t& pb, std::uint8_t& lp, std::uint8_t& lc) { lp = compressedContent.read<std::uint8_t>(0) & 0x0F; pb = (compressedContent.read<std::uint8_t>(0) & 0xF0) >> 4; lc = compressedContent.read<std::uint8_t>(1); compressedContent.erase(0, 2); } std::uint32_t MpressPlugin::getFixStub() { std::uint64_t ep, epOffset; std::vector<std::uint8_t> fixStubOffsetBytes; // Fix imports stub is calculated from the EP section where there is offset into it written at specific offset _file->getFileFormat()->getEpAddress(ep); epOffset = ep - _file->getEpSegment()->getAddress(); _file->getEpSegment()->getBytes(fixStubOffsetBytes, epOffset + mpressUnpackerStubData[_unpackerStub].fixStubOffset, 4); DynamicBuffer fixStubOffsetBuffer(fixStubOffsetBytes, _file->getFileFormat()->getEndianness()); // If we subtract the address of .MPRESS1 section, we have the offset in section std::uint32_t fixImportsStubAddr = ep + mpressUnpackerStubData[_unpackerStub].fixStubOffset + 4 + fixStubOffsetBuffer.read<std::int32_t>(0); fixImportsStubAddr -= _packedContentSect->getAddress(); return fixImportsStubAddr; } void MpressPlugin::fixJumpsAndCalls(DynamicBuffer& buffer) { std::uint32_t pos = 0; std::uint32_t maxAddr = std::max(0, static_cast<std::int32_t>(buffer.getRealDataSize()) - 0x1000); while (pos < maxAddr) { std::uint32_t moveOffset = pos; std::uint8_t opcode = buffer.read<std::uint8_t>(pos++); if ((opcode & 0xFE) != 0xE8) // JMP == E9, CALL == E8 continue; std::int32_t offset = buffer.read<std::int32_t>(pos); moveOffset++; pos += 4; if (offset >= 0) { if (offset >= static_cast<std::int64_t>(maxAddr)) continue; } else { offset += moveOffset; if (offset < 0) continue; offset += maxAddr; } buffer.write<std::int32_t>(offset - moveOffset, pos - 4); } } void MpressPlugin::fixImportsAndEp(DynamicBuffer& buffer) { PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); std::uint32_t pointerSize = imageLoader.getPointerSize(); // At the offset from EP is written EIP relative offset of fix import stub // Fix import stub is then located at the <EP Address> + offset + <loaded offset> // This stub was packed together with code and data in .MPRESS1 section and also contains hints for import table rebuild std::uint32_t fixStubAddr = getFixStub(); // Offet to the hints is located at the <Fix Import Stub Address> + offset // Import hints are located at the <Fix Import Stub Address> + offset + <Import Hints Offset> std::uint32_t importHints = fixStubAddr + mpressFixStubData[_fixStub].importHintsOffset + buffer.read<std::uint32_t>(fixStubAddr + mpressFixStubData[_fixStub].importHintsOffset); // Go through MPRESS import hints and fill the import directory std::int32_t destOffset = imageLoader.getSectionHeader(_packedContentSect->getSecSeg()->getIndex())->VirtualAddress + importHints; std::int32_t lowestDestOffset = std::numeric_limits<std::int32_t>::max(); std::int32_t highestDestOffset = 0; std::int32_t destOffsetDiff; std::uint32_t readPos = importHints; while ((destOffsetDiff = buffer.read<std::int32_t>(readPos)) != -1) { destOffset += destOffsetDiff; buffer.writeRepeatingByte(0, readPos, 4); readPos += 4; std::string moduleName = buffer.readString(readPos); buffer.writeRepeatingByte(0, readPos, static_cast<uint32_t>(moduleName.length())); readPos += static_cast<uint32_t>(moduleName.length() + 1); destOffsetDiff = 0; while (buffer.read<std::uint8_t>(readPos) != 0) { // Import by ordinal if (buffer.read<std::uint8_t>(readPos) <= 0x20) { std::uint16_t ordinal = buffer.read<std::uint16_t>(readPos + 1); _peFile->impDir().addFunction(moduleName, ordinal); buffer.writeRepeatingByte(0, readPos, 3); readPos += 3; } // Import by name else { std::string symbolName = buffer.readString(readPos); _peFile->impDir().addFunction(moduleName, symbolName); buffer.writeRepeatingByte(0, readPos, static_cast<uint32_t>(symbolName.length() + 1)); readPos += static_cast<uint32_t>(symbolName.length() + 1); } destOffsetDiff += 4; } readPos++; // skip null terminator // Set FirstThunk to point into IAT int fileIndex = _peFile->impDir().getFileIndex(moduleName, true); if (fileIndex == -1) throw InvalidImportHintsException(); _peFile->impDir().setFirstThunk(fileIndex, true, destOffset); lowestDestOffset = std::min(destOffset, lowestDestOffset); highestDestOffset = std::max(destOffset, highestDestOffset); destOffset += destOffsetDiff; } buffer.writeRepeatingByte(0, readPos, 4); // clear out last -1 from the hint list // Fix the import directory and import address directory addresses // Since ILT is lost we need to make them from scratch in the whole new section // Ensure the .imports section will be large enough, resize if there are more data std::uint32_t fileAlignment = imageLoader.getFileAlignment(); std::uint32_t importFileSize = _peFile->impDir().calculateSize(pointerSize); std::uint32_t importSectSize = importFileSize & ~(fileAlignment - 1); std::uint32_t newSectionIndex; if (importFileSize & (fileAlignment - 1)) importSectSize += fileAlignment; PeLib::PELIB_IMAGE_SECTION_HEADER * pNewSection = imageLoader.addSection(".imports", importSectSize); pNewSection->Characteristics = PeLib::PELIB_IMAGE_SCN_MEM_READ | PeLib::PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA; imageLoader.setDataDirectory(PeLib::PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT, pNewSection->VirtualAddress, importSectSize); // IAT needs to be put at the desired offset std::uint32_t iatOffset = lowestDestOffset; imageLoader.setDataDirectory(PeLib::PELIB_IMAGE_DIRECTORY_ENTRY_IAT, iatOffset, highestDestOffset + 4 - lowestDestOffset); imageLoader.makeValid(); // Offset to OEP is stored at the offset from the <Fix Import Stub Address> // This offset is addressed from the <Fix Import Stub Address> + offset std::uint32_t oepOffset = imageLoader.getSectionHeader(_packedContentSect->getSecSeg()->getIndex())->VirtualAddress + fixStubAddr + mpressFixStubData[_fixStub].importHintsOffset + buffer.read<std::uint32_t>(fixStubAddr + mpressFixStubData[_fixStub].oepOffset); imageLoader.setAddressOfEntryPoint(oepOffset); // Finally, get rid of the fix imports stub as it is going to mess up frontend analysis in the unpacked section // At the end we add 16 because of 4 bytes directly belonging to the importHintsOffset and additional 12 bytes used // to store library calls GetProcAddress and LoadLibrary buffer.writeRepeatingByte(0, fixStubAddr, mpressFixStubData[_fixStub].importHintsOffset + 16); // Set to the global plugin attributes, so it can be used later _iatVa = iatOffset; _iatSize = highestDestOffset + 4 - lowestDestOffset; _oepVa = oepOffset; _importHintsOffset = importHints; } void MpressPlugin::offsetAnalysis(const DynamicBuffer& buffer) { PeLib::PELIB_IMAGE_SECTION_HEADER * packedContectSection; PeLib::PELIB_IMAGE_SECTION_HEADER * entryPointSection; PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); std::size_t packedContentSectionIndex = _packedContentSect->getSecSeg()->getIndex(); std::uint32_t sectionAlignment = imageLoader.getSectionAlignment(); std::uint32_t fixStubOffset = getFixStub(); std::uint32_t dataFlags = PeLib::PELIB_IMAGE_SCN_MEM_WRITE | PeLib::PELIB_IMAGE_SCN_MEM_READ | PeLib::PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA; std::uint32_t codeFlags = dataFlags | PeLib::PELIB_IMAGE_SCN_CNT_CODE | PeLib::PELIB_IMAGE_SCN_MEM_EXECUTE; // Get pointer to entry point section and also section with packed content packedContectSection = imageLoader.getSectionHeader(packedContentSectionIndex); entryPointSection = imageLoader.getSectionHeader(_file->getEpSegment()->getSecSeg()->getIndex()); // Remove the .MPRESS2 section as the getEpSection()->getIndex() will be shifted by newly created // sections and we can do it safely here //_peFile->peHeader().removeSection(_file->getEpSection()->getIndex()); // @todo There is some problem with removing a section and valid PE file in some cases entryPointSection->Characteristics = dataFlags; // Resize packed content section so we can put unpacked content into it size_t diff = buffer.getRealDataSize() - packedContectSection->SizeOfRawData; packedContectSection->SizeOfRawData = buffer.getRealDataSize(); for (size_t i = _packedContentSect->getSecSeg()->getIndex() + 1; i < imageLoader.getNumberOfSections(); ++i) { PeLib::PELIB_IMAGE_SECTION_HEADER * tempSection = imageLoader.getSectionHeader(i); tempSection->PointerToRawData = tempSection->PointerToRawData + diff; } // Here we will split the big unpacked section into the more data sections and try to locate the code section as much as possible // We will use import hints, IAT, fix stub address and OEP to locate the original sections // We know that hints and fix stub are located at the end of original sections // We also know that IAT is its own section std::uint32_t oepOffset = _oepVa - packedContectSection->VirtualAddress; std::uint32_t iatOffset = (_iatVa & ~(sectionAlignment - 1)) - packedContectSection->VirtualAddress; // We will need this as all other heuristics are based on the shrinking of .text section std::uint32_t moveOffset = 0; // Hints are located before the OEP, we suspect that there is data section before the code if (_importHintsOffset < oepOffset) { // Split the section into .data0|.text if (imageLoader.splitSection(packedContentSectionIndex, ".data0", ".text", (_importHintsOffset & ~(sectionAlignment - 1)) + sectionAlignment) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex)->Characteristics = dataFlags; imageLoader.getSectionHeader(packedContentSectionIndex+1)->Characteristics = codeFlags; _addedSectionCount++; // We will need this as all other heuristics are based on the shrinking of .text section // We need to subtract this from every split offset calculation moveOffset = imageLoader.getSectionHeader(packedContentSectionIndex)->SizeOfRawData; } // We don't mind if IAT is at the beginning of the data, since it is treated properly as data // However there can be IAT between data and code if (_importHintsOffset < iatOffset && iatOffset < oepOffset) { // Split the layout into .data0|.data2|.text if (imageLoader.splitSection(packedContentSectionIndex + 1, ".data2", ".text", ((iatOffset + _iatSize) & ~(sectionAlignment - 1)) + sectionAlignment - moveOffset) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex + 1)->Characteristics = dataFlags; imageLoader.getSectionHeader(packedContentSectionIndex + 2)->Characteristics = codeFlags; _addedSectionCount++; moveOffset += imageLoader.getSectionHeader(packedContentSectionIndex + 1)->SizeOfRawData; } } // Another heuristic is based on the fact that fix stub can be located behind the code // There we can get original code section almost perfectly if (fixStubOffset > oepOffset) { // Split into .data0|.text|.data1 or .data0|.data2|.text|.data1 if (imageLoader.splitSection(packedContentSectionIndex + _addedSectionCount, ".text", ".data1", (fixStubOffset & ~(sectionAlignment - 1)) + sectionAlignment - moveOffset) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex + _addedSectionCount)->Characteristics = codeFlags; imageLoader.getSectionHeader(packedContentSectionIndex + _addedSectionCount + 1)->Characteristics = dataFlags; _addedSectionCount++; } } } // The OEP is before the hints, so code section is probably the first one in this big section else { // Split into .text|.data0 if (imageLoader.splitSection(packedContentSectionIndex, ".text", ".data0", (_importHintsOffset & ~(sectionAlignment - 1)) + sectionAlignment) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex)->Characteristics = codeFlags; imageLoader.getSectionHeader(packedContentSectionIndex + 1)->Characteristics = dataFlags; _addedSectionCount++; } // There can be even IAT between the .text and .data0 if the hints were placed far behind if (oepOffset < iatOffset && iatOffset < _importHintsOffset) { // Split into .text|.data2|.data0 if (imageLoader.splitSection(packedContentSectionIndex, ".text", ".data2", (iatOffset + _iatSize) & ~(sectionAlignment - 1)) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex)->Characteristics = codeFlags; imageLoader.getSectionHeader(packedContentSectionIndex + 1)->Characteristics = dataFlags; _addedSectionCount++; } } // This will probably never happen because if there would be space for fix stub, the hints would be there more probably, but just in case if (fixStubOffset < oepOffset) { // Split into .data1|.text|.data0 or .data1|.text|.data2|.data0 if (imageLoader.splitSection(packedContentSectionIndex, ".data1", ".text", (fixStubOffset & ~(sectionAlignment - 1)) + sectionAlignment) == 0) { imageLoader.getSectionHeader(packedContentSectionIndex)->Characteristics = dataFlags; imageLoader.getSectionHeader(packedContentSectionIndex + 1)->Characteristics = codeFlags; _addedSectionCount++; } } } imageLoader.makeValid(); } void MpressPlugin::trailingBytesAnalysis(const DynamicBuffer& buffer) { // Analysis of the trailing bytes of the section // 64 bytes at the every section alignment multiple are checked, if they are all 0, the new section is probably here so it is created // Only code section left after this function is the one containing the OEP, the code will execute even if some of the code is in data sections // and decompiler will take care of this in front-end instruction decoder PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); PeLib::PELIB_IMAGE_SECTION_HEADER * packedContentSection = imageLoader.getSectionHeader(_packedContentSect->getSecSeg()->getIndex()); std::size_t section = imageLoader.getSectionIndexByRva(imageLoader.getAddressOfEntryPoint()); PeLib::PELIB_IMAGE_SECTION_HEADER * entryPointSection = imageLoader.getSectionHeader(section); std::uint32_t sectionAlignment = imageLoader.getSectionAlignment(); std::uint32_t startOffset = entryPointSection->PointerToRawData - packedContentSection->PointerToRawData; std::uint32_t endOffset = startOffset + entryPointSection->SizeOfRawData; std::uint32_t oepOffset = imageLoader.getAddressOfEntryPoint() - packedContentSection->VirtualAddress; // Used to build the section names std::uint32_t nameCounter = 3; // Start at the next section alignment closest to the start of current .text section // Move with the step of section alignment // End if end of the unpacked section is reached for (std::uint32_t offset = startOffset + sectionAlignment; offset < endOffset; offset += sectionAlignment) { // Inspect trailing 64 bytes, if they are all 0, needSplit is marked as true, resulting in section split bool needSplit = true; for (std::uint8_t idx = 1; idx <= 64; ++idx) { if (buffer.read<std::uint8_t>(offset - idx) != 0) { needSplit = false; break; } } if (!needSplit) continue; std::stringstream ssFirst, ssSecond; std::uint32_t flags[2]; // OEP lies in the first part of splitted sections if (startOffset <= oepOffset && oepOffset < offset) { ssFirst << ".text"; ssSecond << ".data" << nameCounter++; flags[1] = PeLib::PELIB_IMAGE_SCN_MEM_WRITE | PeLib::PELIB_IMAGE_SCN_MEM_READ | PeLib::PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA; flags[0] = flags[1] | PeLib::PELIB_IMAGE_SCN_MEM_EXECUTE | PeLib::PELIB_IMAGE_SCN_CNT_CODE; } // OEP lies in the second part of splitted sections else if (offset <= oepOffset && oepOffset < endOffset) { ssFirst << ".data" << nameCounter++; ssSecond << ".text"; flags[0] = PeLib::PELIB_IMAGE_SCN_MEM_WRITE | PeLib::PELIB_IMAGE_SCN_MEM_READ | PeLib::PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA; flags[1] = flags[0] | PeLib::PELIB_IMAGE_SCN_MEM_EXECUTE | PeLib::PELIB_IMAGE_SCN_CNT_CODE; } // OEP doesn't lie in neither of these two parts, this can happen if .text section was already created and we are analyzing the rest after that else { ssFirst << ".data" << nameCounter++; ssSecond << ".data" << nameCounter++; flags[0] = PeLib::PELIB_IMAGE_SCN_MEM_WRITE | PeLib::PELIB_IMAGE_SCN_MEM_READ | PeLib::PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA; flags[1] = flags[0]; } imageLoader.splitSection(section, ssFirst.str(), ssSecond.str(), offset - startOffset); imageLoader.getSectionHeader(section)->Characteristics = flags[0]; imageLoader.getSectionHeader(section + 1)->Characteristics = flags[1]; imageLoader.makeValid(); _addedSectionCount++; section++; startOffset = offset; } } void MpressPlugin::fixRelocations() { // We will only manipulate this section as all information are stored here const retdec::loader::Segment* epSegment = _file->getEpSegment(); PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); // Calculate the offset of EP in EP section std::uint64_t epAddress; _file->getFileFormat()->getEpAddress(epAddress); epAddress -= epSegment->getAddress(); // Read the data at the desired offsets std::vector<unsigned char> relocRvaBytes, relocSizeBytes; epSegment->getBytes(relocRvaBytes, epAddress + mpressUnpackerStubData[_unpackerStub].relocOffset, 4); epSegment->getBytes(relocSizeBytes, epAddress + mpressUnpackerStubData[_unpackerStub].relocSizeOffset, 4); DynamicBuffer relocRvaBuffer(relocRvaBytes, _file->getFileFormat()->getEndianness()); DynamicBuffer relocSizeBuffer(relocSizeBytes, _file->getFileFormat()->getEndianness()); // When the size of relocation is 0, there are no relocations std::uint32_t relocSize = relocSizeBuffer.read<std::uint32_t>(0); if (relocSize == 0) return; // Set the base relocation directory in the new file // All relocations are here undamaged so we are good with this std::uint32_t relocRva = relocRvaBuffer.read<std::uint32_t>(0); imageLoader.setDataDirectory(PeLib::PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC, relocRva, relocSize); } MpressUnpackerStub MpressPlugin::detectUnpackerStubVersion() { std::uint64_t ep; std::vector<std::uint8_t> signatureBytes; // Get the data in EP section so we can compare it with signature _file->getFileFormat()->getEpAddress(ep); ep -= _file->getEpSegment()->getAddress(); _file->getEpSegment()->getBytes(signatureBytes, ep + 8, 4); DynamicBuffer signatureBuffer(signatureBytes, _file->getFileFormat()->getEndianness()); std::uint32_t signature = signatureBuffer.read<std::uint32_t>(0); // Signature should not be bigger than 0xC00 for all versions of MPRESS // This heuristic can catch corrupted unpacking stubs if (signature >= 0xC00) throw CorruptedUnpackingStubException(); for (std::uint32_t version = 0; version < static_cast<std::uint32_t>(MPRESS_UNPACKER_STUB_UNKNOWN); ++version) { if (signature == mpressUnpackerStubData[version].signature) { _unpackerStub = static_cast<MpressUnpackerStub>(version); return static_cast<MpressUnpackerStub>(version); } } return MPRESS_UNPACKER_STUB_UNKNOWN; } MpressFixStub MpressPlugin::detectFixStubVersion(DynamicBuffer& unpackedContent) { std::uint32_t fixStub = getFixStub(); for (std::uint32_t version = 0; version < static_cast<std::uint32_t>(MPRESS_FIX_STUB_UNKNOWN); ++version) { if (unpackedContent.read<std::uint8_t>(fixStub + 7) == mpressFixStubData[version].signature) { _fixStub = static_cast<MpressFixStub>(version); return static_cast<MpressFixStub>(version); } } return MPRESS_FIX_STUB_UNKNOWN; } void MpressPlugin::saveFile(const std::string& fileName, DynamicBuffer& content) { PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); // Removes the file if it already exists std::remove(fileName.c_str()); // Headers imageLoader.Save(fileName.c_str(), PeLib::IoFlagNewFile); std::fstream outputFile(fileName, std::ios::binary | std::ios::out | std::ios::in); // Copy the section bytes from original file for the sections preceding the packed section for (std::uint32_t index = 0; index < _packedContentSect->getSecSeg()->getIndex(); ++index) copySectionFromOriginalFile(index, outputFile, index); // Copy the section bytes in between packed section and EP section for (std::uint32_t index = _packedContentSect->getSecSeg()->getIndex() + _addedSectionCount; index < _file->getEpSegment()->getSecSeg()->getIndex(); ++index) copySectionFromOriginalFile(index, outputFile, index + _addedSectionCount); // Copy the section bytes from original file for sections after EP section excluded for (std::uint32_t index = _file->getEpSegment()->getSecSeg()->getIndex() + 1; index < _file->getNumberOfSegments(); ++index) copySectionFromOriginalFile(index, outputFile, index + _addedSectionCount); // Write content of new import section std::uint32_t Rva = imageLoader.getDataDirRva(PeLib::PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT); _peFile->impDir().write(fileName, imageLoader.getFileOffsetFromRva(Rva), Rva, imageLoader.getPointerSize()); // After this all we need to update the IAT with the contents of ILT // since Import Directory in PeLib is built after the write to the file for (size_t fileIndex = 0; fileIndex < _peFile->impDir().getNumberOfFiles(false); ++fileIndex) { auto tmp = static_cast<unsigned int>(fileIndex); auto w = static_cast<unsigned short>(_packedContentSect->getSecSeg()->getIndex()); size_t destOffset = _peFile->impDir().getFirstThunk(tmp, false) - imageLoader.getSectionHeader(w)->VirtualAddress; for (size_t funcIndex = 0; funcIndex < _peFile->impDir().getNumberOfFunctions(tmp, false); ++funcIndex, destOffset += 4) { content.write<std::uint32_t>( _peFile->impDir().getOriginalFirstThunk(tmp, static_cast<unsigned int>(funcIndex), false), static_cast<uint32_t>(destOffset)); } } // Write the unpacked content to the packed content section // Use regular file as we will write more sections at once outputFile.seekp(imageLoader.getSectionHeader(_packedContentSect->getSecSeg()->getIndex())->PointerToRawData, std::ios_base::beg); outputFile.write(reinterpret_cast<const char*>(content.getRawBuffer()), content.getRealDataSize()); outputFile.close(); } void MpressPlugin::copySectionFromOriginalFile(std::uint32_t origSectIndex, std::ostream& outputFile, std::uint32_t newSectIndex) { const retdec::loader::Segment* seg = _file->getSegment(origSectIndex); std::vector<std::uint8_t> bytes; seg->getBytes(bytes); PeLib::ImageLoader & imageLoader = _peFile->imageLoader(); const auto* newSect = imageLoader.getSectionHeader(newSectIndex); outputFile.seekp(newSect->PointerToRawData, std::ios_base::beg); outputFile.write(reinterpret_cast<const char*>(bytes.data()), std::min(static_cast<std::uint32_t>(bytes.size()), newSect->SizeOfRawData)); } } // namespace mpress } // namespace unpackertool } // namespace retdec
41.377095
179
0.7567
[ "vector" ]
b1f360c845f842613b8c3577ae43c55484898252
24,231
cpp
C++
MiniEngine/Tools/SDFFontCreator/SDFFontCreator.cpp
Xeio/DirectX-Graphics-Samples
870e283ad4ba262e2505a9c52eaab812991f1652
[ "MIT" ]
1
2019-12-11T14:22:40.000Z
2019-12-11T14:22:40.000Z
MiniEngine/Tools/SDFFontCreator/SDFFontCreator.cpp
5ai8ot/DirectX-Graphics-Samples
aee9b669fc23ac5cb0b998fcbf79705a0e89b0a7
[ "MIT" ]
null
null
null
MiniEngine/Tools/SDFFontCreator/SDFFontCreator.cpp
5ai8ot/DirectX-Graphics-Samples
aee9b669fc23ac5cb0b998fcbf79705a0e89b0a7
[ "MIT" ]
3
2018-11-18T05:36:49.000Z
2019-12-11T14:22:42.000Z
#include <fstream> #include <set> #include <cmath> #include <ft2build.h> #include <cstdint> #include <thread> #include <vector> #include <algorithm> #include <intrin.h> #include FT_FREETYPE_H #define kMajorVersion 1 #define kMinorVersion 0 #define kMaxTextureDimension 4096 using namespace std; template <typename T> inline T align16( T val ) { return (val + 15) & ~15; } // All measurements are in 12.4 fixed point struct GlyphInfo { wchar_t c; // The unicode (UCS2) character code corresponding to the glyph uint16_t u, v; // The upper left texture coordinate of the glyph, not counting border space uint16_t width; // The width of the glyph (not counting horizontal spacing) int16_t bearing; // The leading space before the glyph (sometimes negative) uint16_t advance; // The total distance to advance the pen after printing }; __declspec(thread) FT_Library g_FreeTypeLib = 0; // FreeType2 library wrapper __declspec(thread) FT_Face g_FreeTypeFace = 0; // FreeType2 typeface uint16_t g_numGlyphs = 0; // Number of glyphs to process GlyphInfo g_glyphs[0xFFFF]; // An array of glyph information uint16_t g_borderSize = 0; // Extra space around each glyph used for effects like glow and drop shadow uint16_t g_maxDistance = 0; // Range of search space which controls the "steepness" of the contour map bool g_fixNumberWidths = false; // Prints all numbers with fixed spacing uint16_t g_maxGlyphHeight = 0; // Max height of glyph = ascender - descender int16_t g_fontOffset = 0; // Baseline offset to center the text vertically uint16_t g_fontAdvanceY = 0; // Distance from baseline to baseline (line height) float* g_DistanceMap = 0; uint32_t g_MapWidth = 0; uint32_t g_MapHeight = 0; volatile int32_t g_nextGlyphIdx = 0; volatile bool g_ReadyToPaint = false; void PrintAssertMessage( const char* file, uint32_t line, const char* cond, const char* msg, ...) { printf("Assertion \"%s\" failed at %s:%u\n", cond, file, line); if (msg) { va_list ap; va_start(ap, msg); vprintf(msg, ap); printf("\n"); } } // Assert which allows setting of file and line number #define ASSERT_LINE( test, file, line, ... ) \ if (!(test)) { \ PrintAssertMessage(file, line, #test, ##__VA_ARGS__); \ __debugbreak(); \ } // Assert which automatically detects call location #define ASSERT( test, ... ) ASSERT_LINE( test, __FILE__, __LINE__, __VA_ARGS__ ) void InitializeFont( const char* filename = 0, uint32_t size = 0) { static const char* s_filename = 0; static uint32_t s_size = 0; if (s_filename == 0) { ASSERT(filename != 0, "We must have a TrueType file to initialize FreeType"); ASSERT(size > 0, "A size must be specified to initialize FreeType"); } else { filename = s_filename; size = s_size; } ASSERT(g_FreeTypeLib == 0, "FreeType is already initialized on this thread"); try { if (FT_Init_FreeType( &g_FreeTypeLib )) throw exception("Failed to create library\n"); if (FT_New_Face( g_FreeTypeLib, filename, 0, &g_FreeTypeFace )) throw exception("Failed to create face\n"); if (FT_Set_Pixel_Sizes( g_FreeTypeFace, 0, size )) throw exception("Failed to set pixel sizes\n"); } catch (exception& e) { // If this is the first time, that filename is probably bad. Raise the error. if (s_filename == 0) throw; printf("Error: Unable to initialize FreeType for thread: %s\n", e.what()); } s_filename = filename; s_size = size; } void ShutdownFont(void) { if (g_FreeTypeFace) FT_Done_Face( g_FreeTypeFace ); if (g_FreeTypeLib) FT_Done_FreeType( g_FreeTypeLib ); } struct Canvas { uint8_t* bitmap; // Pointer to rendered glyph memory (from FT_Bitmap) uint32_t pitch; // Width in bytes of a row in the canvas uint32_t width; // Width in pixels of a row in the canvas uint32_t rows; // Number of rows in the canvas uint32_t xOff; // Amount to offset the x coordinate when reading uint32_t yOff; // Amount to offset the y coordinate when reading }; // Access the high res glyph canvas inline bool ReadCanvasBit( const Canvas& canvas, uint32_t x, uint32_t y ) { // Notice that negative values have been cast to large positive values x -= canvas.xOff; y -= canvas.yOff; if (x >= canvas.width || y >= canvas.rows) return false; uint32_t p = y * canvas.pitch + x / 8; uint32_t k = x & 7; return (canvas.bitmap[p] & (0x80 >> k)) ? true : false; } // Setup pixel reads from the glyph canvas inline Canvas LoadCanvas(FT_GlyphSlot glyph) { Canvas ret; ret.bitmap = glyph->bitmap.buffer; ret.pitch = glyph->bitmap.pitch; ret.width = glyph->bitmap.width; ret.rows = glyph->bitmap.rows; ret.xOff = g_borderSize * 16; ret.yOff = g_borderSize * 16 + g_maxGlyphHeight + g_fontOffset - (glyph->metrics.horiBearingY >> 6); return ret; } float DistanceFromInside(const Canvas& canvas, uint32_t xCoord, uint32_t yCoord) { const uint32_t radius = g_maxDistance * 32; const uint32_t x0 = xCoord * 32 + 15; const uint32_t y0 = yCoord * 32 + 15; uint32_t left = (uint32_t)max(0, (int32_t)(x0 - radius + 1)); uint32_t right = x0 + radius - 1; uint32_t top = (uint32_t)max(0, (int32_t)(y0 - radius + 1)); uint32_t bottom = y0 + radius - 1; uint32_t bestDistSq = radius * radius; for (uint32_t y1 = top; y1 <= bottom; y1 += 2) { int32_t distY = (int32_t)(y1 - y0); uint32_t distYSq = (uint32_t)(distY * distY); if (distYSq >= bestDistSq) { if (y1 > y0) continue; else break; } for (uint32_t x1 = left; x1 <= right; x1 += 2) { int32_t distX = (int32_t)(x1 - x0); uint32_t distXSq = (uint32_t)(distX * distX); uint32_t distSq = (uint32_t)(distXSq + distYSq); if (distSq < bestDistSq && !ReadCanvasBit(canvas, x1 >> 1, y1 >> 1)) bestDistSq = distSq; } } return sqrt((float)bestDistSq) / (float)radius; } float DistanceFromOutside(const Canvas& canvas, uint32_t xCoord, uint32_t yCoord) { const uint32_t radius = g_maxDistance * 32; const uint32_t x0 = xCoord * 32 + 15; const uint32_t y0 = yCoord * 32 + 15; uint32_t left = (uint32_t)max(0, (int32_t)(x0 - radius + 1)); uint32_t right = x0 + radius - 1; uint32_t top = (uint32_t)max(0, (int32_t)(y0 - radius + 1)); uint32_t bottom = y0 + radius - 1; uint32_t bestDistSq = radius * radius; for (uint32_t y1 = top; y1 <= bottom; y1 += 2) { int32_t distY = (int32_t)(y1 - y0); uint32_t distYSq = (uint32_t)(distY * distY); if (distYSq >= bestDistSq) { if (y1 > y0) continue; else break; } for (uint32_t x1 = left; x1 <= right; x1 += 2) { int32_t distX = (int32_t)(x1 - x0); uint32_t distXSq = (uint32_t)(distX * distX); uint32_t distSq = (uint32_t)(distXSq + distYSq); if (distSq < bestDistSq && ReadCanvasBit(canvas, x1 >> 1, y1 >> 1)) bestDistSq = distSq; } } return sqrt((float)bestDistSq) / (float)radius; } // Get width and spacing of a given glyph to compute necessary space and layout in final texture. inline uint16_t GetGlyphMetrics( wchar_t c, GlyphInfo& info ) { if (FT_Load_Char( g_FreeTypeFace, c, FT_LOAD_TARGET_MONO )) throw exception("Unable to access glyph data"); FT_Glyph_Metrics& metrics = g_FreeTypeFace->glyph->metrics; info.bearing = (int16_t)(metrics.horiBearingX >> 6); info.width = (uint16_t)(metrics.width >> 6); info.advance = (uint16_t)(metrics.horiAdvance >> 6); return (uint16_t)info.width; } // Compute glyph layout in bitmap for a given texture width. If the height exceeds a certain // threshold, you should recompute the layout with a larger texture width. uint32_t UnwrapUVs(uint32_t textureWidth) { uint16_t glyphBorder = g_borderSize * 16; uint16_t rowSize = align16(g_maxGlyphHeight); // Set the starting point for the drawing uint32_t x = glyphBorder; uint32_t y = glyphBorder; for (uint16_t i = 0; i < g_numGlyphs; ++i) { // We need a pixel border to surround the character because the distance field must enclose // the bitmap. uint32_t deltaX = align16(g_glyphs[i].width) + glyphBorder; // Check for line wrap if (x + deltaX > textureWidth * 16) { x = glyphBorder; y += rowSize + glyphBorder * 2; } // The actual character UVs don't include the border pixels g_glyphs[i].u = x; g_glyphs[i].v = y; x += deltaX + glyphBorder; } return (y + rowSize + glyphBorder) / 16; } void PaintCharacters( float* distanceMap, uint32_t width, uint32_t height ) { int32_t i = -1; while ((i = _InterlockedExchangeAdd((volatile long*)&g_nextGlyphIdx, 1)) < g_numGlyphs) { // Get the character info const GlyphInfo& ch = g_glyphs[i]; if (FT_Load_Char( g_FreeTypeFace, ch.c, FT_LOAD_RENDER | FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO )) throw exception("Character bitmap rendering failed internally"); Canvas canvas = LoadCanvas(g_FreeTypeFace->glyph); uint32_t charWidth = align16(ch.width) / 16; uint32_t charHeight = align16(g_maxGlyphHeight) / 16; uint32_t startX = ch.u / 16 - g_borderSize; uint32_t startY = ch.v / 16 - g_borderSize; // Convert high-res bitmap to low-res distance map for (uint32_t x = 0; x < charWidth + g_borderSize * 2; ++x) { for (uint32_t y = 0; y < charHeight + g_borderSize * 2; ++y) { uint32_t left = x * 16 + 7; uint32_t top = y * 16 + 7; bool inside = ReadCanvasBit(canvas, left, top) & ReadCanvasBit(canvas, left + 1, top) & ReadCanvasBit(canvas, left, top + 1) & ReadCanvasBit(canvas, left + 1, top + 1); if (inside) distanceMap[startX + x + (startY + y) * width] = +DistanceFromInside(canvas, x, y); else distanceMap[startX + x + (startY + y) * width] = -DistanceFromOutside(canvas, x, y); } } } } void WorkerFunc( void ) { // We can initialize FreeType while we wait to paint the alphabet InitializeFont(); // Sleep for 2 milliseconds per iteration until we're ready to paint while (!g_ReadyToPaint) std::this_thread::sleep_for(std::chrono::milliseconds(2)); PaintCharacters(g_DistanceMap, g_MapWidth, g_MapHeight); ShutdownFont(); } struct BMP_Header { // Bitmap file header uint32_t filesz; uint16_t creator1; uint16_t creator2; uint32_t bmp_offset; // DIB header uint32_t header_sz; uint32_t width; uint32_t height; uint16_t nplanes; uint16_t bitspp; uint32_t compress_type; uint32_t bmp_bytesz; uint32_t hres; uint32_t vres; uint32_t ncolors; uint32_t nimpcolors; }; void WritePreviewBMP(const string& fileName, const uint8_t* heightMap, uint32_t width, uint32_t height) { // Append ".bmp" to file name char fileWithSuffix[256]; sprintf_s(fileWithSuffix, 256, "%s.bmp", fileName.c_str()); // Open file ofstream file; file.exceptions(ios_base::failbit | ios_base::badbit); file.open(fileWithSuffix, ios_base::out | ios_base::binary | ios_base::trunc); file.write("BM", 2); // Write header BMP_Header header; memset(&header, 0, sizeof(BMP_Header)); header.filesz = 54 + 256 * sizeof(uint32_t) + width * height; header.bmp_offset = 54 + 256 * sizeof(uint32_t); header.header_sz = 40; header.width = width; header.height = -(int32_t)height; header.nplanes = 1; header.bitspp = 8; header.hres = 0x130B0000; header.vres = 0x130B0000; file.write((const char*)&header, sizeof(BMP_Header)); // Write color map table uint32_t colorMap[256]; for (uint32_t i = 0; i < 256; ++i) colorMap[i] = i << 16 | i << 8 | i; file.write((const char*)colorMap, 256 * sizeof(uint32_t)); // Write data file.write((const char*)heightMap, width * height); // Close file file.close(); } void CompileFont(const string& inputFile, uint32_t size, const string& outputName) { // Figure out how many threads to create, and then spawn them. Leave their parameters blank. We'll fill them in // before they're read. size_t numThreads = std::thread::hardware_concurrency(); std::vector<std::thread> Threads; if (numThreads > 1) { --numThreads; for (uint32_t i = 0; i < numThreads; ++i) { Threads.push_back(std::thread(WorkerFunc)); } } // This implicitly embeds space in the font texture, which wastes memory. What would be better is to just store // the font height (i.e. the line spacing) in the final file header, and pack the texture as tightly as possible. g_fontAdvanceY = (uint16_t)(g_FreeTypeFace->size->metrics.height >> 6); g_maxGlyphHeight = (uint16_t)((g_FreeTypeFace->size->metrics.ascender - g_FreeTypeFace->size->metrics.descender) >> 6); g_fontOffset = (int16_t)(g_FreeTypeFace->size->metrics.descender >> 6); // Get the dimensions of each glyph for (uint16_t i = 0; i < g_numGlyphs; ++i) GetGlyphMetrics(g_glyphs[i].c, g_glyphs[i]); // Adjust metrics for numerals if we want to coerce fixed number widths if (g_fixNumberWidths) { // Compute maximum numeric advance uint32_t numberWidth = 0; for (uint16_t i = 0; i < g_numGlyphs; ++i) { wchar_t wc = g_glyphs[i].c; if (wc >= L'0' && wc <= L'9') numberWidth = max(numberWidth, (uint32_t)g_glyphs[i].advance); } // Adjust each numeral to advance the same amount and to center the digit by adjusting the bearing for (uint16_t i = 0; i < g_numGlyphs; ++i) { wchar_t wc = g_glyphs[i].c; if (wc >= L'0' && wc <= L'9') { int extraSpace = numberWidth - g_glyphs[i].width; g_glyphs[i].bearing = extraSpace / 2; g_glyphs[i].advance = numberWidth; } } } // Compute the smallest rectangular texture with height < width that can contain the result. Use // widths that are a power of two to accelerate the search. for (g_MapWidth = 512; g_MapWidth <= kMaxTextureDimension; g_MapWidth *= 2) { g_MapHeight = UnwrapUVs(g_MapWidth); // Found a good size if (g_MapHeight <= g_MapWidth) break; } // We ran through all possibilities and still couldn't fit the font if (g_MapHeight > g_MapWidth) throw exception("Texture dimensions exceeded maximum allowable"); // Render the glyphs and generate heightmaps. Place heightmaps in the // locations set aside in the texture. g_DistanceMap = new float[g_MapWidth * g_MapHeight]; for (size_t x = g_MapWidth * g_MapHeight; x > 0; --x) g_DistanceMap[x - 1] = -1.0f; // Make sure all of the parameters are flushed to memory before we trigger the threads to paint. __faststorefence(); g_ReadyToPaint = true; // Also paint on the main thread PaintCharacters(g_DistanceMap, g_MapWidth, g_MapHeight); // Wait for all of the other threads if (numThreads > 0) { for_each( Threads.begin(), Threads.end(), []( std::thread& T ) { T.join(); } ); } uint8_t* compressedMap8 = new uint8_t[g_MapWidth * g_MapHeight]; for (uint32_t i = 0; i < g_MapWidth * g_MapHeight; ++i) compressedMap8[i] = (uint8_t)(g_DistanceMap[i] * 127.0f + 127.0f); // (Omit 255) WritePreviewBMP(outputName, compressedMap8, g_MapWidth, g_MapHeight); for (uint32_t i = 0; i < g_MapWidth * g_MapHeight; ++i) compressedMap8[i] = (int8_t)(g_DistanceMap[i] * 127.0f); // Append ".fnt" to file name char fileWithSuffix[256]; sprintf_s(fileWithSuffix, 256, "%s.fnt", outputName.c_str()); ofstream file; file.exceptions(ios_base::failbit | ios_base::badbit); file.open(fileWithSuffix, ios_base::out | ios_base::binary | ios_base::trunc); // The first part of the file is an identifier string to verify format and version const char* idString = "SDFFONT"; file.write(idString, 8); // The second part is information about the font struct FontHeader { uint8_t majorVersion; uint8_t minorVersion; uint16_t borderSize; uint16_t textureWidth; uint16_t textureHeight; uint16_t fontHeight; uint16_t advanceY; uint16_t numGlyphs; uint16_t searchDist; } header; header.majorVersion = kMajorVersion; header.minorVersion = kMinorVersion; header.borderSize = (uint8_t)g_borderSize; header.textureWidth = (uint16_t)g_MapWidth; header.textureHeight = (uint16_t)g_MapHeight; header.fontHeight = g_maxGlyphHeight; header.advanceY = g_fontAdvanceY; header.numGlyphs = g_numGlyphs; header.searchDist = g_maxDistance * 16; file.write((const char*)&header, sizeof(FontHeader)); for (size_t i = 0; i < g_numGlyphs; ++i) file.write( (const char*)&g_glyphs[i].c, 2 ); for (size_t i = 0; i < g_numGlyphs; ++i) file.write( (const char*)&g_glyphs[i].c + 2, sizeof(GlyphInfo) - 2 ); file.write((const char*)compressedMap8, g_MapWidth * g_MapHeight); file.close(); printf("Finished creating %s\n", fileWithSuffix); } void main( int argc, const char** argv ) { string inputFile = ""; string outputName = ""; string characterSet = "ASCII"; uint32_t size = 32; bool extendedASCII = false; bool verbose = true; try { if (argc < 2) throw exception("No font file specified"); inputFile = argv[1]; for (int arg = 2; arg < argc; ++arg) { if (argv[arg][0] != '-') throw exception("Malformed option"); if (arg + 1 == argc) throw exception("Missing operand"); else if (strcmp("-size", argv[arg]) == 0) size = atoi(argv[++arg]); else if (strcmp("-output", argv[arg]) == 0) outputName = argv[++arg]; else if (strcmp("-character_set", argv[arg]) == 0) characterSet = argv[++arg]; else if (strcmp("-border", argv[arg]) == 0) g_borderSize = atoi(argv[++arg]); else if (strcmp("-radius", argv[arg]) == 0) g_maxDistance = atoi(argv[++arg]); else throw exception("Invalid option"); } } catch (exception& e) { printf( "Error: %s\n\n" "Usage: %s <TrueType font file> [options]*\n\n" "Options:\n\n" "-character_set <filename | \"ASCII\" | \"EXTENDED\">\n" "\tA file containing the requested character set.\n\tWhen omitted, defaults to printable ASCII.\n" "-output <string>\n\tThe root name of resultant files.\n" "-size <integer>\n\tThe font pixel resolution.\n" "-radius <integer>\n\tThe search radius.\n\tDefaults to font size / 8.\n" "-border_size <integer>\n\tExtra spacing around glyphs for various effects.\n\tDefaults to the search radius.\n" "\n\nExample: %s myfont.ttf -character_set Japanese.txt -output japanese\n\n", e.what(), argv[0], argv[0]); return; } if (outputName.length() == 0) { outputName = inputFile.substr(0, inputFile.rfind('.')); char sizeAsString[128]; sprintf_s(sizeAsString, 128, "%u", size); outputName += sizeAsString; } if (g_maxDistance == 0) g_maxDistance = (uint16_t)size / 8; if (g_borderSize == 0) g_borderSize = g_maxDistance; if (_strcmpi(characterSet.c_str(), "extended") == 0) { characterSet = "ASCII"; extendedASCII = true; } printf("\n[ TrueType font compiler v.%d.%d ]\n\n", kMajorVersion, kMinorVersion); printf("A tool for generating height maps for enhanced cutout magnification of\nbitmapped text.\n\n"); printf("Font Name: \"%s\"\n", inputFile.c_str()); printf("Font Size: %u\n", size); printf("Border Size: %u\n", g_borderSize); if (extendedASCII) printf("Character Set: %s + Extended ASCII\n", characterSet.c_str()); else printf("Character Set: %s\n", characterSet.c_str()); printf("Output Name: %s\n", outputName.c_str()); printf("Threads: %u\n\n", std::thread::hardware_concurrency()); try { InitializeFont( inputFile.c_str(), size * 16 ); if (strcmp(characterSet.c_str(), "ASCII") == 0) { for (wchar_t c = 32; c < 127; ++c) { if (FT_Get_Char_Index(g_FreeTypeFace, c)) g_glyphs[g_numGlyphs++].c = c; } if (extendedASCII) for (wchar_t c = 128; c < 255; ++c) if (FT_Get_Char_Index(g_FreeTypeFace, c)) g_glyphs[g_numGlyphs++].c = c; } else { ifstream file; file.exceptions(ios_base::badbit); file.open(characterSet.c_str(), ios_base::in | ios_base::binary); set<wchar_t> charSet; wchar_t wtChar; file.read((char*)&wtChar, 2); // Check for unicode (UCS2) or ASCII if (wtChar == 0xFEFF) while (file.read((char*)&wtChar, 2)) charSet.insert(wtChar); else { // ASCII files don't have extra bytes at the beginning; rewind. file.seekg(0, ios_base::beg); char tChar = 0; while (file.read(&tChar, 1)) charSet.insert((wchar_t)tChar); } // Make sure the set includes all extended ascii (except white space) if (extendedASCII) for (wchar_t c = 32; c < 255; ++c) if (FT_Get_Char_Index(g_FreeTypeFace, c)) charSet.insert(c); file.close(); // Sift out the duplicates by iterating across the STL set for (set<wchar_t>::iterator it = charSet.begin(); it != charSet.end(); ++it) g_glyphs[g_numGlyphs++].c = *it; } CompileFont(inputFile, size, outputName); printf("\nComplete!\n"); //printf("Elapsed Time: %g sec\n", t.getElapsed()); } catch (wofstream::failure& e) { printf("\nFile I/O Exception\n%s\n", e.what()); } catch (exception& e) { printf("\nFailed: %s\n", e.what()); } catch (...) { printf("\nFailed\n"); } ShutdownFont(); }
34.370213
125
0.582766
[ "render", "vector" ]
b1f4951c1b752aea0140fa84e2fa20dda26edd61
697
cpp
C++
lib/ShieldControl/ShieldControl.cpp
pbeeken/VernierLabProj
786c89729e0725a0278c62475221218c95fe846c
[ "MIT" ]
null
null
null
lib/ShieldControl/ShieldControl.cpp
pbeeken/VernierLabProj
786c89729e0725a0278c62475221218c95fe846c
[ "MIT" ]
null
null
null
lib/ShieldControl/ShieldControl.cpp
pbeeken/VernierLabProj
786c89729e0725a0278c62475221218c95fe846c
[ "MIT" ]
null
null
null
/**************************************************************** * ShieldControl * This encapsulates the control and state engine for the Arduino * management of the Vernier Shield. There should be only one * instance of this object which is the data acquisition tool * Tested and developed in Platformio 3.1.0 * PBeeken ByramHills High School 7.12.2017 * * 12 Jul 2017- begin development of a binary communication protocol ****************************************************************/ #include <ShieldControl.h> #include <Streaming.h> ShieldControl::ShieldControl() { setState( CLEAR_ALL ); // booting } void ShieldControl::sendStatus() { Serial << "State: " << _state; }
26.807692
68
0.598278
[ "object" ]
b1f539b90444112eb450a38bbe825782142b54c2
14,469
cpp
C++
src/shell/commands/recovery.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
1,352
2017-10-16T03:24:54.000Z
2020-08-18T04:44:23.000Z
src/shell/commands/recovery.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
299
2017-10-19T05:33:32.000Z
2020-08-17T09:03:39.000Z
src/shell/commands/recovery.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
240
2017-10-16T05:57:04.000Z
2020-08-18T10:02:36.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 "shell/commands.h" bool recover(command_executor *e, shell_context *sc, arguments args) { static struct option long_options[] = {{"node_list_file", required_argument, 0, 'f'}, {"node_list_str", required_argument, 0, 's'}, {"wait_seconds", required_argument, 0, 'w'}, {"skip_bad_nodes", no_argument, 0, 'b'}, {"skip_lost_partitions", no_argument, 0, 'l'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0}}; std::string node_list_file; std::string node_list_str; int wait_seconds = 100; std::string output_file; bool skip_bad_nodes = false; bool skip_lost_partitions = false; optind = 0; while (true) { int option_index = 0; int c; c = getopt_long(args.argc, args.argv, "f:s:w:o:bl", long_options, &option_index); if (c == -1) break; switch (c) { case 'f': node_list_file = optarg; break; case 's': node_list_str = optarg; break; case 'w': if (!dsn::buf2int32(optarg, wait_seconds)) { fprintf(stderr, "parse %s as wait_seconds failed\n", optarg); return false; } break; case 'o': output_file = optarg; break; case 'b': skip_bad_nodes = true; break; case 'l': skip_lost_partitions = true; break; default: return false; } } if (wait_seconds <= 0) { fprintf(stderr, "invalid wait_seconds %d, should be positive number\n", wait_seconds); return false; } if (node_list_str.empty() && node_list_file.empty()) { fprintf(stderr, "should specify one of node_list_file/node_list_str\n"); return false; } if (!node_list_str.empty() && !node_list_file.empty()) { fprintf(stderr, "should only specify one of node_list_file/node_list_str\n"); return false; } std::vector<dsn::rpc_address> node_list; if (!node_list_str.empty()) { std::vector<std::string> tokens; dsn::utils::split_args(node_list_str.c_str(), tokens, ','); if (tokens.empty()) { fprintf(stderr, "can't parse node from node_list_str\n"); return true; } for (std::string &token : tokens) { dsn::rpc_address node; if (!node.from_string_ipv4(token.c_str())) { fprintf(stderr, "parse %s as a ip:port node failed\n", token.c_str()); return true; } node_list.push_back(node); } } else { std::ifstream file(node_list_file); if (!file) { fprintf(stderr, "open file %s failed\n", node_list_file.c_str()); return true; } std::string str; int lineno = 0; while (std::getline(file, str)) { lineno++; boost::trim(str); if (str.empty() || str[0] == '#' || str[0] == ';') continue; dsn::rpc_address node; if (!node.from_string_ipv4(str.c_str())) { fprintf(stderr, "parse %s at file %s line %d as ip:port failed\n", str.c_str(), node_list_file.c_str(), lineno); return true; } node_list.push_back(node); } if (node_list.empty()) { fprintf(stderr, "no node specified in file %s\n", node_list_file.c_str()); return true; } } dsn::error_code ec = sc->ddl_client->do_recovery( node_list, wait_seconds, skip_bad_nodes, skip_lost_partitions, output_file); if (!output_file.empty()) { std::cout << "recover complete with err = " << ec.to_string() << std::endl; } return true; } dsn::rpc_address diagnose_recommend(const ddd_partition_info &pinfo); dsn::rpc_address diagnose_recommend(const ddd_partition_info &pinfo) { if (pinfo.config.last_drops.size() < 2) return dsn::rpc_address(); std::vector<dsn::rpc_address> last_two_nodes(pinfo.config.last_drops.end() - 2, pinfo.config.last_drops.end()); std::vector<ddd_node_info> last_dropped; for (auto &node : last_two_nodes) { auto it = std::find_if(pinfo.dropped.begin(), pinfo.dropped.end(), [&node](const ddd_node_info &r) { return r.node == node; }); if (it->is_alive && it->is_collected) last_dropped.push_back(*it); } if (last_dropped.size() == 1) { const ddd_node_info &ninfo = last_dropped.back(); if (ninfo.last_committed_decree >= pinfo.config.last_committed_decree) return ninfo.node; } else if (last_dropped.size() == 2) { const ddd_node_info &secondary = last_dropped.front(); const ddd_node_info &latest = last_dropped.back(); // Select a best node to be the new primary, following the rule: // - choose the node with the largest last committed decree // - if last committed decree is the same, choose node with the largest ballot if (latest.last_committed_decree == secondary.last_committed_decree && latest.last_committed_decree >= pinfo.config.last_committed_decree) return latest.ballot >= secondary.ballot ? latest.node : secondary.node; if (latest.last_committed_decree > secondary.last_committed_decree && latest.last_committed_decree >= pinfo.config.last_committed_decree) return latest.node; if (secondary.last_committed_decree > latest.last_committed_decree && secondary.last_committed_decree >= pinfo.config.last_committed_decree) return secondary.node; } return dsn::rpc_address(); } bool ddd_diagnose(command_executor *e, shell_context *sc, arguments args) { static struct option long_options[] = {{"gpid", required_argument, 0, 'g'}, {"diagnose", no_argument, 0, 'd'}, {"auto_diagnose", no_argument, 0, 'a'}, {"skip_prompt", no_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0}}; std::string out_file; dsn::gpid id(-1, -1); bool diagnose = false; bool auto_diagnose = false; bool skip_prompt = false; optind = 0; while (true) { int option_index = 0; int c; c = getopt_long(args.argc, args.argv, "g:daso:", long_options, &option_index); if (c == -1) break; switch (c) { case 'g': int pid; if (id.parse_from(optarg)) { // app_id.partition_index } else if (sscanf(optarg, "%d", &pid) == 1) { // app_id id.set_app_id(pid); } else { fprintf(stderr, "ERROR: invalid gpid %s\n", optarg); return false; } break; case 'd': diagnose = true; break; case 'a': auto_diagnose = true; break; case 's': skip_prompt = true; break; case 'o': out_file = optarg; break; default: return false; } } std::vector<ddd_partition_info> ddd_partitions; ::dsn::error_code ret = sc->ddl_client->ddd_diagnose(id, ddd_partitions); if (ret != dsn::ERR_OK) { fprintf(stderr, "ERROR: DDD diagnose failed with err = %s\n", ret.to_string()); return true; } std::streambuf *buf; std::ofstream of; if (!out_file.empty()) { of.open(out_file); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); out << "Total " << ddd_partitions.size() << " ddd partitions:" << std::endl; out << std::endl; int proposed_count = 0; int i = 0; for (const ddd_partition_info &pinfo : ddd_partitions) { out << "(" << ++i << ") " << pinfo.config.pid.to_string() << std::endl; out << " config: ballot(" << pinfo.config.ballot << "), " << "last_committed(" << pinfo.config.last_committed_decree << ")" << std::endl; out << " ----" << std::endl; dsn::rpc_address latest_dropped, secondary_latest_dropped; if (pinfo.config.last_drops.size() > 0) latest_dropped = pinfo.config.last_drops[pinfo.config.last_drops.size() - 1]; if (pinfo.config.last_drops.size() > 1) secondary_latest_dropped = pinfo.config.last_drops[pinfo.config.last_drops.size() - 2]; int j = 0; for (const ddd_node_info &n : pinfo.dropped) { char time_buf[30]; ::dsn::utils::time_ms_to_string(n.drop_time_ms, time_buf); out << " dropped[" << j++ << "]: " << "node(" << n.node.to_string() << "), " << "drop_time(" << time_buf << "), " << "alive(" << (n.is_alive ? "true" : "false") << "), " << "collected(" << (n.is_collected ? "true" : "false") << "), " << "ballot(" << n.ballot << "), " << "last_committed(" << n.last_committed_decree << "), " << "last_prepared(" << n.last_prepared_decree << ")"; if (n.node == latest_dropped) out << " <== the latest"; else if (n.node == secondary_latest_dropped) out << " <== the secondary latest"; out << std::endl; } out << " ----" << std::endl; j = 0; for (const ::dsn::rpc_address &r : pinfo.config.last_drops) { out << " last_drops[" << j++ << "]: " << "node(" << r.to_string() << ")"; if (j == (int)pinfo.config.last_drops.size() - 1) out << " <== the secondary latest"; else if (j == (int)pinfo.config.last_drops.size()) out << " <== the latest"; out << std::endl; } out << " ----" << std::endl; out << " ddd_reason: " << pinfo.reason << std::endl; if (diagnose) { out << " ----" << std::endl; dsn::rpc_address primary = diagnose_recommend(pinfo); out << " recommend_primary: " << (primary.is_invalid() ? "none" : primary.to_string()); if (primary == latest_dropped) out << " <== the latest"; else if (primary == secondary_latest_dropped) out << " <== the secondary latest"; out << std::endl; bool skip_this = false; if (!primary.is_invalid() && !auto_diagnose && !skip_prompt) { do { std::cout << " > Are you sure to use the recommend primary? [y/n/s(skip)]: "; char c; std::cin >> c; if (c == 'y') { break; } else if (c == 'n') { primary.set_invalid(); break; } else if (c == 's') { skip_this = true; std::cout << " > You have choosed to skip diagnosing this partition." << std::endl; break; } } while (true); } if (primary.is_invalid() && !skip_prompt && !skip_this) { do { std::cout << " > Please input the primary node: "; std::string addr; std::cin >> addr; if (primary.from_string_ipv4(addr.c_str())) { break; } else { std::cout << " > Sorry, you have input an invalid node address." << std::endl; } } while (true); } if (!primary.is_invalid() && !skip_this) { dsn::replication::configuration_balancer_request request; request.gpid = pinfo.config.pid; request.action_list = { new_proposal_action(primary, primary, config_type::CT_ASSIGN_PRIMARY)}; request.force = false; dsn::error_code err = sc->ddl_client->send_balancer_proposal(request); out << " propose_request: propose -g " << request.gpid.to_string() << " -p ASSIGN_PRIMARY -t " << primary.to_string() << " -n " << primary.to_string() << std::endl; out << " propose_response: " << err.to_string() << std::endl; proposed_count++; } else { out << " propose_request: none" << std::endl; } } out << std::endl; out << "Proposed count: " << proposed_count << "/" << ddd_partitions.size() << std::endl; out << std::endl; } std::cout << "Diagnose ddd done." << std::endl; return true; }
38.687166
100
0.503214
[ "vector" ]
b1f9af47f6cf3cb2e764d809a2c6a8e8f48fb37d
1,073
cpp
C++
src/Street.cpp
TheusStremens/mark-simulator
a4a2c993669f669f7004e2588d4b6ba7953b9c89
[ "MIT" ]
null
null
null
src/Street.cpp
TheusStremens/mark-simulator
a4a2c993669f669f7004e2588d4b6ba7953b9c89
[ "MIT" ]
null
null
null
src/Street.cpp
TheusStremens/mark-simulator
a4a2c993669f669f7004e2588d4b6ba7953b9c89
[ "MIT" ]
null
null
null
#include <iostream> #include "Vehicle.hpp" #include "Intersection.hpp" #include "Street.hpp" Street::Street() { _type = ObjectType::objectStreet; } Street::Street(StreetOrientation orientation, bool is_loop_image_street) : _orientation(orientation), _is_loop_image_street(is_loop_image_street) { _type = ObjectType::objectStreet; } void Street::setIntersectionA(std::shared_ptr<Intersection> intersection) { _intersection_A = intersection; // Add this street to list of streets connected to the intersection. intersection->addStreet(get_shared_this()); } void Street::setIntersectionB(std::shared_ptr<Intersection> intersection) { _intersection_B = intersection; // Add this street to list of streets connected to the intersection. intersection->addStreet(get_shared_this()); } std::vector<std::shared_ptr<Lane>> Street::getLanesByDirection(Direction lane_direction) { std::vector<std::shared_ptr<Lane>> result; for (auto lane : _lanes) { if (lane->getDirection() == lane_direction) result.push_back(lane); } return result; }
24.953488
73
0.754893
[ "vector" ]
b1fbc68f0cc9f65096361ae4e5eac9abb6336fca
8,518
hpp
C++
src/lib/helper/parallel_sort.hpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
7
2017-11-13T11:02:59.000Z
2022-02-05T11:49:35.000Z
src/lib/helper/parallel_sort.hpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
null
null
null
src/lib/helper/parallel_sort.hpp
EvilMcJerkface/hyrise-v1
d97fa0df5b9e2b9aaa78865c010e93173404086d
[ "MIT" ]
6
2017-10-19T13:34:08.000Z
2020-11-30T13:14:47.000Z
// Copyright (c) 2012 Hasso-Plattner-Institut fuer Softwaresystemtechnik GmbH. All rights reserved. #pragma once #include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> #include <pthread.h> #include <sys/time.h> #include <queue> #include <assert.h> template <class T, void (T::*mem_fn)(void*)> void* thunk(void* p) { std::pair<void*, void*>* a = static_cast<std::pair<void*, void*>*>(p); (static_cast<T*>(a->first)->*mem_fn)(a->second); delete a; return 0; } template <typename T> class ParallelSort { typedef struct { std::vector<T>* data; size_t begin; size_t end; } sort_arg_t; typedef struct { std::vector<T>* data; size_t begin; size_t end; bool delete_data_when_done; } merge_arg_t; class merge_data_t { public: T value; size_t slice; size_t pos; friend bool operator<(const merge_data_t& a, const merge_data_t& b) { return a.value >= b.value; } }; std::queue<merge_arg_t> pending_parts; unsigned remaining_parts; pthread_mutex_t parts_mutex; pthread_mutex_t parts_exist_mutex; std::vector<T>* data; size_t thread_count; void sort_thread(void* arg) { std::sort(((sort_arg_t*)arg)->data->begin() + ((sort_arg_t*)arg)->begin, ((sort_arg_t*)arg)->data->begin() + ((sort_arg_t*)arg)->end); } void merge_thread(void* arg) { merge_arg_t a, b, c; bool cont, quit; while (true) { cont = false; quit = false; size_t waiting = 0, remaining = 0; while (true) { pthread_mutex_lock(&parts_mutex); waiting = pending_parts.size(); remaining = remaining_parts; pthread_mutex_unlock(&parts_mutex); if (waiting >= 2) { pthread_mutex_lock(&parts_mutex); a = pending_parts.front(); pending_parts.pop(); b = pending_parts.front(); pending_parts.pop(); remaining_parts -= 1; pthread_mutex_unlock(&parts_mutex); break; } else if (waiting + remaining >= 2) { if (pthread_mutex_trylock(&parts_exist_mutex) != 0) { return; } } else { return; } } c.data = merge_sorted(a, b); c.begin = 0; c.end = c.data->size(); c.delete_data_when_done = true; pthread_mutex_lock(&parts_mutex); pending_parts.push(c); if (pending_parts.size() <= 2) { pthread_mutex_trylock(&parts_exist_mutex); pthread_mutex_unlock(&parts_exist_mutex); } pthread_mutex_unlock(&parts_mutex); } } static std::vector<T>* merge_sorted(merge_arg_t left, merge_arg_t right) { std::vector<T>* out = new std::vector<T>(); size_t i_left = left.begin, i_right = right.begin; while (i_left < left.end && i_right < right.end) { if ((*(left.data))[i_left] < (*(right.data))[i_right]) { out->push_back((*(left.data))[i_left++]); } else { out->push_back((*(right.data))[i_right++]); } } while (i_left < left.end) { out->push_back((*(left.data))[i_left++]); } while (i_right < right.end) { out->push_back((*(right.data))[i_right++]); } // assert((left.end - left.begin) + (right.end - right.begin) == out->size()); if (left.delete_data_when_done) { delete left.data; } if (right.delete_data_when_done) { delete right.data; } return out; } public: ParallelSort(std::vector<T>* _data, size_t _thread_count) : data(_data), thread_count(_thread_count) {} void sort() { sort_arg_t* thread_data; // struct timeval t1, t2; // gettimeofday(&t1, nullptr); if (thread_count == 1) { std::sort(data->begin(), data->end()); } // divide input data on threads for sorting else { pthread_t* threads = new pthread_t[thread_count]; thread_data = new sort_arg_t[thread_count]; size_t begin = 0; size_t per_thread = data->size() / thread_count; size_t remainder = data->size() - per_thread * thread_count; for (int i = 0; i < thread_count; i++) { size_t size = per_thread + (i < remainder ? 1 : 0); thread_data[i].data = data; thread_data[i].begin = begin; thread_data[i].end = begin + size; begin += size; } for (int i = 0; i < thread_count; i++) { pthread_create(&threads[i], nullptr, thunk<ParallelSort, &ParallelSort::sort_thread>, new std::pair<void*, void*>(this, &thread_data[i])); } for (int i = 0; i < thread_count; i++) { pthread_join(threads[i], nullptr); } delete threads; } // gettimeofday(&t2, nullptr); // printf("%f,", t2.tv_sec + (double)t2.tv_usec / 1000000 - t1.tv_sec - (double)t1.tv_usec / 1000000); // gettimeofday(&t1, nullptr); if (thread_count == 1) { } // uses a single 2-way merge to merge the two sorted parts else if (thread_count == 2) { merge_arg_t a, b; a.data = thread_data[0].data; a.begin = thread_data[0].begin; a.end = thread_data[0].end; a.delete_data_when_done = false; b.data = thread_data[1].data; b.begin = thread_data[1].begin; b.end = thread_data[1].end; b.delete_data_when_done = false; std::vector<T>* out = ParallelSort::merge_sorted(a, b); data->swap(*out); delete out; } // uses a single n-way merge to merge the sorted parts. // this is about 2x slower than the solution below // else { // std::vector<T> *out = new std::vector<T>(); // merge_data_t d; // // std::priority_queue<merge_data_t> heap; // // for (int i = 0; i < thread_count; i++) { // d.pos = thread_data[i].begin; // d.value = (*(thread_data[i].data))[d.pos]; // d.slice = i; // heap.push(d); // } // // while (heap.size() > 0) { // d = heap.top(); // heap.pop(); // // out->push_back(d.value); // // d.pos++; // if (d.pos < thread_data[d.slice].end) { // d.value = (*(thread_data[d.slice].data))[d.pos]; // heap.push(d); // } // } // data->swap(*out); // delete out; // } // uses threaded 2-way merges to merge pairs of sorted parts until // only one big sorted part is left else { pthread_mutex_init(&parts_mutex, nullptr); pthread_mutex_init(&parts_exist_mutex, nullptr); size_t merge_thread_count = thread_count / 2; if (merge_thread_count < 2) { merge_thread_count = 2; } remaining_parts = 0; for (int i = 0; i < thread_count; i++) { merge_arg_t a; a.data = thread_data[i].data; a.begin = thread_data[i].begin; a.end = thread_data[i].end; a.delete_data_when_done = false; pending_parts.push(a); remaining_parts++; } pthread_mutex_lock(&parts_exist_mutex); pthread_t* threads = new pthread_t[merge_thread_count]; for (int i = 0; i < merge_thread_count; i++) { pthread_create(&threads[i], nullptr, thunk<ParallelSort, &ParallelSort::merge_thread>, new std::pair<void*, void*>(this, nullptr)); } for (int i = 0; i < merge_thread_count; i++) { pthread_join(threads[i], nullptr); } delete threads; pthread_mutex_destroy(&parts_mutex); pthread_mutex_destroy(&parts_exist_mutex); merge_arg_t res = pending_parts.front(); data->swap(*res.data); delete res.data; } // gettimeofday(&t2, nullptr); // printf("%f\n", t2.tv_sec + (double)t2.tv_usec / 1000000 - t1.tv_sec - (double)t1.tv_usec / 1000000); if (thread_count > 1) { delete thread_data; } } static void sort(std::vector<T>* data, size_t thread_count) { ParallelSort s(data, thread_count); s.sort(); } };
28.205298
116
0.540268
[ "vector" ]
b1fe7921cfb3d1200dbeb485741a98acea28e4a7
3,416
cc
C++
core/optimizer.cc
tintor/mono
396edd39e45f536cac91b1fa6524f019244e4549
[ "Apache-2.0" ]
1
2020-09-27T05:07:20.000Z
2020-09-27T05:07:20.000Z
core/optimizer.cc
tintor/mono
396edd39e45f536cac91b1fa6524f019244e4549
[ "Apache-2.0" ]
null
null
null
core/optimizer.cc
tintor/mono
396edd39e45f536cac91b1fa6524f019244e4549
[ "Apache-2.0" ]
null
null
null
#include "core/optimizer.h" #include "core/numeric.h" #include "core/timestamp.h" void Optimizer::Optimize(span<ParamT *> params) { for (auto p : params) { Timestamp ts; EACH(p->v) p->v[i] -= alpha * p->g[i]; p->backward_ticks += ts.elapsed(); } } void Momentum::Optimize(span<ParamT *> params) { if (ags.size() != params.size()) { ags.resize(params.size()); FOR(i, params.size()) ags[i].reshape(params[i]->shape()); } momentum_exp *= momentum; float alpha_with_correction = alpha / (1 - momentum_exp); FOR(j, params.size()) { Timestamp ts; vtensor &v = params[j]->v, &g = params[j]->g, &ag = ags[j]; EACH(v) { ag[i] = momentum * ag[i] + (1 - momentum) * g[i]; v[i] -= alpha_with_correction * ag[i]; } params[j]->backward_ticks += ts.elapsed(); } } template <bool Correct> void RMSPropUpdate(ParamT *p, tensor agg, float alpha, float rmsprop, float rmsprop_correction, float rmsprop_eps) { Timestamp ts; vtensor &v = p->v, &g = p->g; EACH(v) { agg[i] = rmsprop * agg[i] + (1 - rmsprop) * sqr(g[i]); auto a = Correct ? (agg[i] * rmsprop_correction) : agg[i]; v[i] -= alpha * g[i] / sqrt(a + rmsprop_eps); } p->backward_ticks += ts.elapsed(); } void RMSProp::Optimize(span<ParamT *> params) { if (aggs.size() != params.size()) { aggs.resize(params.size()); FOR(i, params.size()) aggs[i].reshape(params[i]->shape()); } rmsprop_exp *= rmsprop; float rmsprop_correction = 1 / (1 - rmsprop_exp); if (rmsprop_correction >= 0.999999f) { FOR(j, params.size()) { RMSPropUpdate<false>(params[j], aggs[j], alpha, rmsprop, rmsprop_correction, rmsprop_eps); } } else { FOR(j, params.size()) { RMSPropUpdate<false>(params[j], aggs[j], alpha, rmsprop, 1, rmsprop_eps); } } } template <bool Correct> void AdamUpdate(ParamT *p, tensor ag, tensor agg, float alpha_with_correction, float momentum, float rmsprop, float rmsprop_correction, float rmsprop_eps) { Timestamp ts; vtensor &v = p->v, &g = p->g; EACH(v) { ag[i] = momentum * ag[i] + (1 - momentum) * g[i]; agg[i] = rmsprop * agg[i] + (1 - rmsprop) * sqr(g[i]); auto a = Correct ? (agg[i] * rmsprop_correction) : agg[i]; v[i] -= alpha_with_correction * ag[i] / sqrt(a + rmsprop_eps); } p->backward_ticks += ts.elapsed(); } void Adam::Optimize(span<ParamT *> params) { if (ags.size() != params.size()) { ags.resize(params.size()); aggs.resize(params.size()); FOR(i, params.size()) ags[i].reshape(params[i]->shape()); FOR(i, params.size()) aggs[i].reshape(params[i]->shape()); } momentum_exp *= momentum; float alpha_with_correction = alpha / (1 - momentum_exp); rmsprop_exp *= rmsprop; float rmsprop_correction = 1 / (1 - rmsprop_exp); if (rmsprop_correction >= 0.999999f) { FOR(j, params.size()) { AdamUpdate<true>(params[j], ags[j], aggs[j], alpha_with_correction, momentum, rmsprop, rmsprop_correction, rmsprop_eps); } } else { FOR(j, params.size()) { AdamUpdate<false>(params[j], ags[j], aggs[j], alpha_with_correction, momentum, rmsprop, 1, rmsprop_eps); } } }
32.846154
118
0.567916
[ "shape" ]
5904ba5ff409d5978114b3cc5780fd92db6933f7
21,277
cpp
C++
Source/VRTemplate/Interactables/GrabbableSkelMesh.cpp
Lewisscrivens/VRTemplate
c4ec89097fef3a6691b28771c514122b36df312a
[ "MIT" ]
null
null
null
Source/VRTemplate/Interactables/GrabbableSkelMesh.cpp
Lewisscrivens/VRTemplate
c4ec89097fef3a6691b28771c514122b36df312a
[ "MIT" ]
null
null
null
Source/VRTemplate/Interactables/GrabbableSkelMesh.cpp
Lewisscrivens/VRTemplate
c4ec89097fef3a6691b28771c514122b36df312a
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Interactables/GrabbableSkelMesh.h" #include "Components/StaticMeshComponent.h" #include "Components/SkeletalMeshComponent.h" #include "Components/ShapeComponent.h" #include "Components/BoxComponent.h" #include "Player/VRPhysicsHandleComponent.h" #include "GameFramework/PlayerController.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/KismetSystemLibrary.h" #include "Engine/World.h" #include "Player/VRPawn.h" #include "Player/VRHand.h" #include "DrawDebugHelpers.h" #include "Engine/SkeletalMesh.h" #include "ReferenceSkeleton.h" #include "Kismet/KismetSystemLibrary.h" #include "PhysicsEngine/BodyInstance.h" #include "TimerManager.h" #include "Kismet/GameplayStatics.h" #include "Project/EffectsContainer.h" #include "Sound/SoundBase.h" DEFINE_LOG_CATEGORY(LogGrabbableSkelComp); UGrabbableSkelMesh::UGrabbableSkelMesh() { // Setup grabbable collision properties. SetCollisionProfileName("Interactable"); ComponentTags.Add("Grabbable"); SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); SetUseCCD(true); bMultiBodyOverlap = true; SetGenerateOverlapEvents(true); SetNotifyRigidBodyCollision(true); // Defaults. handRef = nullptr; otherHandRef = nullptr; boneToGrab = NAME_None; snapToHandRotationOffset = FRotator::ZeroRotator; grabbed = false; grabFromClosestBone = false; softHandle = false; checkCollision = true; centerPhysicsJoint = true; adjustInertiaFromArray = true; timeToLerp = 0.4f; lerping = false; hapticIntensityMultiplier = 1.0f; #if DEVELOPMENT debug = false; #endif // Initialise default interface variables. interactableSettings.grabHandleData.handleDataEnabled = true; interactableSettings.grabHandleData.softAngularConstraint = false; interactableSettings.grabHandleData.softLinearConstraint = false; interactableSettings.grabHandleData.interpolate = false; interactableSettings.grabHandleData.interpSpeed = 10.0f; interactableSettings.handMinRumbleDistance = 10.0f; interactableSettings.releaseDistance = 30.0f; } void UGrabbableSkelMesh::BeginPlay() { Super::BeginPlay(); // Disable hand distance if collision is disabled to stop comp being released on collision. if (!checkCollision) interactableSettings.canRelease = false; // Decide weather grab closest bone is enabled or disabled. if (boneToGrab == NAME_None) grabFromClosestBone = true; // Setup default impact haptic effect and audio. if (impactSoundOverride) impactSound = impactSoundOverride; else if (AVRPawn* pawn = Cast<AVRPawn>(GetWorld()->GetFirstPlayerController()->GetPawn())) { if (USoundBase* soundToUse = pawn->GetPawnEffects()->GetAudioEffect("DefaultCollision")) impactSound = soundToUse; } else UE_LOG(LogGrabbableSkelComp, Log, TEXT("The grabbable skeletal component %s, cannot find impact audio from override or the pawns effects container."), *GetName()); // Get haptic effect to play on collisions. if (collisionFeedbackOverride) collisionFeedback = collisionFeedbackOverride; else if (AVRPawn* pawn = Cast<AVRPawn>(GetWorld()->GetFirstPlayerController()->GetPawn())) { if (UHapticFeedbackEffect_Base* feedbackEffect = pawn->GetPawnEffects()->GetFeedbackEffect("DefaultCollision")) collisionFeedback = feedbackEffect; } else UE_LOG(LogGrabbableSkelComp, Log, TEXT("The grabbable skeletal component %s, cannot find haptic effect from override or the pawns effects container."), *GetName()); // Enable hit events and bind to this classes function. SetNotifyRigidBodyCollision(true); BodyInstance.SetInstanceNotifyRBCollision(true); if (!OnComponentHit.Contains(this, "OnHit")) this->OnComponentHit.AddDynamic(this, &UGrabbableSkelMesh::OnHit); } void UGrabbableSkelMesh::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { if (!lerping && OtherComp) { // Prevents any hitting components that are either balanced on the grabbable or the grabbable balanced on the hand from calling impact sounds and haptic effects. if (UPrimitiveComponent* hittingComp = Cast<UPrimitiveComponent>(OtherComp)) { if (FMath::IsNearlyEqual(hittingComp->GetPhysicsLinearVelocity().Size(), GetPhysicsLinearVelocity().Size(), 15.0f)) return; } // Check if the hit actor is a hand, therefor rumble the hand. if (AVRHand* hand = Cast<AVRHand>(OtherActor)) { // Calculate intensity and play bot haptic and the sound if they are currently set. float rumbleIntesity = FMath::Clamp(hand->handVelocity.Size() / 250.0f, 0.0f, 1.0f); if (collisionFeedback) hand->PlayFeedback(collisionFeedback, rumbleIntesity * hapticIntensityMultiplier); if (impactSound) hand->PlaySound(impactSound, rumbleIntesity); // If a hand is holding this class goto the area in this function that rumbles the holding hand. if (handRef) goto RumbleHoldingHand; } // Play impact sound at location of grabbable if it is hit by something other than an actor. else { RumbleHoldingHand: float impulseSize = FMath::Abs(NormalImpulse.Size()); float currentZ = GetComponentLocation().Z; // If the impulse is big enough and the grabbable is not rolling/sliding along the floor. if (!FMath::IsNearlyEqual(currentZ, lastZ, 0.1f) && GetPhysicsLinearVelocity().Size() >= 50.0f) { // Get volume from current intensity and check if the sound should be played. float rumbleIntesity = FMath::Clamp(impulseSize / (1200.0f * GetMass()), 0.1f, 1.0f); // If the audio has a valid sound to play. Make sure the sound was not played within the past 0.3 seconds. if (rumbleIntesity > lastRumbleIntensity && lastImpactSoundTime <= GetWorld()->GetTimeSeconds() + 0.3f) { // If sound is intialised play it. if (impactSound) { // Don't play again for set amount of time. lastImpactSoundTime = GetWorld()->GetTimeSeconds(); lastRumbleIntensity = rumbleIntesity; // Play sound effect. UGameplayStatics::PlaySoundAtLocation(GetWorld(), impactSound, GetComponentLocation(), rumbleIntesity); // Set timer to set lastRumbleIntensity back to 0.0f once the sound has played. FTimerDelegate timerDel; timerDel.BindUFunction(this, TEXT("ResetLastRumbleIntensity")); GetWorld()->GetTimerManager().ClearTimer(lastRumbleHandle); GetWorld()->GetTimerManager().SetTimer(lastRumbleHandle, timerDel, impactSound->GetDuration(), true); } } } } } // Save the last hit time. lastHitTime = GetWorld()->GetTimeSeconds(); // Save last Z. NOTE: Bug fix, stops the impact sound from triggering when the ball is rolling, lastZ = GetComponentLocation().Z; } void UGrabbableSkelMesh::ResetLastRumbleIntensity() { lastRumbleIntensity = 0.0f; } bool UGrabbableSkelMesh::GetRecentlyHit() { return GetWorld()->GetTimeSeconds() - lastHitTime <= 0.2f; } void UGrabbableSkelMesh::PickupPhysicsHandle(AVRHand* hand) { // Setup the closest body to the controller, but if the boneToGrab had a name preset grab that bone instead. // OR the second hand is grabbing this component. FName boneName = NAME_None; if (grabFromClosestBone) { if (otherHandRef && otherHandRef == hand) { otherBoneToGrab = UpdateComponentsClosestBody(hand); boneName = otherBoneToGrab; } else { boneToGrab = UpdateComponentsClosestBody(hand); boneName = boneToGrab; } } // Ensure physics is enabled. SetSimulatePhysics(true); // Create joint between hand and physics object and enable physics to handle any collisions. FVector locationToGrab; FRotator rotationToGrab; if (centerPhysicsJoint) { locationToGrab = GetBoneLocation(boneName); rotationToGrab = GetBoneQuaternion(boneName).Rotator(); } else { locationToGrab = hand->grabCollider->GetComponentLocation(); rotationToGrab = hand->grabCollider->GetComponentRotation(); } // Grab the mesh using the hands physics handle. hand->grabHandle->CreateJointAndFollowLocationWithRotation(this, hand->grabCollider, boneName, locationToGrab, rotationToGrab, interactableSettings.grabHandleData); } void UGrabbableSkelMesh::DropPhysicsHandle(AVRHand* hand) { // Destroy the joint created by the physics handle. hand->grabHandle->DestroyJoint(); // If body instance was changed reset. if (softHandle) ToggleSoftPhysicsHandle(false); } FName UGrabbableSkelMesh::UpdateComponentsClosestBody(AVRHand* hand) { // Find the closest bone and set it as the bone to grab. FClosestPointOnPhysicsAsset closest; bool foundBone = GetClosestPointOnPhysicsAsset(hand->grabCollider->GetComponentLocation(), closest, false); if (foundBone) return closest.BoneName; else return NAME_None; } bool UGrabbableSkelMesh::IsMeshGrabbed() { return grabbed; } FTransform UGrabbableSkelMesh::GetGrabbedTransform() { return FTransform(worldRotationOffset, worldPickupOffset, FVector(1.0f)); } void UGrabbableSkelMesh::LerpingBack(float deltaTime) { // Get the current target location of the joint from the current grabbed bones world position. FTransform currentTargetTransform; if (centerPhysicsJoint) currentTargetTransform = GetBoneTransform(GetBoneIndex(boneToGrab)); else { FTransform boneTransform = GetBodyInstance(boneToGrab)->GetUnrealWorldTransform(); currentTargetTransform.SetLocation(boneTransform.TransformPositionNoScale(originalBoneOffset.GetLocation())); currentTargetTransform.SetRotation(boneTransform.TransformRotation(originalBoneOffset.GetRotation())); } // Lerp the transform from currentTargetTransform to the endTargetTransform and apply the location to the grabHandle (Physics handle grabbing this comp). float lerpProgress = GetWorld()->GetTimeSeconds() - lerpStartTime; float alpha = FMath::Clamp(lerpProgress / timeToLerp, 0.0f, 1.0f); FTransform lerpedTransform = UVRFunctionLibrary::LerpT(currentTargetTransform, handRef->grabHandle->GetTargetLocation(), alpha); handRef->grabHandle->SetTarget(lerpedTransform, true); // Once lerp is complete reset the joint values to track the hand movement again. if (alpha >= 1) ToggleLerping(false); #if DEVELOPMENT // Print if currently lerping. if (debug) UE_LOG(LogGrabbableSkelComp, Log, TEXT("The grabbable skeletal mesh %s, is lerping back to the hand %s."), *GetName(), *handRef->GetName()); #endif } void UGrabbableSkelMesh::ToggleLerping(bool on) { if (on) { // Setup handle to allow custom target location for lerping back to the hand. FPhysicsHandleData newData = handRef->grabHandle->handleData; newData.updateTargetLocation = false; handRef->grabHandle->UpdateJointValues(newData); // Setup to lerp back to the hand. (Check and ran in dragging function...) lerping = true; lerpStartTime = GetWorld()->GetTimeSeconds(); // Set the joints target location to start at the bone locations joint location currently. FTransform newTargetTransform; if (centerPhysicsJoint) newTargetTransform = GetBoneTransform(GetBoneIndex(boneToGrab)); else { FTransform boneTransform = GetBodyInstance(boneToGrab)->GetUnrealWorldTransform(); newTargetTransform.SetLocation(boneTransform.TransformPositionNoScale(originalBoneOffset.GetLocation())); newTargetTransform.SetRotation(boneTransform.TransformRotation(originalBoneOffset.GetRotation())); } handRef->grabHandle->SetTarget(newTargetTransform, true); } else { // Reset anything that might still be enabled. FPhysicsHandleData newData = handRef->grabHandle->handleData; newData.updateTargetLocation = true; handRef->grabHandle->UpdateJointValues(newData); lerping = false; } } void UGrabbableSkelMesh::ToggleSoftPhysicsHandle(bool on) { // Ensure that the hand isn't null. if (handRef) { // Enable/Disable soft linear constraint... if (on) { // Play sound and haptic effects. float rumbleIntesity = FMath::Clamp(handRef->handVelocity.Size() / 250.0f, 0.0f, 1.0f); if (collisionFeedback) { handRef->PlayFeedback(collisionFeedback, rumbleIntesity * hapticIntensityMultiplier); // Also check if two handed grabbing mode is enabled and rumble both hands in this case. if (interactableSettings.twoHandedGrabbing && otherHandRef) { otherHandRef->PlayFeedback(collisionFeedback, rumbleIntesity * hapticIntensityMultiplier); } } // Play sound effect. UGameplayStatics::PlaySoundAtLocation(GetWorld(), impactSound, GetComponentLocation(), rumbleIntesity); // Make current bone act like larger bone, so it effects parent bones correctly when grabbed and in soft constraint mode. if (adjustInertiaFromArray) { FBodyInstance* bodyInst = GetBodyInstance(boneToGrab); originalIntertia = bodyInst->InertiaTensorScale; float intertiaMultiplier = 2.2f; bodyInst->InertiaTensorScale = originalIntertia * intertiaMultiplier; bodyInst->UpdateMassProperties(); } } else { // Reset bone inertia/mass properties if enabled. if (adjustInertiaFromArray) { GetBodyInstance(boneToGrab)->InertiaTensorScale = originalIntertia; GetBodyInstance(boneToGrab)->UpdateMassProperties(); } } // Update current soft handle value. handRef->grabHandle->ToggleDrive(on, on); if (interactableSettings.twoHandedGrabbing && otherHandRef) otherHandRef->grabHandle->ToggleDrive(on, on); softHandle = on; } } void UGrabbableSkelMesh::GrabPressed_Implementation(AVRHand* hand) { // Already grabbed and two handed mode is enabled. if (handRef && interactableSettings.twoHandedGrabbing) { // Save new hand and grab with physics handle. otherHandRef = hand; // Broadcast to delegate. OnMeshGrabbed.Broadcast(otherHandRef, this); } else { // Setup the hand reference. handRef = hand; grabbed = true; // Broadcast to delegate. OnMeshGrabbed.Broadcast(handRef, this); // If we don't have a pointer to the hand we have already been released by a delegate if (!handRef) return; // Save original offsets for checking again overlaps at current grabbed location and lerping back to the hand. if (checkCollision) { // Setup ignored actors for use in draggingImplementation. ignored.Add(GetOwner()); ignored.Add(handRef); // Get the original relative offset for the rotation and location when this is grabbed when compared to the hand scene component. FTransform targetTransform = handRef->grabCollider->GetComponentTransform(); FTransform boneTransform = GetBodyInstance(boneToGrab)->GetUnrealWorldTransform(); originalRelativePickupOffset = targetTransform.InverseTransformPositionNoScale(boneTransform.GetLocation()); originalRelativePickupRotation = targetTransform.InverseTransformRotation(boneTransform.GetRotation()).Rotator(); // Save offset bone so less calculations have to be done in the lerp function. originalBoneOffset.SetLocation(boneTransform.InverseTransformPositionNoScale(targetTransform.GetLocation())); originalBoneOffset.SetRotation(boneTransform.InverseTransformRotation(targetTransform.GetRotation())); } } // Grab with the correct method. PickupPhysicsHandle(hand); // NOTE: Temporary bug fix. After grabbed un-highlight everything. TArray<USceneComponent*> components; GetChildrenComponents(true, components); components.Add(this); for (USceneComponent* comp : components) { if (UPrimitiveComponent* isPrimitive = Cast<UPrimitiveComponent>(comp)) { if (isPrimitive->bRenderCustomDepth) { // Reset stencil value to 0 which has no post process material. isPrimitive->SetCustomDepthStencilValue(0); isPrimitive->SetRenderCustomDepth(false); } } } } void UGrabbableSkelMesh::GrabReleased_Implementation(AVRHand* hand) { // If dropped by a second grabbed hand. if (otherHandRef == hand) { // Reset mesh back to normal. DropPhysicsHandle(hand); // Broadcast released delegate. OnMeshReleased.Broadcast(handRef, this); //Reset default values. otherHandRef = nullptr; ignored.Remove(hand); return; } // Reset mesh back to normal. DropPhysicsHandle(hand); // Update velocity from hand movement when releasing this component. (BUG FIX) SetAllPhysicsLinearVelocity(handRef->handVelocity, false); SetAllPhysicsAngularVelocityInDegrees(handRef->handAngularVelocity, false); // Broadcast released delegate. OnMeshReleased.Broadcast(handRef, this); // Reset values to default. Do last. handRef = nullptr; grabbed = false; // Reset collision variables if enabled. if (checkCollision) { lerping = false; ignored.Empty(); } } void UGrabbableSkelMesh::Dragging_Implementation(float deltaTime) { if (handRef && checkCollision) { // Find the current pickup and rotation offset for where the grabbable should be. FVector grabbedBodyLocation = GetBodyInstance(boneToGrab)->GetUnrealWorldTransform().GetLocation(); FTransform controllerTransform = handRef->grabCollider->GetComponentTransform(); worldPickupOffset = controllerTransform.TransformPositionNoScale(originalRelativePickupOffset); worldRotationOffset = controllerTransform.TransformRotation(originalRelativePickupRotation.Quaternion()).Rotator(); // Update the hand grab distance to help hand class decide when to release this component. FVector currentRelativePickupOffset = worldPickupOffset - grabbedBodyLocation; lastHandGrabDistance = interactableSettings.handDistance; interactableSettings.handDistance = currentRelativePickupOffset.Size(); // If grabbed by two hands don't check for collisions as physics is always enabled. if (interactableSettings.twoHandedGrabbing && otherHandRef) { if (!softHandle) ToggleSoftPhysicsHandle(true); return; } // Update trace variables to check if the bones are too close to other bodies or static objects. FHitResult hitResult; FBodyInstance* currentGrabbedBody = GetBodyInstance(boneToGrab); FVector boneExtent = currentGrabbedBody->GetBodyBounds().GetExtent(); FTransform boneTransform = currentGrabbedBody->GetUnrealWorldTransform(); // Show debugging information if in editor and if debug is enabled. EDrawDebugTrace::Type trace = EDrawDebugTrace::None; #if DEVELOPMENT if (debug) trace = EDrawDebugTrace::ForOneFrame; #endif // If hit and stiff handle is enabled active soft handle. if (UKismetSystemLibrary::BoxTraceSingleByProfile(GetWorld(), boneTransform.GetLocation(), worldPickupOffset, boneExtent, worldRotationOffset, "Grabbable", false, ignored, trace, hitResult, true) || GetRecentlyHit()) { if (!softHandle) { ToggleSoftPhysicsHandle(true); if (lerping) ToggleLerping(false); #if DEVELOPMENT if (debug) UE_LOG(LogTemp, Warning, TEXT("SkeletalGrabbableMesh, %s is now using soft constraint on the physics handle."), *GetName()); #endif } } // Otherwise if soft handle is still active disable it. else if (softHandle) { ToggleSoftPhysicsHandle(false); if (!lerping) ToggleLerping(true); #if DEVELOPMENT if (debug) UE_LOG(LogTemp, Warning, TEXT("SkeletalGrabbableMesh, %s is now using interpolating back to the correct grabbed location."), *GetName()); #endif } // If lerping the handle location do so. if (lerping) LerpingBack(deltaTime); } } void UGrabbableSkelMesh::Overlapping_Implementation(AVRHand* hand) { IHandsInterface::Overlapping_Implementation(hand); } void UGrabbableSkelMesh::EndOverlapping_Implementation(AVRHand* hand) { IHandsInterface::EndOverlapping_Implementation(hand); } void UGrabbableSkelMesh::Teleported_Implementation() { if (handRef) { // Release, set new location and grab again. handRef->grabHandle->DestroyJoint(); // Get grabbed bone and controller transform. UPrimitiveComponent* targetComponent = handRef->grabCollider; FTransform controllerTransform = targetComponent->GetComponentTransform(); FTransform boneTransform = GetBodyInstance(boneToGrab)->GetUnrealWorldTransform(); // Get relative bone offset for location and rotation to the component itself in world space. FVector relBoneLoc = boneTransform.InverseTransformPositionNoScale(GetComponentLocation()); FQuat relBoneRot = boneTransform.InverseTransformRotation(GetComponentQuat()); // Get the world location expected for the grabbed bone. FVector newLoc = controllerTransform.TransformPositionNoScale(originalRelativePickupOffset); FQuat newRot = controllerTransform.TransformRotation(originalRelativePickupRotation.Quaternion()); // Get the component location and rotation relative to how the bone should be positioned. FTransform newTransform = FTransform(newRot, newLoc, FVector(1)); newLoc = newTransform.TransformPositionNoScale(relBoneLoc); newRot = newTransform.TransformRotation(relBoneRot); // Teleport this component to its new transform. this->SetWorldLocationAndRotation(newLoc, newRot, false, nullptr, ETeleportType::TeleportPhysics); // Re-Initialise the joint at the new location. handRef->grabHandle->CreateJointAndFollowLocationWithRotation(this, targetComponent, boneToGrab, targetComponent->GetComponentLocation(), targetComponent->GetComponentRotation(), interactableSettings.grabHandleData); } } FHandInterfaceSettings UGrabbableSkelMesh::GetInterfaceSettings_Implementation() { return interactableSettings; } void UGrabbableSkelMesh::SetInterfaceSettings_Implementation(FHandInterfaceSettings newInterfaceSettings) { interactableSettings = newInterfaceSettings; }
37.459507
218
0.772336
[ "mesh", "object", "transform" ]
5908d985a3173fad1fa8ba485fe5161a4976a247
16,441
cpp
C++
thrift/lib/cpp2/async/HeaderServerChannel.cpp
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
2,112
2015-01-02T11:34:27.000Z
2022-03-31T16:30:42.000Z
thrift/lib/cpp2/async/HeaderServerChannel.cpp
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
372
2015-01-05T10:40:09.000Z
2022-03-31T20:45:11.000Z
thrift/lib/cpp2/async/HeaderServerChannel.cpp
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
582
2015-01-03T01:51:56.000Z
2022-03-31T02:01:09.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/async/HeaderServerChannel.h> #include <exception> #include <utility> #include <folly/String.h> #include <folly/io/Cursor.h> #include <thrift/lib/cpp/transport/TTransportException.h> #include <thrift/lib/cpp2/async/HeaderChannelTrait.h> #include <thrift/lib/cpp2/protocol/Serializer.h> using folly::IOBuf; using folly::IOBufQueue; using std::make_unique; using std::pair; using std::unique_ptr; using namespace apache::thrift::transport; using namespace apache::thrift; using apache::thrift::TApplicationException; using apache::thrift::protocol::PROTOCOL_TYPES; using apache::thrift::server::TServerObserver; using folly::EventBase; namespace apache { namespace thrift { std::atomic<uint32_t> HeaderServerChannel::sample_(0); HeaderServerChannel::HeaderServerChannel( const std::shared_ptr<folly::AsyncTransport>& transport) : HeaderServerChannel(std::shared_ptr<Cpp2Channel>(Cpp2Channel::newChannel( transport, make_unique<ServerFramingHandler>(*this)))) {} HeaderServerChannel::HeaderServerChannel( const std::shared_ptr<Cpp2Channel>& cpp2Channel) : callback_(nullptr), arrivalSeqId_(1), lastWrittenSeqId_(0), sampleRate_(0), cpp2Channel_(cpp2Channel) {} void HeaderServerChannel::destroy() { DestructorGuard dg(this); if (callback_) { auto error = folly::make_exception_wrapper<TTransportException>("Channel destroyed"); callback_->channelClosed(std::move(error)); } cpp2Channel_->closeNow(); folly::DelayedDestruction::destroy(); } // Header framing unique_ptr<IOBuf> HeaderServerChannel::ServerFramingHandler::addFrame( unique_ptr<IOBuf> buf, THeader* header) { // Note: This THeader function may throw. However, we don't want to catch // it here, because this would send an empty message out on the wire. // Instead we have to catch it at sendMessage THeader::StringToStringMap persistentWriteHeaders; return header->addHeader( std::move(buf), persistentWriteHeaders, false /* Data already transformed in AsyncProcessor.h */); } std::tuple<unique_ptr<IOBuf>, size_t, unique_ptr<THeader>> HeaderServerChannel::ServerFramingHandler::removeFrame(IOBufQueue* q) { std::unique_ptr<THeader> header(new THeader(THeader::ALLOW_BIG_FRAMES)); // removeHeader will set seqid in header. // For older clients with seqid in the protocol, header // will dig in to the protocol to get the seqid correctly. if (!q || !q->front() || q->front()->empty()) { return make_tuple(std::unique_ptr<IOBuf>(), 0, nullptr); } std::unique_ptr<folly::IOBuf> buf; size_t remaining = 0; try { buf = header->removeHeader(q, remaining, channel_.persistentReadHeaders_); } catch (const std::exception& e) { LOG(ERROR) << "Received invalid request from client: " << folly::exceptionStr(e) << " " << getTransportDebugString(channel_.getTransport()); throw; } if (!buf) { return make_tuple(std::unique_ptr<IOBuf>(), remaining, nullptr); } CLIENT_TYPE ct = header->getClientType(); if (!HeaderChannelTrait::isSupportedClient(ct)) { LOG(ERROR) << "Server rejecting unsupported client type " << ct; HeaderChannelTrait::checkSupportedClient(ct); } // Check if protocol used in the buffer is consistent with the protocol // id in the header. folly::io::Cursor c(buf.get()); auto byte = c.read<uint8_t>(); // Initialize it to a value never used on the wire PROTOCOL_TYPES protInBuf = PROTOCOL_TYPES::T_DEBUG_PROTOCOL; if (byte == 0x82) { protInBuf = PROTOCOL_TYPES::T_COMPACT_PROTOCOL; } else if (byte == 0x80) { protInBuf = PROTOCOL_TYPES::T_BINARY_PROTOCOL; } else if (ct != THRIFT_HTTP_SERVER_TYPE) { LOG(ERROR) << "Received corrupted request from client: " << getTransportDebugString(channel_.getTransport()) << ". " << "Corrupted payload in header message. In message header, " << "protoId: " << header->getProtocolId() << ", " << "clientType: " << folly::to<std::string>(ct) << ". " << "First few bytes of payload: " << getTHeaderPayloadString(buf.get()); throw TTransportException( TTransportException::INVALID_STATE, "Receiving corrupted request from client"); } if (protInBuf != PROTOCOL_TYPES::T_DEBUG_PROTOCOL && header->getProtocolId() != protInBuf) { LOG(ERROR) << "Received corrupted request from client: " << getTransportDebugString(channel_.getTransport()) << ". " << "Protocol mismatch, in message header, protocolId: " << folly::to<std::string>(header->getProtocolId()) << ", " << "clientType: " << folly::to<std::string>(ct) << ", " << "in payload, protocolId: " << folly::to<std::string>(protInBuf) << ". First few bytes of payload: " << getTHeaderPayloadString(buf.get()); } return make_tuple(std::move(buf), 0, std::move(header)); } std::string HeaderServerChannel::getTHeaderPayloadString(IOBuf* buf) { auto len = std::min<size_t>(buf->length(), 20); return folly::cEscape<std::string>( folly::StringPiece((const char*)buf->data(), len)); } std::string HeaderServerChannel::getTransportDebugString( folly::AsyncTransport* transport) { if (!transport) { return std::string(); } auto ret = folly::to<std::string>( "(transport ", folly::demangle(typeid(*transport))); try { folly::SocketAddress addr; transport->getPeerAddress(&addr); folly::toAppend( ", address ", addr.getAddressStr(), ", port ", addr.getPort(), &ret); } catch (const std::exception&) { } ret += ')'; return ret; } // Client Interface HeaderServerChannel::HeaderRequest::HeaderRequest( HeaderServerChannel* channel, unique_ptr<IOBuf>&& buf, unique_ptr<THeader>&& header, const SamplingStatus& samplingStatus) : channel_(channel), header_(std::move(header)), samplingStatus_(samplingStatus) { this->buf_ = std::move(buf); } /** * send a reply to the client. * * Note that to be backwards compatible with thrift1, the generated * code calls sendReply(nullptr) for oneway calls where seqid != * ONEWAY_SEQ_ID. This is so that the sendCatchupRequests code runs * correctly for in-order responses to older clients. sendCatchupRequests * does not actually send null buffers, it just ignores them. * */ void HeaderServerChannel::HeaderRequest::sendReply( ResponsePayload&& response, MessageChannel::SendCallback* cb, folly::Optional<uint32_t>) { // timeoutHeader_ is set in ::sendTimeoutResponse below auto& header = timeoutHeader_ ? timeoutHeader_ : header_; if (!channel_->outOfOrder_.value()) { // In order processing, make sure the ordering is correct. if (InOrderRecvSeqId_ != channel_->lastWrittenSeqId_ + 1) { // Save it until we can send it in order. channel_->inOrderRequests_[InOrderRecvSeqId_] = std::make_tuple(cb, std::move(response).buffer(), std::move(header)); } else { // Send it now, and send any subsequent requests in order. channel_->sendCatchupRequests( std::move(response).buffer(), cb, header.get()); } } else { if (!response) { if (cb) { cb->messageSent(); } return; } try { // out of order, send as soon as it is done. channel_->sendMessage(cb, std::move(response).buffer(), header.get()); } catch (const std::exception& e) { LOG(ERROR) << "Failed to send message: " << e.what(); } } } void HeaderServerChannel::HeaderRequest::serializeAndSendError( apache::thrift::transport::THeader& header, TApplicationException& tae, const std::string& methodName, int32_t protoSeqId, MessageChannel::SendCallback* cb) { if (isOneway()) { sendReply(ResponsePayload{}, cb); return; } std::unique_ptr<folly::IOBuf> exbuf; uint16_t proto = header.getProtocolId(); try { exbuf = serializeError</*includeEnvelope=*/true>( proto, tae, methodName, protoSeqId); } catch (const TProtocolException& pe) { LOG(ERROR) << "serializeError failed. type=" << pe.getType() << " what()=" << pe.what(); channel_->closeNow(); return; } LegacySerializedResponse response{std::move(exbuf)}; auto [_, responsePayload] = std::move(response).extractPayload(/*includeEnvelope=*/true, proto); responsePayload.transform(header_->getWriteTransforms()); sendException(std::move(responsePayload), cb); } /** * Send a serialized error back to the client. * For a header server, this means serializing the exception, and setting * an error flag in the header. */ void HeaderServerChannel::HeaderRequest::sendErrorWrapped( folly::exception_wrapper ew, std::string exCode) { // Other types are unimplemented. DCHECK(ew.is_compatible_with<TApplicationException>()); header_->setHeader("ex", exCode); ew.with_exception([&](TApplicationException& tae) { std::unique_ptr<folly::IOBuf> exbuf; uint16_t proto = header_->getProtocolId(); try { exbuf = serializeError</*includeEnvelope=*/true>(proto, tae, getBuf()); } catch (const TProtocolException& pe) { LOG(ERROR) << "serializeError failed. type=" << pe.getType() << " what()=" << pe.what(); channel_->closeNow(); return; } LegacySerializedResponse response{std::move(exbuf)}; auto [mtype, responsePayload] = std::move(response).extractPayload(/*includeEnvelope=*/true, proto); responsePayload.transform(header_->getWriteTransforms()); if (mtype == MessageType::T_EXCEPTION) { sendException(std::move(responsePayload), nullptr); } else { sendReply(std::move(responsePayload), nullptr); } }); } void HeaderServerChannel::HeaderRequest::sendErrorWrapped( folly::exception_wrapper ew, std::string exCode, const std::string& methodName, int32_t protoSeqId, MessageChannel::SendCallback* cb) { // Other types are unimplemented. DCHECK(ew.is_compatible_with<TApplicationException>()); header_->setHeader("ex", exCode); ew.with_exception([&](TApplicationException& tae) { serializeAndSendError(*header_, tae, methodName, protoSeqId, cb); }); } void HeaderServerChannel::HeaderRequest::sendTimeoutResponse( const std::string& methodName, int32_t protoSeqId, MessageChannel::SendCallback* cb, const transport::THeader::StringToStringMap& headers, TimeoutResponseType responseType) { // Sending timeout response always happens on eb thread, while normal // request handling might still be work-in-progress on tm thread and // touches the per-request THeader at any time. This builds a new THeader // and only reads certain fields from header_. To avoid race condition, // DO NOT read any header from the per-request THeader. timeoutHeader_ = std::make_unique<THeader>(); timeoutHeader_->copyMetadataFrom(*header_); auto errorCode = responseType == TimeoutResponseType::QUEUE ? kServerQueueTimeoutErrorCode : kTaskExpiredErrorCode; timeoutHeader_->setHeader("ex", errorCode); auto errorMsg = responseType == TimeoutResponseType::QUEUE ? "Queue Timeout" : "Task expired"; for (const auto& it : headers) { timeoutHeader_->setHeader(it.first, it.second); } TApplicationException tae( TApplicationException::TApplicationExceptionType::TIMEOUT, errorMsg); serializeAndSendError(*timeoutHeader_, tae, methodName, protoSeqId, cb); } void HeaderServerChannel::sendCatchupRequests( std::unique_ptr<folly::IOBuf> next_req, MessageChannel::SendCallback* cb, THeader* header) { DestructorGuard dg(this); std::unique_ptr<THeader> header_ptr; while (true) { if (next_req) { try { sendMessage(cb, std::move(next_req), header); } catch (const std::exception& e) { LOG(ERROR) << "Failed to send message: " << e.what(); } } else if (nullptr != cb) { // There is no message (like a oneway req), but there is a callback cb->messageSent(); } lastWrittenSeqId_++; // Check for the next req auto next = inOrderRequests_.find(lastWrittenSeqId_ + 1); if (next != inOrderRequests_.end()) { next_req = std::move(std::get<1>(next->second)); cb = std::get<0>(next->second); header_ptr = std::move(std::get<2>(next->second)); header = header_ptr.get(); inOrderRequests_.erase(next); } else { break; } } } TServerObserver::SamplingStatus HeaderServerChannel::shouldSample( const apache::thrift::transport::THeader* header) const { bool isServerSamplingEnabled = (sampleRate_ > 0) && ((sample_++ % sampleRate_) == 0); bool isClientSamplingEnabled = header->getHeaders().find(kClientLoggingHeader.str()) != header->getHeaders().end(); return SamplingStatus(isServerSamplingEnabled, isClientSamplingEnabled); } // Interface from MessageChannel::RecvCallback void HeaderServerChannel::messageReceived( unique_ptr<IOBuf>&& buf, unique_ptr<THeader>&& header) { DestructorGuard dg(this); bool outOfOrder = (header->getFlags() & HEADER_FLAG_SUPPORT_OUT_OF_ORDER); if (!outOfOrder_.has_value()) { outOfOrder_ = outOfOrder; } else if (outOfOrder_.value() != outOfOrder) { LOG(ERROR) << "Channel " << (outOfOrder_.value() ? "" : "doesn't ") << "support out-of-order, but received a message with the " << "out-of-order bit " << (outOfOrder ? "set" : "unset"); messageReceiveErrorWrapped( folly::make_exception_wrapper<TTransportException>( "Bad out-of-order flag")); return; } if (callback_) { auto sampleStatus = shouldSample(header.get()); unique_ptr<HeaderRequest> request(new HeaderRequest( this, std::move(buf), std::move(header), sampleStatus)); if (!outOfOrder) { if (inOrderRequests_.size() > MAX_REQUEST_SIZE) { // There is probably nothing useful we can do here. LOG(WARNING) << "Hit in order request buffer limit"; auto ex = folly::make_exception_wrapper<TTransportException>( "Hit in order request buffer limit"); messageReceiveErrorWrapped(std::move(ex)); return; } if (!request->isOneway()) { // Create a new seqid for in-order messages because they might not // be sequential. This seqid is only used internally in // HeaderServerChannel request->setInOrderRecvSequenceId(arrivalSeqId_++); } } auto ew = folly::try_and_catch( [&]() { callback_->requestReceived(std::move(request)); }); if (ew) { LOG(WARNING) << "Could not parse request: " << ew.what(); messageReceiveErrorWrapped(std::move(ew)); return; } } } void HeaderServerChannel::messageChannelEOF() { DestructorGuard dg(this); auto ew = folly::make_exception_wrapper<TTransportException>("Channel Closed"); if (callback_) { callback_->channelClosed(std::move(ew)); } } void HeaderServerChannel::messageReceiveErrorWrapped( folly::exception_wrapper&& ex) { DestructorGuard dg(this); VLOG(1) << "Receive error: " << ex.what(); if (callback_) { callback_->channelClosed(std::move(ex)); } } void HeaderServerChannel::setCallback(ResponseChannel::Callback* callback) { HeaderServerChannel::Callback* cob = dynamic_cast<Callback*>(callback); DCHECK(!!cob == !!callback); // assert that dynamic cast succeeded callback_ = cob; if (cob) { cpp2Channel_->setReceiveCallback(this); } else { cpp2Channel_->setReceiveCallback(nullptr); } } } // namespace thrift } // namespace apache
34.758985
80
0.674351
[ "transform" ]
590b3641d0a34f83465949b8846da871786c59ad
2,829
cpp
C++
lte/gateway/c/session_manager/SessionRules.cpp
KenG98/magma
dac860761778371f305901e54d81fb09eff102e7
[ "BSD-3-Clause" ]
null
null
null
lte/gateway/c/session_manager/SessionRules.cpp
KenG98/magma
dac860761778371f305901e54d81fb09eff102e7
[ "BSD-3-Clause" ]
null
null
null
lte/gateway/c/session_manager/SessionRules.cpp
KenG98/magma
dac860761778371f305901e54d81fb09eff102e7
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2016-present, 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. */ #include "SessionRules.h" namespace magma { SessionRules::SessionRules(StaticRuleStore &static_rule_ref): static_rules_(static_rule_ref) { } bool SessionRules::get_charging_key_for_rule_id( const std::string &rule_id, uint32_t *charging_key) { // first check dynamic rules and then static rules if (dynamic_rules_.get_charging_key_for_rule_id(rule_id, charging_key)) { return true; } if (static_rules_.get_charging_key_for_rule_id(rule_id, charging_key)) { return true; } return false; } bool SessionRules::get_monitoring_key_for_rule_id( const std::string &rule_id, std::string *monitoring_key) { // first check dynamic rules and then static rules if (dynamic_rules_.get_monitoring_key_for_rule_id(rule_id, monitoring_key)) { return true; } if (static_rules_.get_monitoring_key_for_rule_id(rule_id, monitoring_key)) { return true; } return false; } void SessionRules::insert_dynamic_rule(const PolicyRule &rule) { dynamic_rules_.insert_rule(rule); } void SessionRules::activate_static_rule(const std::string &rule_id) { active_static_rules_.push_back(rule_id); } bool SessionRules::remove_dynamic_rule( const std::string &rule_id, PolicyRule *rule_out) { return dynamic_rules_.remove_rule(rule_id, rule_out); } bool SessionRules::deactivate_static_rule(const std::string &rule_id) { auto it = std::find(active_static_rules_.begin(), active_static_rules_.end(), rule_id); if (it == active_static_rules_.end()) { return false; } active_static_rules_.erase(it); return true; } /** * For the charging key, get any applicable rules from the static rule set * and the dynamic rule set */ void SessionRules::add_rules_to_action( ServiceAction &action, uint32_t charging_key) { static_rules_.get_rule_ids_for_charging_key( charging_key, *action.get_mutable_rule_ids()); dynamic_rules_.get_rule_definitions_for_charging_key( charging_key, *action.get_mutable_rule_definitions()); } void SessionRules::add_rules_to_action( ServiceAction &action, std::string monitoring_key) { static_rules_.get_rule_ids_for_monitoring_key( monitoring_key, *action.get_mutable_rule_ids()); dynamic_rules_.get_rule_definitions_for_monitoring_key( monitoring_key, *action.get_mutable_rule_definitions()); } std::vector<std::string> &SessionRules::get_static_rule_ids() { return active_static_rules_; } DynamicRuleStore &SessionRules::get_dynamic_rules() { return dynamic_rules_; } } // namespace magma
26.194444
79
0.763521
[ "vector" ]
590dce2b12da788c6c7bbbf8cbd69dd091517360
41,641
cpp
C++
kernel/src/simulationTools/OSNSMultipleImpact.cpp
siconos/siconos-deb
2739a23f23d797dbfecec79d409e914e13c45c67
[ "Apache-2.0" ]
null
null
null
kernel/src/simulationTools/OSNSMultipleImpact.cpp
siconos/siconos-deb
2739a23f23d797dbfecec79d409e914e13c45c67
[ "Apache-2.0" ]
null
null
null
kernel/src/simulationTools/OSNSMultipleImpact.cpp
siconos/siconos-deb
2739a23f23d797dbfecec79d409e914e13c45c67
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "OSNSMultipleImpact.hpp" #include "LagrangianDS.hpp" #include "MultipleImpactNSL.hpp" #include "Simulation.hpp" #include "ioMatrix.hpp" #include <boost/numeric/ublas/io.hpp> #include <boost/progress.hpp> #include "OSNSMatrix.hpp" #include "Model.hpp" #include "NonSmoothDynamicalSystem.hpp" //Default constructor OSNSMultipleImpact::OSNSMultipleImpact(): LinearOSNS() { _typeCompLaw = "BiStiffness"; _nStepSave = 100; _tolImpact = DEFAULT__tolImpact; _Tol_Vel = DEFAULT_TOL_VEL; _Tol_Ener = DEFAULT_TOL_ENER; _ZeroVel_EndIm = DEFAULT_TOL_VEL; _ZeroEner_EndIm = DEFAULT_TOL_ENER; _saveData = false; _sizeDataSave = 1000; _nStepMax = 100000; _stepMinSave = 1; _stepMaxSave = _nStepMax; _namefile = "DataMultipleImpact.dat"; } //------------------------------ ------------------------------------------------------------- OSNSMultipleImpact::OSNSMultipleImpact(std::string newTypeLaw, double newDelP = 1.0e-5): LinearOSNS() { _typeCompLaw = newTypeLaw; _deltaP = newDelP; _nStepSave = 100; _tolImpact = DEFAULT__tolImpact; _Tol_Vel = DEFAULT_TOL_VEL; _Tol_Ener = DEFAULT_TOL_ENER; _ZeroVel_EndIm = DEFAULT_TOL_VEL; _ZeroEner_EndIm = DEFAULT_TOL_ENER; _saveData = false; _namefile = "DataMultipleImpact.dat"; _sizeDataSave = 1000; _nStepMax = 100000; _stepMinSave = 1; _stepMaxSave = _nStepMax; if ((_typeCompLaw != "MonoStiffness") && (_typeCompLaw != "BiStiffness")) RuntimeException::selfThrow("OSNSMultipleImpact::_typeCompLaw type of the compliance model must be either MonoStiffness or BiStiffness!"); } //------------------------------------------------------------------------------------------------- OSNSMultipleImpact::~OSNSMultipleImpact() {} //------------------------------------------------------------------------------------------------ void OSNSMultipleImpact::setTolImpact(double newTolZero) { _tolImpact = newTolZero; }; void OSNSMultipleImpact::SetSaveData(bool var) { _saveData = var; }; void OSNSMultipleImpact::SetNameOutput(std::string file_name) { _namefile = file_name; }; void OSNSMultipleImpact::SetTolVel(double _var) { _Tol_Vel = _var; }; void OSNSMultipleImpact::SetTolEner(double _var) { _Tol_Ener = _var; }; void OSNSMultipleImpact::SetZeroVelEndImp(double _var) { _ZeroVel_EndIm = _var; }; void OSNSMultipleImpact::SetZeroEnerEndImp(double _var) { _ZeroEner_EndIm = _var; }; void OSNSMultipleImpact::SetNstepSave(unsigned int var) { _nStepSave = var; }; void OSNSMultipleImpact::SetNstepMax(unsigned int var) { _nStepMax = var; }; void OSNSMultipleImpact::SetStepMinMaxSave(unsigned int var1, unsigned int var2) { _stepMinSave = var1; _stepMaxSave = var2; } void OSNSMultipleImpact::set_typeCompLaw(std::string newTypeLaw) { _typeCompLaw = newTypeLaw; if ((_typeCompLaw != "MonoStiffness") && (_typeCompLaw != "BiStiffness")) RuntimeException::selfThrow("OSNSMultipleImpact::_typeCompLaw type of the compliance model must be either MonoStiffness or BiStiffness!"); }; void OSNSMultipleImpact::SetSizeDataSave(unsigned int var) { _sizeDataSave = var; } //--------------------------------------------------------------------------------------------------- void OSNSMultipleImpact::WriteVectorIntoMatrix(const SiconosVector m, const unsigned int pos_row, const unsigned int pos_col) { for (unsigned int i = 0; i < m.size(); ++i) { (*_DataMatrix)(pos_row, pos_col + i) = m(i); } } //---------------------------------------------------------------------------------------------------- bool OSNSMultipleImpact::isZero(double Var) { if (std::abs(Var) <= _tolImpact) return true; else return false; } //------------------------------------------------------------------------------------------------ bool OSNSMultipleImpact::isVelNegative(double Var) { if (Var < - _Tol_Vel) return true; else return false; } //------------------------------------------------------------------------------------------------- bool OSNSMultipleImpact::isEnerZero(double Var) { if (std::abs(Var) <= _Tol_Ener) return true; else return false; } //-------------------------------------------------------------------------------------------------- unsigned int OSNSMultipleImpact::EstimateNdataCols() { unsigned int _numberCols = 1; // Number of columns for data at contacts SP::InteractionsGraph indexSet = simulation()->indexSet(0); // get indexSet[0] InteractionsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { //_numberCols = _numberCols + 3*(indexSet->bundle(*ui)->interaction()->nonSmoothLaw()->size()) + 1; _numberCols = _numberCols + (indexSet->bundle(*ui)->getSizeOfY()); } // Number of columns for data at particles SP::DynamicalSystemsGraph DSG = simulation()->nonSmoothDynamicalSystem()->dynamicalSystems(); DynamicalSystemsGraph::VIterator dsi, dsiend; for (std11::tie(dsi, dsiend) = DSG->vertices(); dsi != dsiend; ++dsi) { _numberCols = _numberCols + (DSG->bundle(*dsi)->dimension()); } return(_numberCols); } //----------------------------------------------------------------------------------------------- void OSNSMultipleImpact::AllocateMemory() { if (!_velocityContact) _velocityContact.reset(new SiconosVector(maxSize())); else { if (_velocityContact->size() != maxSize()) _velocityContact->resize(maxSize()); }; // if (!_oldVelocityContact) _oldVelocityContact.reset(new SiconosVector(maxSize())); else { if (_oldVelocityContact->size() != maxSize()) _oldVelocityContact->resize(maxSize()); }; // if (! _energyContact) _energyContact.reset(new SiconosVector(maxSize())); else { if (_energyContact->size() != maxSize()) _energyContact->resize(maxSize()); }; // if (!_WorkcContact) _WorkcContact.reset(new SiconosVector(maxSize())); else { if (_WorkcContact->size() != maxSize()) _WorkcContact->resize(maxSize()); }; // if (!_distributionVector) _distributionVector.reset(new SiconosVector(maxSize())); else { if (_distributionVector->size() != maxSize()) _distributionVector->resize(maxSize()); }; // if (!_stateContact) _stateContact.reset(new IndexInt(maxSize())); else { if (_stateContact->size() != maxSize()) _stateContact->resize(maxSize()); }; // if (!_Kcontact) _Kcontact.reset(new SiconosVector(maxSize())); else { if (_Kcontact->size() != maxSize()) _Kcontact->resize(maxSize()); }; // if (!_restitutionContact) _restitutionContact.reset(new SiconosVector(maxSize())); else { if (_restitutionContact->size() != maxSize()) _restitutionContact->resize(maxSize()); }; // if (!_elasticyCoefficientcontact) _elasticyCoefficientcontact.reset(new SiconosVector(maxSize())); else { if (_elasticyCoefficientcontact->size() != maxSize()) _elasticyCoefficientcontact->resize(maxSize()); }; if (!_tolImpulseContact) _tolImpulseContact.reset(new SiconosVector(maxSize())); else { if (_tolImpulseContact->size() != maxSize()) _tolImpulseContact->resize(maxSize()); }; // if (!_deltaImpulseContact) _deltaImpulseContact.reset(new SiconosVector(maxSize())); else { if (_deltaImpulseContact->size() != maxSize()) _deltaImpulseContact->resize(maxSize()); }; // if (!_impulseContactUpdate) _impulseContactUpdate.reset(new SiconosVector(maxSize())); else { if (_impulseContactUpdate->size() != maxSize()) _impulseContactUpdate->resize(maxSize()); } // if (!_forceContact) _forceContact.reset(new SiconosVector(maxSize())); else { if (_forceContact->size() != maxSize()) _forceContact->resize(maxSize()); }; // for the data matrix unsigned int _numberCols = EstimateNdataCols(); if (!_DataMatrix) _DataMatrix.reset(new SimpleMatrix(_sizeDataSave, _numberCols)); else { if ((_DataMatrix->size(0) != _sizeDataSave) || (_DataMatrix->size(1) != _numberCols)) _DataMatrix->resize(_sizeDataSave, _numberCols); } } //===================================================================================== void OSNSMultipleImpact::BuildParaContact() { SP::InteractionsGraph indexSet = simulation()->indexSet(1); // get indexSet[1] //Loop over the Interactionof the indexSet(1) InteractionsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { SP::Interaction inter = indexSet->bundle(*ui); SP::NonSmoothLaw nslaw = inter->nslaw(); SP::MultipleImpactNSL Mulnslaw = std11::dynamic_pointer_cast<MultipleImpactNSL>(nslaw); assert(Mulnslaw && "In OSNSMultipleImpact::BuildStiffResCofVec, non-smooth law used must be MultipleImpactNSL!!!"); // Get the relative position of inter-interactionBlock in the vector _velocityContact unsigned int pos = _M->getPositionOfInteractionBlock(*inter); (*_restitutionContact)(pos) = Mulnslaw->ResCof(); (*_Kcontact)(pos) = Mulnslaw->Stiff(); (*_elasticyCoefficientcontact)(pos) = Mulnslaw->ElasCof(); } /* std::cout << " Restitution coefficients: " <<std::endl; _restitutionContact->display(); std::cout << "Stiffnesses: " <<std::endl; _Kcontact->display(); std::cout << "Elasticity coeffients at contacts: " <<std::endl; _elasticyCoefficientcontact->display(); */ } //======================================================================================== void OSNSMultipleImpact::PreComputeImpact() { //1. Get the number of contacts and bodies involved in the impact if (indexSetLevel() != 1) RuntimeException::selfThrow("OSNSMultipleImpact::PreComputeImpact==> the levelMin must be equal to 1 in the multiple impact model !!"); SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // get indexSet[1] _nContact = indexSet->size(); //2. Compute matrix _M SP::Topology topology = simulation()->nonSmoothDynamicalSystem()->topology(); bool isLinear = simulation()->nonSmoothDynamicalSystem()->isLinear(); if (!_hasBeenUpdated || !isLinear) { // Computes new _unitaryBlocks if required updateInteractionBlocks(); // Updates matrix M _M->fill(indexSet, !_hasBeenUpdated); _sizeOutput = _M->size(); } if (_nContact != _sizeOutput) RuntimeException::selfThrow("OSNSMultipleImpact::ComputeWMinvWtrans: number of contacts different from the size of output--> this case is not yet implemented!"); //3. Checks size of vectors if (_velocityContact->size() != _sizeOutput) { _velocityContact->resize(_sizeOutput); } _velocityContact->zero(); // if (_oldVelocityContact->size() != _sizeOutput) { _oldVelocityContact->resize(_sizeOutput); } _oldVelocityContact->zero(); // if (_energyContact->size() != _sizeOutput) { _energyContact->resize(_sizeOutput); } _energyContact->zero(); // if (_WorkcContact->size() != _sizeOutput) { _WorkcContact->resize(_sizeOutput); } _WorkcContact->zero(); // if (_distributionVector->size() != _sizeOutput) { _distributionVector->resize(_sizeOutput); } _distributionVector->zero(); // if (_stateContact->size() != _sizeOutput) { _stateContact->resize(_sizeOutput); } // if (_Kcontact->size() != _sizeOutput) { _Kcontact->resize(_sizeOutput); } _Kcontact->zero(); // if (_restitutionContact->size() != _sizeOutput) { _restitutionContact->resize(_sizeOutput); } _restitutionContact->zero(); // if (_elasticyCoefficientcontact->size() != _sizeOutput) { _elasticyCoefficientcontact->resize(_sizeOutput); } _elasticyCoefficientcontact->zero(); // if (_tolImpulseContact->size() != _sizeOutput) { _tolImpulseContact->resize(_sizeOutput); } _tolImpulseContact->zero(); // if (_deltaImpulseContact->size() != _sizeOutput) { _deltaImpulseContact->resize(_sizeOutput); } _deltaImpulseContact->zero(); // if (_impulseContactUpdate->size() != _sizeOutput) { _impulseContactUpdate->resize(_sizeOutput); } _impulseContactUpdate->zero(); // if (_forceContact->size() != _sizeOutput) { _forceContact->resize(_sizeOutput); } _forceContact->zero(); //4. Initialize the relative velocity, potential energy, impulse at contacts InitializeInput(); //5. Build the vectors of stifnesseses, of restitution coefficients, and of elaticity coefficients BuildParaContact(); } //======================================================================================= void OSNSMultipleImpact::InitializeInput() { //Loop over alls Interactioninvolved in the indexSet[1] SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // get indexSet[1] InteractionsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { SP::Interaction inter = indexSet->bundle(*ui); //SP::SiconosVector Vc0 = inter->y(1); // Relative velocity at beginning of impact SP::SiconosVector Vc0 = inter->yOld(1); // Relative velocity at beginning of impact unsigned int pos_inter = _M->getPositionOfInteractionBlock(*inter); setBlock(*Vc0, _velocityContact, Vc0->size(), 0, pos_inter); SP::SiconosVector ener0(new SiconosVector(Vc0->size())); ener0->zero(); // We suppose that the initial potential energy before impact is equal to zero at any contact // at the beginning of impact setBlock(*ener0, _energyContact, ener0->size(), 0, pos_inter); //SP::SiconosVector impulse0= (inter)->lambda(1))->vector(inter->number()); SP::SiconosVector impulse0(new SiconosVector(Vc0->size())); impulse0->zero(); // We suppose that the impulse before impact is equal to zero at any contact // at the beginning of impact setBlock(*impulse0, _tolImpulseContact, impulse0->size(), 0, pos_inter); }; /* std::cout << "Initial relative velocity at contacts" <<std::endl; _velocityContact->display(); std::cout<< "Initial energy at contacts" <<std::endl; _energyContact->display(); std::cout << "Impulse at contact" <<std::endl; _tolImpulseContact->display(); */ } //========================================================================================= void OSNSMultipleImpact::initialize(SP::Simulation sim) { // General initialize for OneStepNSProblem OneStepNSProblem::initialize(sim); // Allocate the memory AllocateMemory(); // get topology SP::Topology topology = simulation()->nonSmoothDynamicalSystem()->topology(); // Note that _interactionBlocks is up to date since updateInteractionBlocks // has been called during OneStepNSProblem::initialize() if (! _M) { if (_MStorageType == 0) _M.reset(new OSNSMatrix(maxSize(), 0)); else // if(_MStorageType == 1) size = number of _interactionBlocks // = number of Interactionin the largest considered indexSet _M.reset(new OSNSMatrix(simulation()->indexSet(indexSetLevel())->size(), 1)); } }; //======================================================================================== void OSNSMultipleImpact::PrimConVelocity() { getMin(*_velocityContact, _relativeVelocityPrimaryContact, _primaryContactId); _energyPrimaryContact = (*_energyContact)(_primaryContactId); if (!isVelNegative(_relativeVelocityPrimaryContact)) { RuntimeException::selfThrow("OSNSMultipleImpact::PrimConVelocity, the velocity at the primary contact must be negative !!"); } /* std::cout << "Primary contact according to relative velocity: " << _primaryContactId <<std::endl; std::cout << "Relative velocity at the primary contact: " << _relativeVelocityPrimaryContact <<std::endl; std::cout << "Potential energy at the primary contact: " << _energyPrimaryContact <<std::endl; */ } //======================================================================================= void OSNSMultipleImpact::PrimConEnergy() { getMax(*_energyContact, _energyPrimaryContact, _primaryContactId); _relativeVelocityPrimaryContact = (*_velocityContact)(_primaryContactId); if (_energyPrimaryContact < 0.0) { RuntimeException::selfThrow("OSNSMultipleImpact::PrimConEnergy the potential energy at the primary contact must be positive !!"); } /* std::cout << "Primary contact according to potenial energy: " << _primaryContactId <<std::endl; std::cout << "Relative velocity at the primary contact: " << _relativeVelocityPrimaryContact <<std::endl; std::cout << "Potential energy at the primary contact: " << _energyPrimaryContact <<std::endl; */ } //====================================================================================== bool OSNSMultipleImpact::IsEnermaxZero() { double MaxEner; unsigned int IdMax; getMax(*_energyContact, MaxEner, IdMax); if (isEnerZero(MaxEner)) return true; else return false; } //====================================================================================== bool OSNSMultipleImpact::IsVcminNegative() { double MinVelCon; unsigned int IdConVmin; getMin(*_velocityContact, MinVelCon, IdConVmin); if (isVelNegative(MinVelCon)) return true; else return false; } //======================================================================================= void OSNSMultipleImpact::Check_stateContact() { for (unsigned int i = 0; i < _nContact; ++i) { if (isEnerZero((*_energyContact)(i))) // potential energy is zero { if (!isVelNegative((*_velocityContact)(i))) // relative velocity is positive or equal to zero (*_stateContact)[i] = 0; // no impact at this contact else // impact happens without potential energy { (*_stateContact)[i] = 1; } } else // impact happens with not zero potential energy { if ((*_stateContact)[i] != 2) { (*_stateContact)[i] = 2; } } } } //======================================================================================= bool OSNSMultipleImpact::IsMulImpactTerminate() { _IsImpactEnd = true; for (unsigned int i = 0; i < _nContact; ++i) { if (((*_energyContact)(i) > _ZeroEner_EndIm) || ((*_velocityContact)(i) < -_ZeroVel_EndIm)) // if potential energy is not equal to zero or the relative velocity is negative { _IsImpactEnd = false; } } return _IsImpactEnd; // bool var = true; // for(unsigned int i = 0; i < _nContact;++i) // { // if ((*_stateContact)[i] != 0) // { // var = false; // break; // }; // }; // return var; // //cout << "Is the multiple impacts is terminated: " << _IsImpactEnd <<std::endl; // } //======================================================================================= void OSNSMultipleImpact::SelectPrimaContact() { if (IsEnermaxZero()) // case of no potential energy at any contact { PrimConVelocity(); // Select the primary contact according to the relative velocity at contact _isPrimaryContactEnergy = false; } else { PrimConEnergy(); // Select the primary contact according to the potential energy at contacts _isPrimaryContactEnergy = true; } // // std::cout << "The primary contact is :" << _primaryContactId <<std::endl; // std::cout << "Is the primary contact is selected according to the potential energy: " << _isPrimaryContactEnergy <<std::endl; } //======================================================================================= void OSNSMultipleImpact::Compute_distributionVector() { //Case 1: if no potential energy at any contact double _ratio_mu, ratio_stiff, ratio_ener; double mu_prima = (*_elasticyCoefficientcontact)(_primaryContactId); // Elasticity coefficient at the primary contact double stiff_prima = (*_Kcontact)(_primaryContactId); // Stiffness at the primary contact double _mu, _stiff, _vel, _energy; if (!_isPrimaryContactEnergy) // case of primary contact selected according to the relative velocity { double ratio_vel; for (unsigned int i = 0; i < _nContact; ++i) { if ((*_stateContact)[i] != 0) // the impact can takes place at this contact { _mu = (*_elasticyCoefficientcontact)(i); // Elasticity coefficient at the current contact _stiff = (*_Kcontact)(i); // Stiffness at the current contact _vel = (*_velocityContact)(i); // Relative velocity at the current contact _ratio_mu = (std::pow(_mu + 1.0, (_mu / (_mu + 1.0)))) / (std::pow(mu_prima + 1.0, (mu_prima / (mu_prima + 1.0)))); ratio_stiff = (std::pow(_stiff, (1.0 / (1.0 + _mu)))) / (std::pow(stiff_prima, (1.0 / (1.0 + mu_prima)))); if (!isVelNegative(_vel)) { RuntimeException::selfThrow("OSNSMultipleImpact::Compute_distributionVector, the relative velocity when particle starts to impact must be negative!!"); } ratio_vel = (std::pow(std::fabs(_vel), (_mu / (_mu + 1.0)))) / (std::pow(std::fabs(_relativeVelocityPrimaryContact), (mu_prima / (1.0 + mu_prima)))); (*_distributionVector)(i) = std::pow((_ratio_mu * ratio_stiff * ratio_vel), (1.0 + _mu)) * std::pow(_deltaP, ((_mu - mu_prima) / (1.0 + mu_prima))); } else { (*_distributionVector)(i) = 0.0; } if ((*_distributionVector)(i) < 0.0) RuntimeException::selfThrow("OSNSMultipleImpact::Compute_distributionVector the component of _distributionVector must be positive !!"); }; } //Case 2: case of primary contact selected according to the potential energy else { for (unsigned int i = 0; i < _nContact; ++i) { // _mu = (*_elasticyCoefficientcontact)(i); _stiff = (*_Kcontact)(i); _ratio_mu = (std::pow(_mu + 1.0, (_mu / (_mu + 1.0)))) / (std::pow(mu_prima + 1.0, (mu_prima / (mu_prima + 1.0)))); ratio_stiff = (std::pow(_stiff, (1.0 / (1.0 + _mu)))) / (std::pow(stiff_prima, (1.0 / (1.0 + mu_prima)))); if ((*_stateContact)[i] == 1) // no potential energy at this contact, including the contacts at which impact repeats { if (!isVelNegative((*_velocityContact)(i))) { RuntimeException::selfThrow("OSNSMultipleImpact::Compute_distributionVector, the pre-impact velocity must be negative!!"); } else { _vel = (*_velocityContact)(i); ratio_ener = (std::pow(std::fabs(_vel * _deltaP), (_mu / (_mu + 1.0)))) / (std::pow(_energyPrimaryContact, (mu_prima / (mu_prima + 1.0)))); // // std::cout << "_ratio_m: " << _ratio_mu <<std::endl; // std::cout << "Stiff: " << _stiff <<std::endl; // std::cout << "ratio_stiff: " << ratio_stiff <<std::endl; // std::cout << "energy ratio: " << ratio_ener <<std::endl; // (*_distributionVector)(i) = std::pow((_ratio_mu * ratio_stiff * ratio_ener), (1.0 + _mu)); } } else if ((*_stateContact)[i] == 2) // potential is not zero at this contact { _energy = (*_energyContact)(i); // Potential energy at the current contact ratio_ener = (std::pow(_energy, (_mu / (_mu + 1.0)))) / (std::pow(_energyPrimaryContact, (mu_prima / (mu_prima + 1.0)))); (*_distributionVector)(i) = _ratio_mu * ratio_stiff * ratio_ener; } else // no impact at this contact { (*_distributionVector)(i) = 0.0; }; if ((*_distributionVector)(i) < 0.0) RuntimeException::selfThrow("OSNSMultipleImpact::Compute_distributionVector the component of _distributionVector must be positive !!"); }; }; } //======================================================================================= void OSNSMultipleImpact::ComputeImpulseContact() { (*_deltaImpulseContact) = (*_distributionVector) * _deltaP; (*_tolImpulseContact) = (*_tolImpulseContact) + (*_deltaImpulseContact); (*_impulseContactUpdate) = (*_impulseContactUpdate) + (*_deltaImpulseContact); // Compute the contact force double PowCompLaw; for (unsigned int i = 0; i < _nContact; ++i) { PowCompLaw = (*_elasticyCoefficientcontact)(i); if (isEnerZero((*_energyContact)(i))) // if potential energy at this contact is zero { if (isVelNegative((*_velocityContact)(i))) // if the relative velocity at contact is negative { (*_forceContact)(i) = std::pow((1.0 + PowCompLaw), PowCompLaw / (1.0 + PowCompLaw)) * std::pow((*_Kcontact)(i), 1.0 / (1.0 + PowCompLaw)) * std::pow((std::fabs((*_velocityContact)(i)) * (*_deltaImpulseContact)(i)), PowCompLaw / (1.0 + PowCompLaw)); } else { (*_forceContact)(i) = 0.0; }; } else { (*_forceContact)(i) = std::pow((1.0 + PowCompLaw), PowCompLaw / (1.0 + PowCompLaw)) * std::pow((*_Kcontact)(i), 1.0 / (1.0 + PowCompLaw)) * std::pow((*_energyContact)(i), PowCompLaw / (1.0 + PowCompLaw)); } if ((*_forceContact)(i) < 0.0) { RuntimeException::selfThrow("OSNSMultipleImpact::ComputeImpulseContact, the contact force must be positive or equal to zero!!!"); } }; } //======================================================================================= void OSNSMultipleImpact::Compute_velocityContact() { (*_oldVelocityContact) = (*_velocityContact); //save the relative velocity at the beginning of the step (*_velocityContact) = (*_velocityContact) + prod(*(_M->defaultMatrix()), *_deltaImpulseContact); // compute the relative velocity at the end of the step // /* std::cout << "Relative velocity at contacts at the beginning of step:" <<std::endl; _oldVelocityContact->display(); std::cout << "Relative velocity at contacts at the end of step:" <<std::endl; _velocityContact->display(); */ // } //======================================================================================= void OSNSMultipleImpact::Compute_energyContact() { if (_typeCompLaw == "BiStiffness") // For Bistiffness model { for (unsigned int i = 0; i < _nContact; ++i) { if ((0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i))) <= 0.0) // Contact located in the compression phase { (*_energyContact)(i) = (*_energyContact)(i) - 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i)); } else // Contact located in the expansion phase { if (!isZero((*_restitutionContact)(i))) { (*_energyContact)(i) = (*_energyContact)(i) - (1.0 / std::pow((*_restitutionContact)(i), 2)) * 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i)); // if ((*_energyContact)(i) < 0.0) { (*_energyContact)(i) = 0.0; }; } else // restitution coefficient equal to zero { (*_energyContact)(i) = 0.0; // In this case, no potential energy at contacts when the contact is located in the compression phase } }; // if ((*_energyContact)(i) < 0.0) { RuntimeException::selfThrow("OSNSMultipleImpact::Compute_energyContact, the potential energy during compression phase must be positive!!!"); }; }; } else // For the mono-stiffness model { for (unsigned int i = 0; i < _nContact; ++i) { //1: dertermine the work done by the last compression phase at contacts (nessessary for the mono-stiffness compliance model) // if Vc(k) < 0 and Vc(k +1) >= 0 ==> transition from the compression phase to the expansion phase, Wc = E(k) if (((*_oldVelocityContact)(i) < 0.0) && ((*_velocityContact)(i) >= 0.0)) { (*_WorkcContact)(i) = (*_energyContact)(i); }; //2: Calculate the potential energy at the end of stap (*_energyContact)(i) = (*_energyContact)(i) - 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i)); //3: Check if the termination condition is verified or not (if Vc(k+1) > 0.0 and E(k+1) <= (1-e^2)*Wc). If yes, discard the potential energy // in order to respect the energetic constraint if (((*_stateContact)[i] == 2) && (((*_velocityContact)(i) > 0.0) && ((*_energyContact)(i) <= ((1.0 - std::pow((*_restitutionContact)(i), 2)) * (*_WorkcContact)(i))))) { (*_energyContact)(i) = 0.0; // potential energy at this contact is completely dissipated before the compression phase finishes }; }; } /* std::cout << "Potential energy at contacts at the end of step:" <<std::endl; _energyContact->display(); std::cout << "Work done during the compression phase at contacts" <<std::endl; _WorkcContact->display(); */ } //====================================================================================== void OSNSMultipleImpact::UpdateDuringImpact() { //1. Copy _velocityContact/_deltaImpulseContact into the vector y/lambda for Interactions SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // y and lambda vectors SP::SiconosVector lambda; SP::SiconosVector y; // === Loop through "active" Interactions (ie present in indexSets[1]) === unsigned int pos; InteractionsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { Interaction& inter = *indexSet->bundle(*ui); // Get the relative position of inter-interactionBlock in the vector _velocityContact/_tolImpulseContact pos = _M->getPositionOfInteractionBlock(inter); // Get Y and Lambda for the current Interaction y = inter.y(inputOutputLevel()); lambda = inter.lambda(inputOutputLevel()); // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda // save into y !! setBlock(*_velocityContact, y, y->size(), pos, 0); // saved into lambda[1] !! setBlock(*_impulseContactUpdate, lambda, lambda->size(), pos, 0); //setBlock(*_deltaImpulseContact, lambda, lambda->size(), pos, 0); }; //2. Update the Input[1], state of DS systems, Output[1] simulation()->update(inputOutputLevel()); _impulseContactUpdate->zero(); // reset input[1] to zero after each update } //-------------------------------------------------------------------------------------- void OSNSMultipleImpact::SaveDataOneStep(unsigned int _ithPoint) { // Save the total impulse at the primary contacts (time-like independent variable) and the time evolution during impact if (_ithPoint >= _DataMatrix->size(0)) RuntimeException::selfThrow("In OSNSMultipleImpact::ComputeImpact, number of points saved exceeds the size of matrix allocated!!!"); //(*_DataMatrix)(_ithPoint,0) = _timeVariable; (*_DataMatrix)(_ithPoint, 0) = _impulseVariable; // Save the data related to UnitaryRelations SP::InteractionsGraph indexSet0 = simulation()->indexSet(0); SP::InteractionsGraph indexSet1 = simulation()->indexSet(indexSetLevel()); unsigned int pos; InteractionsGraph::VIterator ui, uiend; unsigned int col_pos = 1; for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui) { SP::Interaction inter = indexSet0->bundle(*ui); SP::SiconosVector ydot = inter->y(1); SP::SiconosVector P_inter(new SiconosVector(inter->getSizeOfY())); SP::SiconosVector F_inter(new SiconosVector(inter->getSizeOfY())); SP::SiconosVector E_inter(new SiconosVector(1)); if (indexSet1->is_vertex(inter)) // if Interaction belongs to the IndexSet[1] { pos = _M->getPositionOfInteractionBlock(*inter); setBlock(*_tolImpulseContact, P_inter, P_inter->size(), pos, 0); setBlock(*_forceContact, F_inter, F_inter->size(), pos, 0); setBlock(*_energyContact, E_inter, E_inter->size(), pos, 0); } else { P_inter->zero(); // no impulse at this Interaction F_inter->zero(); // no force at this Interaction E_inter->zero(); // no potential at this Interaction }; // Write the force at the Interaction WriteVectorIntoMatrix(*F_inter, _ithPoint, col_pos); //WriteVectorIntoMatrix(*P_inter, _ithPoint, col_pos); //WriteVectorIntoMatrix(*E_inter, _ithPoint, col_pos); col_pos = col_pos + F_inter->size(); } // Save the data related to DS SP::DynamicalSystemsGraph DSG = simulation()->nonSmoothDynamicalSystem()->dynamicalSystems(); DynamicalSystemsGraph::VIterator dsi, dsiend; for (std11::tie(dsi, dsiend) = DSG->vertices(); dsi != dsiend; ++dsi) { SP::DynamicalSystem ds = DSG->bundle(*dsi); // DS SP::LagrangianDS Lagds = std11::dynamic_pointer_cast<LagrangianDS>(ds); SP::SiconosVector qdot = Lagds->velocity(); // Write WriteVectorIntoMatrix(*qdot, _ithPoint, col_pos); col_pos = col_pos + qdot->size(); } } //======================================================================================= void OSNSMultipleImpact::ComputeImpact() { _impulseVariable = 0.0; _timeVariable = 0.0; unsigned int number_step = 1; unsigned int point_save = 0; unsigned int _counterstepsave = 0; // Show computation progress //cout << "*********** Impact computation progress *************" <<std::endl; //boost::progress_display show_progress(_nStepMax); /* std::cout << "----------Before multiple impacts computation---------------" <<std::endl; std::cout << "Velocity at contacts: "; _velocityContact->display(); std::cout << "Impulse at contact: "; _tolImpulseContact->display(); */ //cout << "-------------------Multiple impacts computation starts:-----------------------" <<std::endl; // First save at the beginning of impact computation if ((_saveData) && (_stepMinSave == 1)) { SaveDataOneStep(point_save); // Save the data point_save++; } // while (1 != 0) { // std::cout << "==================Step==================: " << number_step <<std::endl; // std::cout << "Impulse variable: " << _impulseVariable <<std::endl; // std::cout << "_timeVariable: " << _timeVariable <<std::endl; //Step 1: check the state at contacts Check_stateContact(); //Step 2: check if the multiple impact is terminated or not if (IsMulImpactTerminate()) // multiple impact terminated { if (_saveData) // Save the date at the end of impact { UpdateDuringImpact(); // Update state of dynamical system SaveDataOneStep(point_save); // Save the data } break; } // Select the primary contact SelectPrimaContact(); //Step 3: compute the vector of distributing law Compute_distributionVector(); //Step 4: compute the increment of normal impulse and the total impulse at contacts ComputeImpulseContact(); // Step 5: compute the relative velocity at contacts Compute_velocityContact(); // Step 6: compute the potential energy at contacts Compute_energyContact(); //Step 7: Update the time-like variable ++number_step; ++_counterstepsave; //++show_progress; _impulseVariable = _impulseVariable + _deltaP; _timeVariable = _timeVariable + _deltaP / (*_forceContact)(_primaryContactId); // Step 8: update the state of DS and output during impact and write data into output file at the beginning of each step if ((_saveData) & (_counterstepsave >= _nStepSave)) { if ((number_step >= _stepMinSave) && (number_step <= _stepMaxSave)) { UpdateDuringImpact(); // Update state of dynamical system SaveDataOneStep(point_save); // Save the data point_save++; _counterstepsave = 0; // reset the counter to 0 } } // if (number_step > _nStepMax) { RuntimeException::selfThrow("In OSNSMultipleImpact::ComputeImpact, number of integration steps perfomed exceeds the maximal number of steps allowed!!!"); //cout << "Causion: so long computation, the computation is stopped even when the impact is not yet terminated!!! " <<std::endl; break; } // std::cout << "Distribution vector: "; // _distributionVector->display(); // std::cout << "Incremental Impulse: "; // _deltaImpulseContact->display(); // std::cout << "Impulse at contact: "; // _tolImpulseContact->display(); // std::cout << "Velocity at contacts: "; // _velocityContact->display(); // std::cout << "Potential energy at contacts: "; // _energyContact->display(); } // // std::cout << "*****************Impact computation is terminated******************" <<std::endl; // std::cout << "Number of integration steps: " << number_step <<std::endl; // std::cout << "Velocity at contacts: "; // _velocityContact->display(); // std::cout << "Impulse at contact: "; // _tolImpulseContact->display(); // std::cout << "Duration of the multiple impacts process: " << _timeVariable << " s" <<std::endl; // Close the stream file if (_saveData) { ioMatrix::write(_namefile.c_str(), "ascii", *_DataMatrix, "noDim"); } } //======================================================================================= void OSNSMultipleImpact::PostComputeImpact() { // === Get index set from Topology === SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // y and lambda vectors SP::SiconosVector lambda; SP::SiconosVector y; // === Loop through "active" Interactions (ie present in indexSets[1]) === unsigned int pos; InteractionsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { Interaction& inter = *indexSet->bundle(*ui); // Get the relative position of inter-interactionBlock in the vector _velocityContact/_tolImpulseContact pos = _M->getPositionOfInteractionBlock(inter); // Get Y and Lambda for the current Interaction y = inter.y(inputOutputLevel()); lambda = inter.lambda(inputOutputLevel()); // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda // save into y !! setBlock(*_velocityContact, y, y->size(), pos, 0);// Warning: yEquivalent is // saved into lambda[1] !! setBlock(*_impulseContactUpdate, lambda, lambda->size(), pos, 0); // If the update is performed at the end of the impact process, we update the total normal impulse at contacts // from the beginning to the end of impact (vector _tolImpulseContact). Otherwise, we must reset the lambda[1] to zero because // the post-impact velocity has been calculated during impact // if (!_saveData) // we update the impact state at the end of impact // { // // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda // // save into y !! // setBlock(*_velocityContact, y, y->size(), pos, 0);// Warning: yEquivalent is // // saved into lambda[1] !! // setBlock(*_tolImpulseContact, lambda, lambda->size(), pos, 0); // } // else // // lambda->zero(); } } //======================================================================================== int OSNSMultipleImpact::compute(double time) { // Pre-compute for impact PreComputeImpact(); // solve the multiple impacts if ((_nContact != 0) && IsVcminNegative()) // if there is at least one contact and the vilocity before impact is negative { ComputeImpact(); }; // Post-compute for multiple impacts PostComputeImpact(); return 0; } //======================================================================================== void OSNSMultipleImpact::display() const { std::cout << "<<<<<<<<<<<<<<<<< Information about the multiple impact >>>>>>>>>>>>>>>>>>>>>" <<std::endl; std::cout << "Type of the contact compliance law: " << _typeCompLaw <<std::endl; std::cout << "Number of contacts involved into impacts: " << _nContact <<std::endl; std::cout << "Step size used: " << _deltaP <<std::endl; std::cout << "Primary impulse at the end of impact: " << _impulseVariable <<std::endl; std::cout << "Duration of the multiple impacs process: " << _timeVariable <<std::endl; // Display post-impact velocities SP::DynamicalSystemsGraph DSG0 = simulation()->nonSmoothDynamicalSystem()->topology()->dSG(0); DynamicalSystemsGraph::VIterator ui, uiend; for (std11::tie(ui, uiend) = DSG0->vertices(); ui != uiend; ++ui) { SP::DynamicalSystem ds = DSG0->bundle(*ui); SP::LagrangianDS lag_ds = std11::dynamic_pointer_cast<LagrangianDS>(ds); std::cout << "DS number: " << ds->number() <<std::endl; std::cout << "Pre-impact velocity: "; (lag_ds->velocityMemory()->getSiconosVector(1))->display(); std::cout << "Post-impact velocity: "; (lag_ds->velocity())->display(); } // Display impulses at contact points SP::InteractionsGraph IndexSet0 = simulation()->nonSmoothDynamicalSystem()->topology()->indexSet(0); InteractionsGraph::VIterator vi, viend; for (std11::tie(vi, viend) = IndexSet0->vertices(); vi != viend; ++vi) { SP::Interaction inter = IndexSet0->bundle(*vi); std::cout << "Impulse at contact point " << inter->number() << ":"; (inter->lambda(1))->display(); } };
38.735814
256
0.621623
[ "vector", "model" ]
59121623594c1e10b67b99310a19be3ae6a0fa15
1,181
hpp
C++
Includes/renderer.hpp
abaire/NevolutionX
54b04d009a4a6d9186f88082e52ad278f80d3839
[ "MIT" ]
72
2019-03-28T19:23:52.000Z
2022-03-12T05:58:19.000Z
Includes/renderer.hpp
abaire/NevolutionX
54b04d009a4a6d9186f88082e52ad278f80d3839
[ "MIT" ]
94
2019-04-30T06:59:43.000Z
2022-02-20T23:06:25.000Z
Includes/renderer.hpp
abaire/NevolutionX
54b04d009a4a6d9186f88082e52ad278f80d3839
[ "MIT" ]
26
2019-04-27T14:11:11.000Z
2022-03-27T03:18:47.000Z
#ifndef RENDERER_H #define RENDERER_H #include <SDL.h> #include <vector> int min(int lhs, int rhs); int max(int lhs, int rhs); class Renderer { public: Renderer(); ~Renderer(); int init(); int init(const char* bg); int clear(); void flip(); SDL_Renderer* getRenderer() { return renderer; } int getWidth() const { return width; } int getHeight() const { return height; } int setDrawColor(uint8_t r = 0x40, uint8_t g = 0x40, uint8_t b = 0xE0, uint8_t a = 0x00); void drawTexture(SDL_Texture* tex, SDL_Rect& src, SDL_Rect& dst); void drawTexture(SDL_Texture* tex, SDL_Rect& dst); void drawTexture(SDL_Texture* tex, int x, int y); void fillRectangle(const SDL_Rect& dst); void fillRectangle(const SDL_FRect& dst); void blitSurface(SDL_Surface* bg, SDL_Surface* fg, int offset); void drawBackground(); private: SDL_Renderer* renderer = nullptr; SDL_Window* window = nullptr; SDL_Texture* background = nullptr; Uint32 renderFlags = 0; Uint32 windowFlags = 0; int height = 0; int width = 0; int overscanCompX = 0; int overscanCompY = 0; size_t menuItemCount = 0; size_t lowerHalf = 0; size_t upperHalf = 0; }; #endif
21.87037
91
0.692633
[ "vector" ]
59156541fa48813df310de526bbb7857202c7e03
15,616
cpp
C++
Tests/UnitTests/Sources/FunctionTest/Conv2DTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
6
2021-07-06T10:52:33.000Z
2021-12-30T11:30:04.000Z
Tests/UnitTests/Sources/FunctionTest/Conv2DTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
1
2022-01-07T12:18:03.000Z
2022-01-08T12:23:13.000Z
Tests/UnitTests/Sources/FunctionTest/Conv2DTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
3
2021-12-05T06:21:50.000Z
2022-01-09T12:44:23.000Z
// Copyright (c) 2021, Justin Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <FunctionTest/Conv2DTest.hpp> #include <TestUtil.hpp> #include <Sapphire/compute/ConvolutionOps.hpp> #include <Sapphire/compute/dense/naive/Convolution.hpp> #include <Sapphire/util/Shape.hpp> #include <iostream> #include <random> #include <vector> #include "doctest.h" namespace Sapphire::Test { void CudaConv2DTest(bool printForward, bool printBackward) { CudaDevice cuda(0, "cuda0"); int N = 4; int inputHeight = 100; int inputWidth = 100; int inputChannels = 1; int numFilters = 1; int filterWidth = 3; int filterHeight = 3; int strideRow = 2; int strideCol = 2; int dilationRow = 2; int dilationCol = 2; int rowPadding = 2; int colPadding = 2; int outputChannels = numFilters; int outputHeight = (inputHeight + 2 * rowPadding - dilationRow * (filterHeight - 1) - 1) / strideRow + 1; int outputWidth = (inputWidth + 2 * colPadding - dilationCol * (filterWidth - 1) - 1) / strideCol + 1; Shape xShape({ N, inputChannels, inputHeight, inputWidth }); Shape filterShape({ numFilters, inputChannels, filterHeight, filterWidth }); Shape yShape({ N, outputChannels, outputHeight, outputWidth }); TensorUtil::TensorData x(xShape, Type::Dense, cuda); TensorUtil::TensorData dx(xShape, Type::Dense, cuda); TensorUtil::TensorData filter(filterShape, Type::Dense, cuda); TensorUtil::TensorData dFilter(filterShape, Type::Dense, cuda); TensorUtil::TensorData y(yShape, Type::Dense, cuda); TensorUtil::TensorData dy(yShape, Type::Dense, cuda); x.SetMode(ComputeMode::Cuda); dx.SetMode(ComputeMode::Cuda); filter.SetMode(ComputeMode::Cuda); dFilter.SetMode(ComputeMode::Cuda); y.SetMode(ComputeMode::Cuda); dy.SetMode(ComputeMode::Cuda); Compute::Initialize::Ones(x); Compute::Initialize::Zeros(dx); Compute::Initialize::Ones(filter); Compute::Initialize::Ones(dFilter); Compute::Initialize::Zeros(y); Compute::Initialize::Ones(dy); Compute::Conv2DForward(y, x, filter, strideRow, strideCol, dilationRow, dilationCol, rowPadding, colPadding); y.ToHost(); y.SetMode(ComputeMode::Host); const auto* forwardOutput = y.HostRawPtr(); for (unsigned i = 0; i < y.HostTotalSize; ++i) if (printForward) std::cout << "forwardData [" << i << "] : " << forwardOutput[i] << std::endl; y.SetMode(ComputeMode::Cuda); Compute::Conv2DBackward(dx, dFilter, dy, x, filter, strideRow, strideCol, rowPadding, colPadding, dilationRow, dilationCol); dx.ToHost(); const auto* backwardOutput = dx.HostRawPtr(); for (unsigned i = 0; i < dy.HostTotalSize; ++i) if (printBackward) std::cout << "backwardData[" << i << "]: " << backwardOutput[i] << std::endl; } void MaxPool2DTest(bool printForward, bool printBackward) { CudaDevice cuda(0, "cuda0"); int N = 1; int inputHeight = 100; int inputWidth = 100; int inputChannels = 1; int windowRows = 4; int windowCols = 4; int strideRow = 2; int strideCol = 2; int rowPadding = 2; int colPadding = 2; int outputChannels = inputChannels; int outputHeight = (inputHeight + 2 * rowPadding - (windowCols - 1) - 1) / strideRow + 1; int outputWidth = (inputWidth + 2 * colPadding - (windowRows - 1) - 1) / strideCol + 1; Shape xShape({ (N), (inputChannels), (inputHeight), (inputWidth) }); Shape yShape({ (N), (outputChannels), (outputHeight), (outputWidth) }); TensorUtil::TensorData x(xShape, Type::Dense, cuda); TensorUtil::TensorData dx(xShape, Type::Dense, cuda); TensorUtil::TensorData y(yShape, Type::Dense, cuda); TensorUtil::TensorData dy(yShape, Type::Dense, cuda); x.SetMode(ComputeMode::Cuda); dx.SetMode(ComputeMode::Cuda); y.SetMode(ComputeMode::Cuda); dy.SetMode(ComputeMode::Cuda); Compute::Initialize::Ones(x); Compute::Initialize::Zeros(dx); Compute::Initialize::Zeros(y); Compute::Initialize::Ones(dy); Compute::MaxPool2DForward(y, x, windowRows, windowCols, strideRow, strideCol, rowPadding, colPadding); y.ToHost(); y.SetMode(ComputeMode::Host); const auto* forwardOutput = y.HostRawPtr(); for (unsigned i = 0; i < y.HostTotalSize; ++i) if (printForward) std::cout << "forwardData [" << i << "] : " << forwardOutput[i] << std::endl; y.SetMode(ComputeMode::Cuda); Compute::MaxPool2DBackward(dx, dy, x, y, windowRows, windowCols, strideRow, strideCol, rowPadding, colPadding); dx.ToHost(); const auto* backwardOutput = dx.HostRawPtr(); for (unsigned i = 0; i < dy.HostTotalSize; ++i) if (printBackward) std::cout << "backwardData[" << i << "]: " << backwardOutput[i] << std::endl; } void AvgPool2DTest(bool printForward, bool printBackward) { CudaDevice cuda(0, "cuda0"); int N = 1; int inputHeight = 100; int inputWidth = 100; int inputChannels = 1; int windowRows = 4; int windowCols = 4; int strideRow = 2; int strideCol = 2; int rowPadding = 2; int colPadding = 2; int outputChannels = inputChannels; int outputHeight = (inputHeight + 2 * rowPadding - (windowCols - 1) - 1) / strideRow + 1; int outputWidth = (inputWidth + 2 * colPadding - (windowRows - 1) - 1) / strideCol + 1; Shape xShape({ (N), (inputChannels), (inputHeight), (inputWidth) }); Shape yShape({ (N), (outputChannels), (outputHeight), (outputWidth) }); TensorUtil::TensorData x(xShape, Type::Dense, cuda); TensorUtil::TensorData dx(xShape, Type::Dense, cuda); TensorUtil::TensorData y(yShape, Type::Dense, cuda); TensorUtil::TensorData dy(yShape, Type::Dense, cuda); x.SetMode(ComputeMode::Cuda); dx.SetMode(ComputeMode::Cuda); y.SetMode(ComputeMode::Cuda); dy.SetMode(ComputeMode::Cuda); Compute::Initialize::Ones(x); Compute::Initialize::Zeros(dx); Compute::Initialize::Zeros(y); Compute::Initialize::Ones(dy); Compute::AvgPool2DForward(y, x, windowRows, windowCols, strideRow, strideCol, rowPadding, colPadding); y.ToHost(); y.SetMode(ComputeMode::Host); const auto* forwardOutput = y.HostRawPtr(); for (unsigned i = 0; i < y.HostTotalSize; ++i) if (printForward) std::cout << "forwardData [" << i << "] : " << forwardOutput[i] << std::endl; y.SetMode(ComputeMode::Cuda); Compute::AvgPool2DBackward(dx, dy, x, y, windowRows, windowCols, strideRow, strideCol, rowPadding, colPadding); dx.ToHost(); const auto* backwardOutput = dx.HostRawPtr(); for (unsigned i = 0; i < dy.HostTotalSize; ++i) if (printBackward) std::cout << "backwardData[" << i << "]: " << backwardOutput[i] << std::endl; } void HostIm2ColTest(bool print) { const int N = 4; const int numFilters = 2; const int numInputChannels = 3; const int InputRows = 3; const int InputCols = 3; const int filterRows = 2; const int filterCols = 2; const int rowPadding = 0; const int colPadding = 0; const int dilationRow = 1; const int dilationCol = 1; const int strideRow = 1; const int strideCol = 1; const Shape inputShape({ N, numInputChannels, InputRows, InputCols }); const Shape filterShape({ numFilters, numInputChannels, filterRows, filterCols }); const int outputRows = (static_cast<int>(inputShape.Rows()) + 2 * rowPadding - dilationRow * (filterShape.Rows() - 1) - 1) / strideRow + 1; const int outputCols = (static_cast<int>(inputShape.Cols()) + 2 * colPadding - dilationCol * (filterShape.Cols() - 1) - 1) / strideCol + 1; const auto inputMatrixRows = filterShape.At(filterShape.Dim() - 3) * filterShape.Rows() * filterShape . Cols(); const auto inputMatrixCols = (outputRows * outputCols); const Shape inputMatrixShape({ N, inputMatrixRows, inputMatrixCols }); CudaDevice device(0, "cuda0"); TensorUtil::TensorData inputData(inputShape, Type::Dense, device); TensorUtil::TensorData filterData(filterShape, Type::Dense, device); TensorUtil::TensorData inputMatrixData(inputMatrixShape, Type::Dense, device); TensorUtil::TensorData reConvertedInputData(inputShape, Type::Dense, device); inputData.SetMode(ComputeMode::Host); filterData.SetMode(ComputeMode::Host); inputMatrixData.SetMode(ComputeMode::Host); reConvertedInputData.SetMode(ComputeMode::Host); int count = 0; for (int i = 0; i < inputData.Size(); ++i) inputData.HostMutableRawPtr()[i] = static_cast<float>((count++) % 9); Compute::Dense::Naive::Im2Col(inputMatrixData, filterData, inputData, strideRow, strideCol, rowPadding, colPadding, dilationRow, dilationCol, 0); if (print) for (int i = 0; i < inputMatrixData.Size(); ++i) std::cout << "Im2Col[" << i << "]: " << inputMatrixData.HostRawPtr()[i] << std::endl; Compute::Initialize::Zeros(inputData); Compute::Dense::Naive::Col2Im(inputData, inputMatrixData, filterData, strideCol, strideRow, rowPadding, colPadding, dilationRow, dilationCol); const Shape newFilterShape( { filterShape.Rows(), filterShape.Size() / filterShape.Rows() }); filterData.Reshape(newFilterShape); if (print) for (int i = 0; i < inputData.Size(); ++i) std::cout << "Col2Im[" << i << "] = " << inputData.HostMutableRawPtr()[i] << std::endl; } void HostConv2DTest(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution dist(-10.0f, 10.0f); const int N = 2; const int numFilters = 5; const int numInputChannels = 4; const int InputRows = 6; const int InputCols = 6; const int filterRows = 2; const int filterCols = 2; const int rowPadding = 2; const int colPadding = 2; const int dilationRow = 2; const int dilationCol = 2; const int strideRow = 2; const int strideCol = 2; const Shape xShape({ N, numInputChannels, InputRows, InputCols }); const Shape filterShape( { numFilters, numInputChannels, filterRows, filterCols }); const int yRows = (static_cast<int>(xShape.Rows()) + 2 * rowPadding - dilationRow * (filterShape.Rows() - 1) - 1) / strideRow + 1; const int yCols = (static_cast<int>(xShape.Cols()) + 2 * colPadding - dilationCol * (filterShape.Cols() - 1) - 1) / strideCol + 1; const Shape yShape({ N, numFilters, (yRows), (yCols) }); CudaDevice device(0, "cuda0"); TensorUtil::TensorData x(xShape, Type::Dense, device); TensorUtil::TensorData dx(xShape, Type::Dense, device); TensorUtil::TensorData filter(filterShape, Type::Dense, device); TensorUtil::TensorData y(yShape, Type::Dense, device); TensorUtil::TensorData dFilter(filterShape, Type::Dense, device); TensorUtil::TensorData dy(yShape, Type::Dense, device); x.SetMode(ComputeMode::Host); dx.SetMode(ComputeMode::Host); filter.SetMode(ComputeMode::Host); y.SetMode(ComputeMode::Host); dFilter.SetMode(ComputeMode::Host); dy.SetMode(ComputeMode::Host); Compute::Initialize::Zeros(y); std::vector<float> filterData(filter.Size()); std::vector<float> xData(x.Size()); for (auto& data : filterData) data = dist(gen); for (auto& data : xData) data = dist(gen); x.SetData(xData); filter.SetData(filterData); Compute::Dense::Naive::Conv2D(y, x, filter, strideRow, strideCol, rowPadding, colPadding, dilationRow, dilationCol, device); auto yDataHost = y.GetDataCopy(); x.ToCuda(); y.ToCuda(); filter.ToCuda(); Compute::Conv2DForward(y, x, filter, strideRow, strideCol, dilationRow, dilationCol, rowPadding, colPadding); auto yDataCuda = y.GetDataCopy(); for (int i = 0; i < y.Size(); ++i) { if (!std::isnan(yDataHost[i]) && !std::isnan(yDataCuda[i])) CHECK(std::abs( yDataHost[i] - yDataCuda[i]) < 0.01f); if (print) std::cout << "host[" << i << "] = " << yDataHost[i] << " cuda[" << i << "] = " << yDataCuda[i] << std::endl; } std::vector<float> dyData(y.Size()); for (auto& data : dyData) data = dist(gen); dx.ToHost(); dFilter.ToHost(); dy.ToHost(); x.ToHost(); filter.ToHost(); Compute::Initialize::Normal(dy, 0.0f, 1.0f); Compute::Initialize::Zeros(dx); Compute::Initialize::Zeros(dFilter); Compute::Dense::Naive::Conv2DBackward(dx, dFilter, dy, x, filter, strideRow, strideCol, rowPadding, colPadding, dilationRow, dilationCol, device); auto dxDataHost = dx.GetDataCopy(); auto dFilterDataHost = dFilter.GetDataCopy(); Compute::Initialize::Zeros(dx); Compute::Initialize::Zeros(dFilter); x.ToCuda(); dx.ToCuda(); filter.ToCuda(); dFilter.ToCuda(); dy.ToCuda(); Compute::Conv2DBackward(dx, dFilter, dy, x, filter, strideRow, strideCol, rowPadding, colPadding, dilationRow, dilationCol); auto dxDataCuda = dx.GetDataCopy(); auto dFilterDataCuda = dFilter.GetDataCopy(); for (int i = 0; i < dx.Size(); ++i) { if (!std::isnan(dxDataHost[i]) && !std::isnan(dxDataCuda[i])) CHECK(std::abs(dxDataHost[i] - dxDataCuda[i]) < 0.01f); if (print) std::cout << "host[" << i << "] = " << dxDataHost[i] << " cuda[" << i << "] = " << dxDataCuda[i] << std::endl; } std::cout << "Filter" << std::endl; for (int i = 0; i < filter.Size(); ++i) { if (!std::isnan(dFilterDataHost[i]) && !std::isnan(dFilterDataCuda[i])) CHECK(std::abs(dFilterDataHost[i] - dFilterDataCuda[i]) < 0.01f); if (print) std::cout << "host[" << i << "] = " << dFilterDataHost[i] << " cuda[" << i << "] = " << dFilterDataCuda[i] << std::endl; } } }
31.739837
80
0.577036
[ "shape", "vector" ]
59156666a862088831512d39a7c7049335608ad1
636
cpp
C++
Easy/Minimum Value to Get Positive Step by Step Sum.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
Easy/Minimum Value to Get Positive Step by Step Sum.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
Easy/Minimum Value to Get Positive Step by Step Sum.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
class Solution { //Runtime: 0 ms, faster than 100.00% of C++ online submissions for Minimum Value to Get Positive Step by Step Sum. public: int minStartValue(vector<int>& nums) { int minimum = min(0,nums[0]); //minimum can either be 0 or a negative value for(int i = 1;i<nums.size();i++) { nums[i] +=nums[i-1]; //Prefix summation minimum = min(minimum,nums[i]); //Getting the minimum value of prefix summation } return (-minimum + 1); //Minimum will be absolute value of (minimum +1) } };
45.428571
155
0.539308
[ "vector" ]
59159b49ec5685bcfde475fbf44e8d5ef4ecc6b8
410
cc
C++
RecoHGCal/TICL/plugins/PatternRecognitionbyMultiClusters.cc
akssikdar/cmssw
060bed0f27c94e9803b26f2f595fab5db394a6d8
[ "Apache-2.0" ]
2
2020-05-09T16:03:43.000Z
2020-05-09T16:03:50.000Z
RecoHGCal/TICL/plugins/PatternRecognitionbyMultiClusters.cc
akssikdar/cmssw
060bed0f27c94e9803b26f2f595fab5db394a6d8
[ "Apache-2.0" ]
null
null
null
RecoHGCal/TICL/plugins/PatternRecognitionbyMultiClusters.cc
akssikdar/cmssw
060bed0f27c94e9803b26f2f595fab5db394a6d8
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
#include "PatternRecognitionbyMultiClusters.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" void ticl::PatternRecognitionbyMultiClusters::makeTracksters( const PatternRecognitionAlgoBase::Inputs& input, std::vector<Trackster>& result, std::unordered_map<int, std::vector<int>>& seedToTracksterAssociation) { LogDebug("HGCPatterRecoTrackster") << "making Tracksters" << std::endl; }
41
76
0.782927
[ "vector" ]