text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
**
** Copyright (C) 1995-1999 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domcore/docfrag.h"
#include "modules/dom/src/domcore/domdoc.h"
#include "modules/dom/src/domcore/domstaticnodelist.h"
#include "modules/dom/src/domhtml/htmlcoll.h"
#include "modules/dom/src/domhtml/htmlelem.h"
#include "modules/dom/src/opatom.h"
#include "modules/dom/src/webforms2/webforms2dom.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/logdoc.h"
#include "modules/logdoc/link.h"
static BOOL IsInvisibleFormElm(HTML_Element *elm, LogicalDocument* logdoc)
{
// Some forms in HTML (not XHTML) are ignored by all form code, since they are nested
// in other forms. They are kept for completeness (layout, dom, etc) but when looking
// from a form perspective they shouldn't exist.
OP_ASSERT(elm->IsMatchingType(HE_FORM, NS_HTML));
if (!logdoc || logdoc->IsXml())
return FALSE;
return elm->GetInserted() < HE_INSERTED_BYPASSING_PARSER && elm->GetFormNr() == -1;
}
/* virtual */ void
DOM_SimpleCollectionFilter::Visit(HTML_Element *element, BOOL &include, BOOL &visit_children, LogicalDocument *logdoc)
{
HTML_ElementType elm_type = element->Type();
BOOL is_html = element->GetNsType() == NS_HTML;
include = FALSE;
visit_children = TRUE;
switch (group)
{
case ALL:
case ALLELEMENTS:
if (Markup::IsRealElement(elm_type))
include = TRUE;
break;
case CHILDREN:
// MSDN: "Retrieves a collection of DHTML Objects that are direct descendants of the object."
// We'll return all elements, skipping text nodes, comments and processing instructions. MSIE will
// also return comments but the implementation is faster if it doesn't, and Mozilla does as Opera.
if (Markup::IsRealElement(elm_type))
include = TRUE;
visit_children = FALSE;
break;
case CHILDNODES:
include = TRUE;
visit_children = FALSE;
break;
case IMAGES:
if (is_html && elm_type == HE_IMG)
include = TRUE;
break;
case AREAS:
if (is_html && elm_type == HE_AREA)
include = TRUE;
break;
case TABLE_SECTION_ROWS:
case TABLE_ROWS:
visit_children = FALSE;
if (is_html)
if (elm_type == HE_TR)
include = TRUE;
else if (group == TABLE_ROWS && (elm_type == HE_TBODY || elm_type == HE_TFOOT || elm_type == HE_THEAD))
{
HTML_Element* parent = element->ParentActual();
if (parent && parent->IsMatchingType(HE_TABLE, NS_HTML))
visit_children = TRUE;
}
break;
case TABLE_CELLS:
case TABLE_ROW_CELLS:
visit_children = FALSE;
if (is_html)
if (elm_type == HE_TD || elm_type == HE_TH)
include = TRUE;
else if (group == TABLE_CELLS && (elm_type == HE_TBODY || elm_type == HE_TFOOT || elm_type == HE_THEAD || elm_type == HE_TR))
visit_children = TRUE;
break;
case TBODIES:
if (is_html && elm_type == HE_TBODY)
include = TRUE;
visit_children = FALSE;
break;
case OPTIONS:
case SELECTED_OPTIONS:
visit_children = FALSE;
if (is_html)
{
if (elm_type == HE_OPTION)
{
if (group == OPTIONS || element->IsSelectedOption())
include = TRUE;
}
else if (elm_type == HE_OPTGROUP)
visit_children = TRUE;
}
break;
case FORMELEMENTS:
if (is_html)
{
switch (elm_type)
{
case HE_SELECT:
case HE_DATALIST:
visit_children = FALSE;
include = TRUE;
break;
case HE_INPUT:
include = element->GetInputType() != INPUT_IMAGE;
break;
case HE_KEYGEN:
case HE_BUTTON:
case HE_OBJECT:
case HE_TEXTAREA:
case HE_FIELDSET:
case HE_OUTPUT:
include = TRUE;
break;
}
}
break;
case APPLETS:
if (is_html && elm_type == HE_APPLET)
include = TRUE;
else if (is_html && elm_type == HE_OBJECT)
{
if (URL* inline_url = element->GetUrlAttr(ATTR_DATA, NS_IDX_HTML, logdoc))
{
HTML_ElementType element_type = elm_type;
OP_BOOLEAN resolve_status = element->GetResolvedObjectType(inline_url, element_type, logdoc);
if (resolve_status == OpBoolean::IS_TRUE && element_type == HE_APPLET)
include = TRUE;
}
}
break;
case LINKS:
if (is_html && ((elm_type == HE_AREA && element->GetAREA_URL(logdoc))
|| (elm_type == HE_A && element->GetA_URL(logdoc))))
include = TRUE;
break;
case FORMS:
if (is_html && elm_type == HE_FORM && !IsInvisibleFormElm(element, logdoc))
include = TRUE;
break;
case ANCHORS:
if (is_html && elm_type == HE_A && element->GetName())
include = TRUE;
break;
case DOCUMENTNODES:
if (is_html)
{
if (elm_type == HE_OBJECT)
{
// We have to avoid returning a collection for the case
// <object id=x><embed id=x></object>
// All browsers do differently but Safari's model seems likely
// to be accepted as HTML5. See bug 288935 and revised bug CORE-19579
// Skip HE_OBJECT elements that has are not fallback-free
HTML_Element* stop = element->NextSiblingActual();
HTML_Element* it = element->NextActual();
BOOL has_fallback = FALSE;
while (it != stop)
{
if (it->IsMatchingType(HE_OBJECT, NS_HTML) ||
it->IsMatchingType(HE_EMBED, NS_HTML))
{
has_fallback = TRUE;
break;
}
it = it->NextActual();
}
if (has_fallback)
{
// Is not "fallback-free"
break; // Skip this node
}
}
BOOL accessible_through_id = TRUE;
if (elm_type == HE_FORM ||
elm_type == HE_IFRAME && !element->HasAttr(ATTR_NAME)) // in MSIE it's available for <iframe name=""> but not for <iframe name>
{
accessible_through_id = FALSE;
}
switch (elm_type)
{
case HE_FORM: // MSIE, FF: Only accessible through name (not id)
if (IsInvisibleFormElm(element, logdoc))
break;
// fallthrough
case HE_IMG: // MSIE: Only through the name. FF: through both id and name
case HE_IFRAME: // MSIE: Through both the name and id _if_ there is a name attribute. HTML5, Safari, FF: Not included at all
case HE_EMBED: // MSIE: Only through the name. FF: through both id and name
case HE_APPLET:
case HE_OBJECT: // MSIE, FF: Through both name and id but in Safari object element isn't included if it contains other content.
// Elements that have a non empty name or id should be included
if (*(const uni_char*)element->GetAttr(ATTR_NAME, ITEM_TYPE_STRING, (void*)UNI_L(""), NS_IDX_HTML))
include = TRUE;
else if (accessible_through_id)
{
const uni_char* id = element->GetId();
include = id && *id;
}
default:
break;
}
}
break;
case NAME_IN_WINDOW:
// When MSIE looks for names in a window (!), it finds anything with a
// name or an id, except form elements (FORM, INPUT, SELECT, TEXTAREA,
// OPTION, BUTTON) inside FORM elements. There is further filtering
// of this collection done in DOM_Collection::FetchPropertiesL() and
// DOM_Collection::GetName(), the only methods reachable on this
// collection.
if (is_html && Markup::IsRealElement(elm_type))
switch (elm_type)
{
case HE_FORM:
if (IsInvisibleFormElm(element, logdoc))
return;
include = TRUE;
break;
case HE_INPUT:
case HE_SELECT:
case HE_OPTION:
case HE_BUTTON:
case HE_TEXTAREA:
if (element->GetFormNr() != -1)
break;
default:
include = TRUE;
}
break;
case EMBEDS:
if (is_html && elm_type == HE_EMBED)
include = TRUE;
break;
case PLUGINS:
if (is_html && elm_type == HE_EMBED)
include = TRUE;
else if (is_html && elm_type == HE_OBJECT)
{
if (URL* inline_url = element->GetUrlAttr(ATTR_DATA, NS_IDX_HTML, logdoc))
{
OP_BOOLEAN resolve_status = element->GetResolvedObjectType(inline_url, elm_type, logdoc);
if (resolve_status == OpBoolean::IS_TRUE && (elm_type == HE_EMBED || elm_type == HE_OBJECT))
include = TRUE;
}
}
break;
case SCRIPTS:
if (is_html && elm_type == HE_SCRIPT)
include = TRUE;
break;
case STYLESHEETS:
if (element->IsLinkElement())
{
if (elm_type == HE_PROCINST)
include = TRUE;
else
{
const uni_char *rel = element->GetStringAttr(ATTR_REL);
if (rel)
{
unsigned kinds = LinkElement::MatchKind(rel);
include = (kinds & LINK_TYPE_STYLESHEET) != 0;
}
}
}
else if (element->IsStyleElement())
include = TRUE;
break;
}
}
/* virtual */ BOOL
DOM_SimpleCollectionFilter::IsMatched(unsigned collections)
{
switch (group)
{
default:
return FALSE;
case SELECTED_OPTIONS:
return (collections & DOM_Environment::COLLECTION_SELECTED_OPTIONS) != 0;
case FORMELEMENTS:
return (collections & DOM_Environment::COLLECTION_FORM_ELEMENTS) != 0;
case APPLETS:
return (collections & DOM_Environment::COLLECTION_APPLETS) != 0;
case LINKS:
return (collections & DOM_Environment::COLLECTION_LINKS) != 0;
case ANCHORS:
return (collections & DOM_Environment::COLLECTION_ANCHORS) != 0;
case DOCUMENTNODES:
return ((collections & DOM_Environment::COLLECTION_DOCUMENT_NODES) != 0 || (collections & DOM_Environment::COLLECTION_NAME_OR_ID) != 0);
case PLUGINS:
return (collections & DOM_Environment::COLLECTION_PLUGINS) != 0;
case STYLESHEETS:
return (collections & DOM_Environment::COLLECTION_STYLESHEETS) != 0;
}
}
/* virtual */ DOM_CollectionFilter *
DOM_SimpleCollectionFilter::Clone() const
{
DOM_SimpleCollectionFilter *filter = OP_NEW(DOM_SimpleCollectionFilter, (group));
if (!filter)
return NULL;
filter->allocated = TRUE;
filter->is_incompatible = is_incompatible;
return filter;
}
/* virtual */ BOOL
DOM_SimpleCollectionFilter::CanSkipChildren()
{
switch (group)
{
case CHILDREN:
case CHILDNODES:
case OPTIONS:
case SELECTED_OPTIONS:
case TABLE_ROWS:
case TABLE_SECTION_ROWS:
case TABLE_CELLS:
case TABLE_ROW_CELLS:
case TBODIES:
case FORMELEMENTS:
/* These can set visit_children to FALSE, which is incompatible
with fast search. */
return TRUE;
default:
return FALSE;
}
}
/* virtual */ BOOL
DOM_SimpleCollectionFilter::CanIncludeGrandChildren()
{
switch (group)
{
case CHILDNODES:
case CHILDREN:
case TABLE_SECTION_ROWS:
case TABLE_ROW_CELLS:
case TBODIES:
/* These will not set visit_children to TRUE */
return FALSE;
default:
return TRUE;
}
}
/* virtual */ BOOL
DOM_SimpleCollectionFilter::IsEqual(DOM_CollectionFilter *other)
{
if (other->GetType() != TYPE_SIMPLE)
return FALSE;
DOM_SimpleCollectionFilter *other_simple = static_cast<DOM_SimpleCollectionFilter *>(other);
return (group == other_simple->group);
}
/* virtual */ void
DOM_HTMLElementCollectionFilter::Visit(HTML_Element *element, BOOL &include, BOOL &visit_children, LogicalDocument *logdoc)
{
HTML_ElementType elm_type = element->Type();
if (!Markup::IsRealElement(elm_type) && elm_type != HE_ANY)
{
include = FALSE;
visit_children = FALSE;
return;
}
BOOL is_html = element->GetNsType() == NS_HTML;
if (is_html && elm_type == tag_match)
{
include = TRUE;
visit_children = tag_match_children;
}
else if (!is_html)
{
const uni_char *elm_tag = element->GetTagName();
include = elm_tag && uni_str_eq(tag_name, elm_tag);
visit_children = tag_match_children;
}
else
{
include = FALSE;
visit_children = TRUE;
}
}
/* virtual */ DOM_CollectionFilter *
DOM_HTMLElementCollectionFilter::Clone() const
{
DOM_HTMLElementCollectionFilter *filter = OP_NEW(DOM_HTMLElementCollectionFilter, (tag_match, tag_name, tag_match_children));
if (!filter)
return NULL;
filter->allocated = TRUE;
filter->is_incompatible = is_incompatible;
return filter;
}
/* virtual */ BOOL
DOM_HTMLElementCollectionFilter::IsEqual(DOM_CollectionFilter *other)
{
if (other->GetType() != TYPE_HTML_ELEMENT)
return FALSE;
DOM_HTMLElementCollectionFilter *other_elem = static_cast<DOM_HTMLElementCollectionFilter *>(other);
return (tag_match == other_elem->tag_match && tag_match_children == other_elem->tag_match_children);
}
/* static */ BOOL
DOM_NameCollectionFilter::IsHETypeWithNameAllowedOnWindow(HTML_ElementType type)
{
/**
* CORE-27753
* when looking up window[name] where name is the name=""
* attribute do NOT return non form and form field elements
* and other special types.
*
* Note that HE_FRAME and HE_IFRAME are missing from this list
* because the nameinwindow collection maps elements by name,
* but JS_Window::GetName calls DOM_GetWindowFrame before
* accessing nameinwindow which properly returns frames by their
* name.
*/
switch (type)
{
//Form elements
case HE_INPUT:
case HE_SELECT:
case HE_OPTION:
case HE_BUTTON:
case HE_TEXTAREA:
case HE_FORM:
// Special stuff http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object
case HE_A:
case HE_APPLET:
case HE_AREA:
case HE_EMBED:
case HE_FRAMESET:
case HE_IMG:
case HE_OBJECT:
return TRUE;
}
return FALSE;
}
#define IS_DOM_FILTER_NAMEINWINDOW(filter) \
((filter) && (filter)->GetType() == DOM_CollectionFilter::TYPE_SIMPLE && \
static_cast<DOM_SimpleCollectionFilter *>(filter)->IsNameInWindow())
/* virtual */ void
DOM_NameCollectionFilter::Visit(HTML_Element *element, BOOL &include, BOOL &visit_children, LogicalDocument *logdoc)
{
if (base)
base->Visit(element, include, visit_children, logdoc);
else
{
include = TRUE;
visit_children = TRUE;
}
if (include)
{
BOOL name_match = FALSE;
if (check_name)
{
const uni_char *elm_name = element->GetName();
if (elm_name)
{
if (IS_DOM_FILTER_NAMEINWINDOW(base) && !IsHETypeWithNameAllowedOnWindow(element->Type()))
elm_name = NULL;
if (elm_name && uni_str_eq(elm_name, name))
name_match = TRUE;
}
}
if (check_id && !name_match)
{
const uni_char *elm_id = element->GetId();
if (elm_id && uni_str_eq(elm_id, name))
name_match = TRUE;
}
include = name_match;
}
}
/* virtual */ DOM_CollectionFilter *
DOM_NameCollectionFilter::Clone() const
{
DOM_CollectionFilter *base_copy = NULL;
if (base)
{
base_copy = base->Clone();
if (!base_copy)
return NULL;
}
const uni_char *name_copy = uni_strdup(name);
if (!name_copy)
{
OP_DELETE(base_copy);
return NULL;
}
DOM_NameCollectionFilter *filter = OP_NEW(DOM_NameCollectionFilter, (base_copy, name_copy, check_name, check_id));
if (!filter)
{
OP_DELETE(base_copy);
op_free((uni_char *) name_copy);
return NULL;
}
filter->allocated = TRUE;
filter->is_incompatible = is_incompatible;
return filter;
}
BOOL
DOM_NameCollectionFilter::CheckIncompatible(DOM_CollectionFilter *base_filter)
{
if (!base_filter || base_filter->GetType() != TYPE_NAME)
return FALSE;
DOM_NameCollectionFilter *base_name = static_cast<DOM_NameCollectionFilter*>(base);
if (!uni_str_eq(name, base_name->name))
return TRUE;
/* If we added a new filter of same name, then the check for same-name has already been performed for the base filter,
hence re-using its is-incompatible is perfectly fine (and desirable.) */
return base_filter->IsIncompatible();
}
/*static*/ BOOL
DOM_NameCollectionFilter::IsNameFilterFor(DOM_CollectionFilter *filter, const uni_char *name)
{
if (!filter || filter->GetType() != TYPE_NAME)
return FALSE;
DOM_NameCollectionFilter *name_filter = static_cast<DOM_NameCollectionFilter*>(filter);
return (name_filter->check_id && name_filter->check_name && name_filter->name && name && uni_str_eq(name, name_filter->name));
}
/* virtual */ BOOL
DOM_NameCollectionFilter::IsMatched(unsigned collections)
{
return (collections & DOM_Environment::COLLECTION_NAME_OR_ID) != 0 || base && base->IsMatched(collections);
}
/* virtual */ BOOL
DOM_NameCollectionFilter::IsEqual(DOM_CollectionFilter *other)
{
if (other->GetType() != TYPE_NAME)
return FALSE;
DOM_NameCollectionFilter *other_name = static_cast<DOM_NameCollectionFilter *>(other);
BOOL same_fields =
(name == other_name->name || name && other_name->name && uni_str_eq(name, other_name->name)) &&
check_name == other_name->check_name && check_id == other_name->check_id;
return (same_fields && (base == other_name->base || base && base->IsEqual(other)));
}
DOM_TagsCollectionFilter::DOM_TagsCollectionFilter(DOM_CollectionFilter *base, const uni_char *ns_uri, const uni_char *name, BOOL is_xml)
: base(base),
any_ns(ns_uri && ns_uri[0] == '*' && !ns_uri[1]),
any_name(name && name[0] == '*' && !name[1]),
ns_uri(ns_uri),
name(name),
is_xml(is_xml)
{
is_incompatible = base && base->IsIncompatible();
}
/* virtual */
DOM_TagsCollectionFilter::~DOM_TagsCollectionFilter()
{
if (allocated)
{
OP_DELETE(base);
uni_char *nc_name = const_cast<uni_char *>(name);
OP_DELETEA(nc_name);
uni_char *nc_ns_uri = const_cast<uni_char *>(ns_uri);
OP_DELETEA(nc_ns_uri);
}
}
BOOL
DOM_TagsCollectionFilter::TagNameMatches(HTML_Element* elm)
{
const uni_char *tagname = elm->GetTagName();
if (!tagname || !*tagname)
return FALSE;
return UseCaseSensitiveCompare(elm) ? uni_str_eq(tagname, name) : uni_stri_eq(tagname, name);
}
/* virtual */ void
DOM_TagsCollectionFilter::Visit(HTML_Element *element, BOOL &include, BOOL &visit_children, LogicalDocument *logdoc)
{
if (base)
{
base->Visit(element, include, visit_children, logdoc);
if (!include)
return;
}
else
visit_children = TRUE;
include = FALSE;
if (name && Markup::IsRealElement(element->Type()))
{
if (!any_ns)
{
const uni_char *uri = g_ns_manager->GetElementAt(element->GetNsIdx())->GetUri();
if (uri && !*uri)
uri = NULL;
if (!ns_uri != !uri || uri && ns_uri && uni_strcmp(uri, ns_uri) != 0)
return;
}
if (!any_name)
{
if (!TagNameMatches(element))
return;
}
include = TRUE;
}
}
/* virtual */ DOM_CollectionFilter *
DOM_TagsCollectionFilter::Clone() const
{
DOM_CollectionFilter *base_copy = NULL;
if (base)
{
base_copy = base->Clone();
if (!base_copy)
return NULL;
}
uni_char *name_copy = (uni_char *) name;
if (name_copy && !(name_copy = UniSetNewStr(name_copy)))
{
OP_DELETE(base_copy);
return NULL;
}
uni_char *ns_uri_copy = (uni_char *) ns_uri;
if (ns_uri_copy && !(ns_uri_copy = UniSetNewStr(ns_uri_copy)))
{
OP_DELETE(base_copy);
OP_DELETEA(name_copy);
return NULL;
}
DOM_TagsCollectionFilter *filter = OP_NEW(DOM_TagsCollectionFilter, (base_copy, ns_uri_copy, name_copy, is_xml));
if (!filter)
{
OP_DELETE(base_copy);
OP_DELETEA(name_copy);
OP_DELETEA(ns_uri_copy);
return NULL;
}
filter->allocated = TRUE;
filter->is_incompatible = is_incompatible;
return filter;
}
/* virtual */ BOOL
DOM_TagsCollectionFilter::IsMatched(unsigned collections)
{
return base && base->IsMatched(collections);
}
/* virtual */ BOOL
DOM_TagsCollectionFilter::IsEqual(DOM_CollectionFilter *other)
{
if (other->GetType() != TYPE_TAGS)
return FALSE;
DOM_TagsCollectionFilter *other_tags = static_cast<DOM_TagsCollectionFilter *>(other);
return (base == other_tags->base &&
is_xml == other_tags->is_xml &&
(any_ns && any_ns == other_tags->any_ns || ns_uri == other_tags->ns_uri || ns_uri && other_tags->ns_uri && uni_str_eq(ns_uri, other_tags->ns_uri)) &&
(any_name && any_name == other_tags->any_name || name == other_tags->name || name && other_tags->name && uni_str_eq(name, other_tags->name)));
}
DOM_NodeCollection::DOM_NodeCollection(BOOL reusable)
: DOM_CollectionLink(reusable),
root(NULL),
filter(NULL),
subcollections(NULL),
tree_root(NULL),
owner(NULL),
include_root(FALSE),
create_subcollections(FALSE),
check_name(TRUE),
check_id(TRUE),
has_named_element_properties(TRUE),
use_form_nr(FALSE),
prefer_window_objects(FALSE),
needs_invalidation(TRUE),
serial_nr(-1),
cached_valid(TRUE),
cached_index(-1),
cached_length(-1),
cached_index_match(NULL)
{
missing_names[0] = missing_names[1] = missing_names[2] = OP_ATOM_UNASSIGNED;
}
/* static */ OP_STATUS
DOM_NodeCollection::Make(DOM_NodeCollection *&collection, DOM_EnvironmentImpl *environment, DOM_Node *root, BOOL include_root, BOOL has_named_properties, const DOM_CollectionFilter &filter_prototype, BOOL reusable)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
if (OpStatus::IsMemoryError(DOMSetObjectRuntime(collection = OP_NEW(DOM_NodeCollection, (reusable)), runtime)) ||
OpStatus::IsError(collection->SetFilter(filter_prototype)))
{
collection = NULL;
return OpStatus::ERR_NO_MEMORY;
}
collection->has_named_element_properties = has_named_properties;
collection->SetRoot(root, include_root);
return OpStatus::OK;
}
OP_STATUS
DOM_NodeCollection::SetFilter(const DOM_CollectionFilter &filter_prototype)
{
OP_ASSERT(!filter);
if (!(filter = filter_prototype.Clone()))
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
void
DOM_NodeCollection::SetRoot(DOM_Node *new_root, BOOL new_include_root)
{
root = new_root;
include_root = new_include_root;
RecalculateTreeRoot();
}
void
DOM_NodeCollection::SetCreateSubcollections()
{
create_subcollections = TRUE;
}
void
DOM_NodeCollection::AddToIndexCache(unsigned int index, HTML_Element *new_element)
{
/* Update the cache if the index is later than already known about. */
if (cached_index < 0 || cached_index < static_cast<int>(index))
{
cached_valid = TRUE;
/* ToDo: insert assert verifying that the item at the given index is indeed correct? */
cached_index = index;
cached_index_match = new_element;
}
}
void
DOM_NodeCollection::RefreshIndexCache(HTML_Element *new_element)
{
/* Re-enable the cache if the indexed element is the same. It is guaranteed by the caller that it
* is now the current element. */
if (!cached_valid && cached_index > 0 && cached_index_match == new_element)
{
cached_valid = TRUE;
}
}
void
DOM_NodeCollection::SetOwner(DOM_Object *new_owner)
{
owner = new_owner;
}
BOOL
DOM_NodeCollection::IsSameCollection(DOM_Node* other_root, BOOL other_include_root, DOM_CollectionFilter* other_filter)
{
return (root == other_root && include_root == static_cast<unsigned>(other_include_root) &&
((filter && filter->IsEqual(other_filter)) || (!filter && !other_filter)));
}
void
DOM_NodeCollection::ElementCollectionStatusChanged(HTML_Element *affected_tree_root, HTML_Element *element, BOOL added, BOOL removed, unsigned collections)
{
if (added && element == tree_root)
{
// Our subtree was added to another tree so we got a new root.
GetEnvironment()->MoveCollection(this, tree_root, affected_tree_root);
tree_root = affected_tree_root;
}
if (tree_root == affected_tree_root)
{
BOOL invalidate_collection = TRUE;
if (added || removed)
{
// Shallow collections (which are common: childNodes, cells, rows, ...) can
// easily avoid being invalidated unnecessary by checking the root element in the
// inserted/removed subtree.
if (filter && !filter->CanIncludeGrandChildren())
{
// We can just check if the element itself is/will be a part of the
// collection. If not, then this collection will not be affected by
// the change and can keep its cache.
invalidate_collection = FALSE;
if (root && element->ParentActual() == root->GetPlaceholderElement())
{
LogicalDocument *logdoc = root->GetOwnerDocument()->GetLogicalDocument();
BOOL include;
BOOL visit_children;
filter->Visit(element, include, visit_children, logdoc);
OP_ASSERT(!visit_children || !"The filter claimed to never set visit_children by returning FALSE in CanIncludeGrandChildren()");
invalidate_collection = include;
}
}
}
if (invalidate_collection && needs_invalidation)
{
needs_invalidation = FALSE;
if (owner)
owner->SignalPropertySetChanged();
SignalPropertySetChanged();
/* Notify caches on the DOM_Collections that share this NodeCollection. */
for (DOM_Collection *collection = collection_listeners.First(); collection; collection = collection->Suc())
collection->SignalPropertySetChanged();
}
HTML_Element *root_element = root->GetPlaceholderElement();
if (removed && element->IsAncestorOf(root_element))
{
GetEnvironment()->MoveCollection(this, tree_root, element);
tree_root = element;
}
/* The selectedOptions collection doesn't include the <select> root
element, but changes are reported via it. Make any invalidation
go ahead for that collection. */
if (element == root_element && !include_root && collections != DOM_EnvironmentImpl::COLLECTION_SELECTED_OPTIONS)
return;
if (invalidate_collection)
ElementCollectionStatusChangedSpecific(affected_tree_root, element, added, removed, collections);
}
}
void
DOM_NodeCollection::ElementCollectionStatusChangedSpecific(HTML_Element *affected_tree_root, HTML_Element *element, BOOL added, BOOL removed, unsigned collections)
{
OP_ASSERT(filter); // Called on a not-fully created collection. Check the construction code.
if (collections == DOM_Environment::COLLECTION_ALL || filter->IsMatched(collections))
{
cached_valid = FALSE;
cached_length = -1;
if (added)
missing_names[0] = missing_names[1] = missing_names[2] = OP_ATOM_UNASSIGNED;
}
if (collections == DOM_Environment::COLLECTION_NAME_OR_ID && added)
missing_names[0] = missing_names[1] = missing_names[2] = OP_ATOM_UNASSIGNED;
OP_ASSERT(!root || tree_root && !tree_root->Parent() || removed && tree_root == element);
}
void
DOM_NodeCollection::ResetRoot(HTML_Element *affected_tree_root)
{
if (tree_root == affected_tree_root)
{
/* Our tree is being garbage collected. Since we mark our root, and
thus the tree, in GCTrace(), this means we are also about to be
garbage collected. Nevertheless, need to reset, in case something
happens in the meantime. */
root = NULL;
GetEnvironment()->MoveCollection(this, tree_root, NULL);
tree_root = NULL;
}
}
/* virtual */
DOM_NodeCollection::~DOM_NodeCollection()
{
OP_DELETE(filter);
collection_listeners.RemoveAll();
}
void
DOM_NodeCollection::UnregisterCollection(DOM_Collection *c)
{
c->Out();
}
OP_STATUS
DOM_NodeCollection::RegisterCollection(DOM_Collection *c)
{
c->Into(&collection_listeners);
return OpStatus::OK;
}
ES_GetState
DOM_NodeCollection::GetLength(int &length, BOOL allowed)
{
OP_ASSERT(filter);
needs_invalidation = TRUE;
BOOL has_length_property = !root || filter->GetType() != DOM_CollectionFilter::TYPE_SIMPLE || static_cast<DOM_SimpleCollectionFilter*>(filter)->HasLengthProperty();
if (!has_length_property)
return GET_FAILED;
if (!allowed)
return GET_SECURITY_VIOLATION;
length = Length();
return GET_SUCCESS;
}
ES_GetState
DOM_NodeCollection::GetCollectionProperty(DOM_Collection *collection, BOOL allowed, const uni_char *property_name, int property_code, ES_Value *value, ES_Runtime *origining_runtime)
{
OpAtom atom = static_cast<OpAtom>(property_code);
OP_ASSERT(atom >= OP_ATOM_UNASSIGNED && atom < OP_ATOM_ABSOLUTELY_LAST_ENUM);
BOOL has_length_value = FALSE;
needs_invalidation = TRUE;
if (atom == OP_ATOM_length && collection->GetName(atom, value, origining_runtime) == GET_SUCCESS)
{
/* A few collections let an object named "length" hide the length property */
OP_ASSERT(filter);
BOOL obj_named_length_hides_coll_length = filter->GetType() == DOM_CollectionFilter::TYPE_SIMPLE && static_cast<DOM_SimpleCollectionFilter*>(filter)->IsObjectHidingLengthProperty();
if (!obj_named_length_hides_coll_length)
return GET_SUCCESS;
has_length_value = TRUE;
}
if (create_subcollections)
{
BOOL found_many;
if (HTML_Element *element = NamedItem(atom, property_name, &found_many))
{
if (!allowed)
return GET_SECURITY_VIOLATION;
if (value)
if (found_many)
{
DOM_Collection *subcollection;
GET_FAILED_IF_ERROR(GetCachedSubcollection(subcollection, property_name));
if (!subcollection)
{
if (DOM_NameCollectionFilter::IsNameFilterFor(filter, property_name))
subcollection = collection;
else
{
DOM_NameCollectionFilter subfilter(filter, property_name);
GET_FAILED_IF_ERROR(DOM_Collection::Make(subcollection, GetEnvironment(), collection->GetRuntime()->GetClass(*collection), root, include_root, TRUE, subfilter));
DOM_NodeCollection *node_subcollection = subcollection->GetNodeCollection();
node_subcollection->create_subcollections = TRUE;
node_subcollection->check_id = check_id;
node_subcollection->check_name = check_name;
node_subcollection->has_named_element_properties = has_named_element_properties;
node_subcollection->use_form_nr = use_form_nr;
GET_FAILED_IF_ERROR(SetCachedSubcollection(property_name, subcollection));
}
}
DOMSetObject(value, *subcollection);
return GET_SUCCESS;
}
else
return SetElement(value, element, static_cast<DOM_Runtime *>(origining_runtime));
else
return GET_SUCCESS;
}
}
else if (HTML_Element *element = NamedItem(atom, property_name))
{
if (!allowed)
return GET_SECURITY_VIOLATION;
if (value)
return SetElement(value, element, static_cast<DOM_Runtime *>(origining_runtime));
else
return GET_SUCCESS;
}
if (atom == OP_ATOM_length)
return has_length_value ? GET_SUCCESS : GET_FAILED;
if (atom == OP_ATOM_UNASSIGNED)
return GET_FAILED;
return collection->GetName(atom, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_Collection::GetName(const uni_char *property_name, int property_code, ES_Value *value, ES_Runtime *origining_runtime)
{
BOOL allowed = OriginCheck(origining_runtime);
return GetNodeCollection()->GetCollectionProperty(this, allowed, property_name, property_code, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_Collection::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
BOOL allowed = OriginCheck(origining_runtime);
if (HTML_Element *element = GetNodeCollection()->Item(property_index))
if (!allowed)
return GET_SECURITY_VIOLATION;
else
return GetNodeCollection()->SetElement(value, element, static_cast<DOM_Runtime *>(origining_runtime));
else
return GET_FAILED;
}
/* static */ OP_STATUS
DOM_Collection::Make(DOM_Collection *&collection, DOM_EnvironmentImpl *environment, const uni_char *uni_class_name, const char *class_name, DOM_Node *root, BOOL include_root, BOOL try_sharing, const DOM_CollectionFilter &filter_prototype, DOM_Runtime::Prototype &prototype)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
if (!(collection = OP_NEW(DOM_Collection, ())) ||
OpStatus::IsMemoryError(collection->SetFunctionRuntime(runtime, runtime->GetPrototype(prototype), uni_class_name, class_name, "s-")))
{
OP_DELETE(collection);
return OpStatus::ERR_NO_MEMORY;
}
DOM_NodeCollection *node_collection;
if (try_sharing)
{
BOOL found = filter_prototype.IsElementFilter() ?
environment->FindElementCollection(node_collection, root, include_root, const_cast<DOM_CollectionFilter *>(&filter_prototype)) :
environment->FindNodeCollection(node_collection, root, include_root, const_cast<DOM_CollectionFilter *>(&filter_prototype));
if (found)
{
RETURN_IF_ERROR(node_collection->RegisterCollection(collection));
collection->node_collection = node_collection;
return OpStatus::OK;
}
}
RETURN_IF_ERROR(DOM_NodeCollection::Make(node_collection, environment, root, include_root, prototype == DOM_Runtime::HTMLCOLLECTION_PROTOTYPE, filter_prototype, try_sharing));
RETURN_IF_ERROR(node_collection->RegisterCollection(collection));
collection->node_collection = node_collection;
return OpStatus::OK;
}
/* static */ OP_STATUS
DOM_Collection::Make(DOM_Collection *&collection, DOM_EnvironmentImpl *environment, const char *class_name, DOM_Node *root, BOOL include_root, BOOL try_sharing, const DOM_CollectionFilter &filter_prototype)
{
DOM_Runtime::Prototype prototype;
if (op_strcmp(class_name, "NodeList") == 0)
prototype = DOM_Runtime::NODELIST_PROTOTYPE;
else
prototype = DOM_Runtime::HTMLCOLLECTION_PROTOTYPE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append(class_name));
return DOM_Collection::Make(collection, environment, buffer.GetStorage(), class_name, root, include_root, try_sharing, filter_prototype, prototype);
}
/* static */ OP_STATUS
DOM_Collection::MakeNodeList(DOM_Collection *&collection, DOM_EnvironmentImpl *environment, DOM_Node *root, BOOL include_root, BOOL try_sharing, const DOM_CollectionFilter &filter_prototype)
{
DOM_Runtime::Prototype prototype = DOM_Runtime::NODELIST_PROTOTYPE;
return DOM_Collection::Make(collection, environment, UNI_L("NodeList"), "NodeList", root, include_root, try_sharing, filter_prototype, prototype);
}
void
DOM_Collection::SetCreateSubcollections()
{
GetNodeCollection()->SetCreateSubcollections();
}
/* virtual */ ES_GetState
DOM_Collection::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
{
BOOL allowed = OriginCheck(origining_runtime);
int length;
ES_GetState result = GetNodeCollection()->GetLength(length, allowed);
if (result == GET_SUCCESS)
DOMSetNumber(value, length);
return result;
}
else
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_Collection::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
return PUT_READ_ONLY;
else
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ int
DOM_Collection::Call(ES_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, ES_Runtime* origining_runtime)
{
DOM_CHECK_ARGUMENTS("s");
if (!OriginCheck(origining_runtime))
return ES_EXCEPT_SECURITY;
return CallAsGetNameOrGetIndex(argv[0].value.string, return_value, (DOM_Runtime *) origining_runtime);
}
/* virtual */
DOM_Collection::~DOM_Collection()
{
Out();
}
/* virtual */ void
DOM_Collection::GCTrace()
{
GCMark(node_collection);
}
/* virtual */ void
DOM_NodeCollection::GCTrace()
{
GCMark(root);
GCMark(subcollections);
}
/* virtual */ ES_GetState
DOM_Collection::FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime *origining_runtime)
{
ES_GetState result = DOM_Object::FetchPropertiesL(enumerator, origining_runtime);
if (result != GET_SUCCESS)
return result;
if (!GetNodeCollection()->has_named_element_properties)
return GET_SUCCESS;
BOOL is_name_in_window = IS_DOM_FILTER_NAMEINWINDOW(GetNodeCollection()->GetFilter());
int length = GetNodeCollection()->Length();
for (int index = 0; index < length; ++index)
{
HTML_Element *item = GetNodeCollection()->Item(index);
if (GetNodeCollection()->check_name)
{
const uni_char *name = item->GetName();
if (name && *name && (!is_name_in_window || DOM_NameCollectionFilter::IsHETypeWithNameAllowedOnWindow(item->Type())))
enumerator->AddPropertyL(name);
}
if (GetNodeCollection()->check_id)
{
const uni_char *id = item->GetId();
if (id && *id)
enumerator->AddPropertyL(id);
}
}
return GET_SUCCESS;
}
/* virtual */ ES_GetState
DOM_Collection::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime)
{
count = GetNodeCollection()->Length();
return GET_SUCCESS;
}
int
DOM_NodeCollection::Length()
{
if (!root || filter->IsIncompatible())
return 0;
UpdateSerialNr();
if (cached_length != -1)
return cached_length;
int length = 0;
const uni_char *name;
unsigned index_to_cache = 0;
HTML_Element *elem_to_cache = NULL;
HTML_Element *root_element = GetRootElement();
if (!root_element)
return 0;
LogicalDocument *logdoc = root->GetOwnerDocument()->GetLogicalDocument();
if (logdoc && check_id && check_name && (!filter->CanSkipChildren() && filter->IsNameSearch(name)))
{
NamedElementsIterator iterator;
int matched = logdoc->SearchNamedElements(iterator, root_element, name, TRUE, TRUE);
HTML_Element* form = use_form_nr ? GetForm() : NULL;
for (int index2 = 0; index2 < matched; ++index2)
{
BOOL include;
BOOL visit_children;
HTML_Element *iter = iterator.GetNextElement();
if (!use_form_nr || iter->BelongsToForm(root->GetFramesDocument(), form))
filter->Visit(iter, include, visit_children, logdoc);
else
include = FALSE;
if (include)
{
OP_ASSERT(!(IsElementCollection() && !Markup::IsRealElement(iter->Type())) || !"Element collections must not include non-element nodes");
index_to_cache = length;
elem_to_cache = iter;
++length;
}
}
}
else
{
HTML_Element *iter = root_element;
HTML_Element *stop = iter->NextSiblingActual();
HTML_Element* form = NULL;
if (!include_root)
iter = iter->NextActual();
if (use_form_nr)
{
form = GetForm();
stop = NULL;
}
while (iter != stop)
{
BOOL include;
BOOL visit_children;
filter->Visit(iter, include, visit_children, logdoc);
// Check that an invalidation assumption is correct.
OP_ASSERT(!include || Markup::IsRealElement(iter->Type()) || !IsElementCollection() || !"Assumption in ElementCollectionStatusChanged about only one collection included text nodes is incorrect");
include = include && (!use_form_nr || iter->BelongsToForm(root->GetFramesDocument(), form));
if (include)
{
elem_to_cache = iter;
index_to_cache = length;
++length;
}
if (visit_children)
iter = iter->NextActual();
else
iter = iter->NextSiblingActual();
}
}
if (cached_index < 0 && elem_to_cache)
{
cached_valid = TRUE;
cached_index_match = elem_to_cache;
cached_index = index_to_cache;
}
cached_length = length;
return length;
}
/* virtual */ HTML_Element *
DOM_NodeCollection::Item(int index)
{
if (!root || filter->IsIncompatible())
return NULL;
UpdateSerialNr();
if (cached_length != -1 && index >= cached_length)
return NULL;
if (cached_valid && cached_index_match && cached_index == index)
return cached_index_match;
/* Force the computation of length (and seeding of cache) to determine if given index is out of bounds. */
if (cached_length == -1)
{
cached_length = Length();
if (index >= cached_length)
return NULL;
}
HTML_Element *root_element = GetRootElement();
if (!root_element)
return NULL;
HTML_Element *iter = root_element;
HTML_Element *stop = iter->NextSiblingActual();
int start_index = index;
HTML_Element* form = NULL;
BOOL forward = TRUE;
if (!include_root)
iter = iter->NextActual();
if (use_form_nr)
{
form = GetForm();
stop = NULL;
}
BOOL can_skip_children = filter->CanSkipChildren();
if (cached_valid && cached_index_match)
{
if (cached_index == index)
return cached_index_match;
else if (cached_index < index)
{
index -= cached_index;
iter = cached_index_match;
}
else if (cached_index - index < index)
{
index = cached_index - index;
iter = cached_index_match;
forward = FALSE;
}
}
BOOL include = FALSE;
BOOL visit_children = FALSE;
LogicalDocument *logdoc = GetLogicalDocument();
FramesDocument *root_doc = root->GetFramesDocument();
while (iter != stop)
{
filter->Visit(iter, include, visit_children, logdoc);
already_visited:
include = include && (!use_form_nr || iter->BelongsToForm(root_doc, form));
if (include)
if (index == 0)
{
cached_valid = TRUE;
cached_index = start_index;
cached_index_match = iter;
return iter;
}
else
--index;
if (forward)
if (visit_children)
iter = iter->NextActual();
else
iter = iter->NextSiblingActual();
else
{
iter = iter->PrevActual();
if (can_skip_children && iter)
{
HTML_Element *candidate = NULL;
BOOL candidate_include = FALSE;
for (HTML_Element *ancestor = iter->ParentActual(); ancestor; ancestor = ancestor->ParentActual())
{
if (!include_root && ancestor == root_element)
break;
if (filter)
filter->Visit(ancestor, include, visit_children, logdoc);
if (!visit_children)
{
candidate = ancestor;
candidate_include = include;
}
if (ancestor == root_element)
break;
}
if (candidate)
{
iter = candidate;
include = candidate_include;
goto already_visited;
}
}
}
}
return NULL;
}
HTML_Element *
DOM_NodeCollection::NamedItem(OpAtom atom, const uni_char *name, BOOL *found_many)
{
if (!root || filter->IsIncompatible())
return NULL;
UpdateSerialNr();
if (atom != OP_ATOM_UNASSIGNED)
if (atom == missing_names[0] || atom == missing_names[1] || atom == missing_names[2])
return NULL;
DOM_NameCollectionFilter name_filter(filter, name, check_name, check_id);
HTML_Element *found_element = NULL;
HTML_Element *root_element = GetRootElement();
if (!root_element)
return NULL;
LogicalDocument *logdoc = root->GetOwnerDocument()->GetLogicalDocument();
if (logdoc && logdoc->GetRoot()->IsAncestorOf(root_element))
{
BOOL found = FALSE;
BOOL can_skip_children = name_filter.CanSkipChildren();
NamedElementsIterator iterator;
int matched = logdoc->SearchNamedElements(iterator, root_element, name, check_id, check_name);
HTML_Element* form = use_form_nr ? GetForm() : NULL;
for (int index = 0; index < matched; ++index)
{
BOOL include;
BOOL visit_children;
HTML_Element *iter = iterator.GetNextElement();
name_filter.Visit(iter, include, visit_children, logdoc);
include = include && (!use_form_nr || iter->BelongsToForm(root->GetFramesDocument(), form));
if (include && can_skip_children && !use_form_nr)
for (HTML_Element *parent = iter->Parent(); parent && parent != root_element; parent = parent->Parent())
{
BOOL include2, visit_children2;
name_filter.Visit(parent, include2, visit_children2, logdoc);
if (!visit_children2)
{
include = FALSE;
break;
}
}
if (include)
if (found)
{
*found_many = TRUE;
return found_element;
}
else if (found_many)
{
found = TRUE;
*found_many = FALSE;
found_element = iter;
}
else
return iter;
}
}
else
{
HTML_Element *iter = root_element;
HTML_Element *stop = iter->NextSiblingActual();
HTML_Element* form = NULL;
if (!include_root)
iter = iter->NextActual();
if (use_form_nr)
{
form = GetForm();
stop = NULL;
}
BOOL found = FALSE;
while (iter != stop)
{
BOOL include;
BOOL visit_children;
name_filter.Visit(iter, include, visit_children, logdoc);
include = include && (!use_form_nr ||
iter->BelongsToForm(root->GetFramesDocument(), form)
);
if (include)
if (found)
{
*found_many = TRUE;
return found_element;
}
else if (found_many)
{
found = TRUE;
*found_many = FALSE;
found_element = iter;
}
else
return iter;
if (visit_children)
iter = iter->NextActual();
else
iter = iter->NextSiblingActual();
}
}
if (atom != OP_ATOM_UNASSIGNED && !found_element)
{
missing_names[2] = missing_names[1];
missing_names[1] = missing_names[0];
missing_names[0] = atom;
}
return found_element;
}
int
DOM_Collection::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
if (this_object && this_object->IsA(DOM_TYPE_STATIC_NODE_LIST))
return DOM_StaticNodeList::getItem(this_object, argv, argc, return_value, origining_runtime);
DOM_THIS_OBJECT(collection, DOM_TYPE_COLLECTION, DOM_Collection);
DOM_CHECK_ARGUMENTS("N");
int index = TruncateDoubleToInt(argv[0].value.number);
ES_GetState state = collection->GetIndex(index, return_value, origining_runtime);
if (state == GET_FAILED)
{
DOMSetNull(return_value);
return ES_VALUE;
}
else
return ConvertGetNameToCall(state, return_value);
}
int
DOM_HTMLCollection::namedItem(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(collection, DOM_TYPE_COLLECTION, DOM_Collection);
DOM_CHECK_ARGUMENTS("s");
ES_GetState state = collection->GetName(argv[0].value.string, OP_ATOM_UNASSIGNED, return_value, origining_runtime);
if (state == GET_FAILED)
{
DOMSetNull(return_value);
return ES_VALUE;
}
else
return ConvertGetNameToCall(state, return_value);
}
int
DOM_NodeCollection::GetTags(const uni_char *name, ES_Value *return_value)
{
BOOL is_xml = root && root->GetOwnerDocument()->IsXML(); // if we have an empty (not loaded) document, it doesn't matter if it's xml or not.
DOM_TagsCollectionFilter tag_filter(filter, NULL, name, is_xml);
DOM_Collection *tags;
CALL_FAILED_IF_ERROR(DOM_Collection::Make(tags, GetEnvironment(), "TagsArray", root, include_root, TRUE, tag_filter));
tags->GetNodeCollection()->SetCreateSubcollections();
DOMSetObject(return_value, tags);
return ES_VALUE;
}
int
DOM_HTMLCollection::tags(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(base, DOM_TYPE_COLLECTION, DOM_Collection);
DOM_CHECK_ARGUMENTS("s");
return base->GetNodeCollection()->GetTags(argv[0].value.string, return_value);
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_HTMLCollection)
DOM_FUNCTIONS_FUNCTION(DOM_HTMLCollection, DOM_HTMLCollection::namedItem, "namedItem", "s-")
DOM_FUNCTIONS_END(DOM_HTMLCollection)
DOM_FUNCTIONS_START(DOM_Collection)
DOM_FUNCTIONS_FUNCTION(DOM_Collection, DOM_Collection::item, "item", "n-")
DOM_FUNCTIONS_END(DOM_Collection)
void
DOM_NodeCollection::RecalculateTreeRoot()
{
HTML_Element* new_tree_root;
if (root)
{
new_tree_root = root->GetPlaceholderElement();
if (new_tree_root)
while (HTML_Element *parent = new_tree_root->Parent())
new_tree_root = parent;
}
else
new_tree_root = NULL;
if (new_tree_root != tree_root)
{
GetEnvironment()->MoveCollection(this, tree_root, new_tree_root);
tree_root = new_tree_root;
}
}
OP_STATUS
DOM_NodeCollection::GetCachedSubcollection(DOM_Collection *&subcollection, const uni_char *name)
{
subcollection = NULL;
if (subcollections)
{
OP_BOOLEAN result;
ES_Value value;
RETURN_IF_ERROR(result = subcollections->Get(name, &value));
if (result == OpBoolean::IS_TRUE)
subcollection = DOM_VALUE2OBJECT(value, DOM_Collection);
}
return OpStatus::OK;
}
OP_STATUS
DOM_NodeCollection::SetCachedSubcollection(const uni_char *name, DOM_Collection *subcollection)
{
if (!subcollections)
{
DOM_Runtime *runtime = GetEnvironment()->GetDOMRuntime();
if (OpStatus::IsMemoryError(DOMSetObjectRuntime(subcollections = OP_NEW(DOM_Object, ()), runtime)))
{
subcollections = NULL;
return OpStatus::ERR_NO_MEMORY;
}
}
return subcollections->Put(name, *subcollection);
}
ES_GetState
DOM_NodeCollection::SetElement(ES_Value *value, HTML_Element *element, DOM_Runtime *origining_runtime)
{
ES_GetState state = root->DOMSetElement(value, element);
if (prefer_window_objects && value->type == VALUE_OBJECT)
{
DOM_Node *node = DOM_HOSTOBJECT(value->value.object, DOM_Node);
if (node->IsA(DOM_TYPE_HTML_FRAMEELEMENT))
{
DOM_HTMLFrameElement *frameelement = static_cast<DOM_HTMLFrameElement *>(node);
return frameelement->GetName(OP_ATOM_contentWindow, value, origining_runtime);
}
}
return state;
}
HTML_Element *
DOM_NodeCollection::GetRootElement()
{
if (!root)
return NULL;
HTML_Element *element = root->GetPlaceholderElement();
if (use_form_nr)
{
HTML_Element *document_element = root->GetOwnerDocument()->GetPlaceholderElement();
if (document_element && document_element->IsAncestorOf(element))
return document_element;
}
return element;
}
int
DOM_NodeCollection::GetFormNr()
{
OP_ASSERT(root->GetPlaceholderElement()->Type() == HE_FORM);
return root->GetPlaceholderElement()->GetFormNr();
}
HTML_Element*
DOM_NodeCollection::GetForm()
{
OP_ASSERT(root->GetPlaceholderElement()->Type() == HE_FORM);
return root->GetPlaceholderElement();
}
void
DOM_NodeCollection::UpdateSerialNr()
{
if (!GetEnvironment()->GetFramesDocument())
{
/* This collection belongs to a 'disconnected' environment, in which
collection updating won't be performed by logdoc, so just drop
anything we think we know. This means collections in disconnected
environments are slow, but they ought to be used sparingly. */
cached_valid = FALSE;
cached_index = -1;
cached_length = -1;
cached_index_match = NULL;
missing_names[0] = missing_names[1] = missing_names[2] = OP_ATOM_UNASSIGNED;
}
needs_invalidation = TRUE;
}
/* static */ OP_STATUS
DOM_HTMLOptionsCollection::Make(DOM_HTMLOptionsCollection *&collection, DOM_EnvironmentImpl *environment, DOM_Element *select_element)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
DOM_SimpleCollectionFilter filter(OPTIONS);
DOM_NodeCollection *node_collection;
RETURN_IF_ERROR(DOM_NodeCollection::Make(node_collection, environment, select_element, FALSE, TRUE, filter, FALSE));
if (!(collection = OP_NEW(DOM_HTMLOptionsCollection, ())) ||
OpStatus::IsMemoryError(collection->SetFunctionRuntime(runtime, runtime->GetPrototype(DOM_Runtime::HTMLOPTIONSCOLLECTION_PROTOTYPE), "HTMLOptionsCollection", "s")))
{
OP_DELETE(collection);
return OpStatus::ERR_NO_MEMORY;
}
RETURN_IF_ERROR(node_collection->RegisterCollection(collection));
collection->node_collection = node_collection;
node_collection->SetRoot(select_element, FALSE);
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_HTMLOptionsCollection::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_selectedIndex:
case OP_ATOM_value:
return GetNodeCollection()->root->GetName(property_name, value, origining_runtime);
default:
return DOM_Collection::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_HTMLOptionsCollection::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
case OP_ATOM_selectedIndex:
case OP_ATOM_value:
return GetNodeCollection()->GetRoot()->PutName(property_name, value, origining_runtime);
default:
return DOM_Collection::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_HTMLOptionsCollection::PutNameRestart(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime, ES_Object* restart_object)
{
return static_cast<DOM_HTMLSelectElement *>(GetNodeCollection()->GetRoot())->PutNameRestart(property_name, value, origining_runtime, restart_object);
}
/* virtual */ ES_PutState
DOM_HTMLOptionsCollection::PutIndex(int property_index, ES_Value* value, ES_Runtime *origining_runtime)
{
return static_cast<DOM_HTMLSelectElement *>(GetNodeCollection()->GetRoot())->PutIndex(property_index, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_HTMLOptionsCollection::PutIndexRestart(int property_index, ES_Value* value, ES_Runtime *origining_runtime, ES_Object* restart_object)
{
return static_cast<DOM_HTMLSelectElement *>(GetNodeCollection()->GetRoot())->PutIndexRestart(property_index, value, origining_runtime, restart_object);
}
int
DOM_HTMLOptionsCollection::addOrRemove(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
if (argc >= 0)
{
DOM_THIS_OBJECT(options, DOM_TYPE_HTML_OPTIONS_COLLECTION, DOM_HTMLOptionsCollection);
return DOM_HTMLSelectElement::addOrRemove((DOM_HTMLSelectElement *) options->GetNodeCollection()->GetRoot(), argv, argc, return_value, origining_runtime, data);
}
else
return DOM_HTMLSelectElement::addOrRemove(NULL, NULL, -1, return_value, origining_runtime, data);
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_WITH_DATA_START(DOM_HTMLOptionsCollection)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_HTMLOptionsCollection, DOM_HTMLOptionsCollection::addOrRemove, 0, "add", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_HTMLOptionsCollection, DOM_HTMLOptionsCollection::addOrRemove, 1, "remove", "n-")
DOM_FUNCTIONS_WITH_DATA_END(DOM_HTMLOptionsCollection)
|
#include "JackTokenizer.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <unordered_set>
JackTokenizer::JackTokenizer(std::string fileInput){
inputFile.open(fileInput);
if(!inputFile.is_open()){
std::cerr << "Error opening " << fileInput << "." << std::endl;
return;
}
else{
keywords.insert("class");
keywords.insert("constructor");
keywords.insert("function");
keywords.insert("method");
keywords.insert("field");
keywords.insert("static");
keywords.insert("var");
keywords.insert("int");
keywords.insert("char");
keywords.insert("boolean");
keywords.insert("void");
keywords.insert("true");
keywords.insert("false");
keywords.insert("null");
keywords.insert("this");
keywords.insert("let");
keywords.insert("do");
keywords.insert("if");
keywords.insert("else");
keywords.insert("while");
keywords.insert("return");
symbols.insert('{');
symbols.insert('}');
symbols.insert('(');
symbols.insert(')');
symbols.insert('[');
symbols.insert(']');
symbols.insert('.');
symbols.insert(',');
symbols.insert(';');
symbols.insert('+');
symbols.insert('-');
symbols.insert('*');
symbols.insert('/');
symbols.insert('&');
symbols.insert('|');
symbols.insert('<');
symbols.insert('>');
symbols.insert('=');
symbols.insert('~');
}
}
bool JackTokenizer::hasMoreTokens(){
return(!inputFile.eof());
}
void JackTokenizer::advance(){
while(hasMoreTokens()){
getline(inputFile, currentLine);
if((currentLine.find("/*") != std::string::npos ||
currentLine.find("/**") != std::string::npos) && hasMoreTokens()){
int endComment = currentLine.find("*/");
while(endComment == std::string::npos && hasMoreTokens()){
getline(inputFile, currentLine);
endComment = currentLine.find("*/");
}
continue;
}
std::stringstream tokenStream(currentLine);
while(tokenStream){
currentToken.clear();
tokenStream >> currentToken;
//Take care of comments
if(currentToken.substr(0,2) == "//"){
break;
}
if((currentToken.find("/*") != std::string::npos ||
currentToken.find("/**") != std::string::npos) && hasMoreTokens()){
int endComment = currentLine.find("*/");
while(endComment == std::string::npos && hasMoreTokens()){
getline(inputFile, currentLine);
}
break;
}
//Take care of string literals here
int quotePosition = currentToken.find("\"");
if(quotePosition == std::string::npos && currentToken.length() != 0){
extractSymbols(currentToken);
}
if(quotePosition != std::string::npos){
if(quotePosition == 0){
std::string stringLiteral = currentToken;
stringLiteral += " ";
while(tokenStream){
currentToken.clear();
tokenStream >> currentToken;
stringLiteral += currentToken;
}
stringLiteral = currentToken.substr(0, currentToken.length() - 1);
currentToken = stringLiteral;
extractSymbols(currentToken);
}
else{
std::string tempToken = currentToken.substr(0, quotePosition);
extractSymbols(tempToken);
std::string stringLiteral = currentToken.substr(quotePosition);
stringLiteral += " ";
while(tokenStream){
currentToken.clear();
tokenStream >> currentToken;
stringLiteral += currentToken;
stringLiteral += " ";
}
stringLiteral = stringLiteral.substr(0, stringLiteral.length() - 2);
currentToken = stringLiteral;
extractSymbols(currentToken);
}
}
}
}
cleanTokenVector();
}
void JackTokenizer::cleanTokenVector(){
int a = 0;
while(a < tokens.size()){
if(tokens[a].length() == 0){
tokens.erase(tokens.begin() + a);
a--;
}
a++;
}
}
std::string JackTokenizer::tokenType(std::string token){
if(keywords.find(token) != keywords.end()){
return "KEYWORD";
}
else if(symbols.find(token[0]) != symbols.end()){
return "SYMBOL";
}
else if(isdigit(token[0])){
return "INT_CONST";
}
else if(token[0] == '"' && token.back() == '"'){
return "STRING_CONST";
}
else{
return "IDENTIFIER";
}
}
std::string JackTokenizer::keyWord(std::string token){
std::unordered_set<std::string>::iterator tok = keywords.find(token);
std::string key = *tok;
std::string upperKey = "";
for(int i = 0; i < key.length(); i++){
upperKey += std::toupper(key[i]);
}
return upperKey;
}
char JackTokenizer::symbol(char token){
std::unordered_set<char>::iterator tok = symbols.find(currentToken[0]);
return *tok;
}
std::string JackTokenizer::identifier(std::string token){
return token;
}
int JackTokenizer::intVal(){
return std::stoi(currentToken);
}
void JackTokenizer::extractSymbols(std::string token){
bool symbol_found = false;
for(int i = 0; i < token.length(); i++){
if(symbols.find(token[i]) != symbols.end()){
symbol_found = true;
break;
}
}
if(symbol_found == false){
tokens.push_back(token);
}
else{
int j = 0;
while(j < token.length()){
if(symbols.find(token[j]) != symbols.end() && token.length() > 0){
if(j > 0){
tokens.push_back(token.substr(0, j));
tokens.push_back(std::string(1, token[j]));
token.erase(0, j + 1);
}
else{
tokens.push_back(std::string(1, token[0]));
token = token.substr(1);
}
j=-1;
}
j++;
}
}
if(token.length() > 0 && symbol_found == true){
tokens.push_back(token);
}
}
JackTokenizer::~JackTokenizer(){
tokens.clear();
if(inputFile.is_open()){
inputFile.close();
}
}
|
#ifndef _TABLE_H
#define _TABLE_H
#include <time.h>
#include "TableTimer.h"
#include "Player.h"
#include "GameLogic.h"
#include "Configure.h"
#define STATUS_TABLE_CLOSE -1 //桌子关闭
#define STATUS_TABLE_EMPTY 0 //桌子空
#define STATUS_TABLE_READY 1 //桌子正在准备
#define STATUS_TABLE_ACTIVE 2 //桌子正在玩牌
#define STATUS_TABLE_OVER 3 //桌子游戏结束
#define GAME_OVER_TIME 2500
typedef std::set<Player *> PlayerSet;
typedef struct _LeaverInfo
{
int uid;
short m_nTabIndex;
char name[64];
int64_t betcoin;
short source;
short cid;
short pid;
short sid;
bool m_bAllin;
int64_t m_lMoney;
int64_t betCoinList[5];
int m_nWin;
int m_nLose;
int m_nRunAway;
int m_nTie;
int m_nMagicNum;
int m_nMagicCoinCount;
int64_t m_lMaxWinMoney;
int64_t m_lMaxCardValue;
}LeaverInfo;
typedef struct _ContainBet
{
int uid;
int64_t betcoin;
bool hashandle;
_ContainBet():uid(0), betcoin(0), hashandle(false)
{};
}ContainBet;
typedef struct _PoolInfo
{
ContainBet userBet[GAME_PLAYER];
int64_t betCoinCount;
}PoolInfo;
class Table
{
public:
Table();
virtual ~Table();
void init();
void reset();
//内置函数
public:
inline void closeTable(){this->m_nStatus = STATUS_TABLE_CLOSE;};
inline bool isClose(){return m_nStatus==STATUS_TABLE_CLOSE;};
inline bool hasOnePlayer() {return m_nCountPlayer == 1;};
inline bool isEmpty(){return m_nStatus==STATUS_TABLE_EMPTY || m_nCountPlayer == 0;};
inline bool isNotFull() {return m_nCountPlayer < Configure::getInstance()->numplayer;};
inline bool isActive() {return this->m_nStatus == STATUS_TABLE_ACTIVE;};
inline char* getPassword() { return password; }
inline void setStartTime(time_t t){StartTime = t;}
inline time_t getStartTime(){return StartTime;}
inline void setEndTime(time_t t){EndTime = t;}
inline time_t getEndTime(){return EndTime;}
inline void setGameID(const char* id) {strcpy(GameID, id);}
inline const char* getGameID() {return GameID;}
inline void setEndType(short type){EndType = type;}
inline short getEndType(){return EndType;}
inline void lockTable(){kicktimeflag = true; KickTime = time(NULL);}
inline void unlockTable(){kicktimeflag = false;}
inline bool isLock(){return kicktimeflag;}
//行为函数
public:
void reSetInfo();
void setTableConf();
bool isUserInTab(int uid);
Player* getPlayer(int uid);
Player* getPlayerInTab(int uid);
int playerComming(Player* player, int tabindex = -1);
void playerLeave(int uid);
void playerLeave(Player* player);
void setSeatNULL(Player* player);
//用户在桌子上找到一个座位
int playerSeatInTab(Player* player);
//只有一个人能有操作,需要直接发牌结束
bool isOnlyOneOprate();
Player* getNextBetPlayer(Player* player, short playeroptype);
void setPlayerOptype(Player* player, short playeroptype);
void setPlayerlimitcoin();
bool isCanGameStart();
bool isAllReady();
int64_t getSecondLargeCoin();
void gameStart();
bool iscanGameOver();
bool SelectMaxUser(UserWinList &EndResult);
int calcCoin();
//赢钱的用户 输钱的用户ID 输多少钱给这个用户 几个人分
void setWinnerPool(Player* winner, int loserID, int64_t losecoin, short averageNum = 1);
int gameOver();
//设置下一轮的信息,并且发牌
int setNextRound();
void setKickTimer();
int setBottomPool(short currRound);
void setUserBetBool(int index, int64_t betroundcoin);
int setFirstBetter();
void setSumPool();
int64_t getSumPool();
void calcMaxValue(Player* player);
bool isAllRobot();
void privateRoomOp();
//时间函数
public:
void stopAllTimer();
void startBetCoinTimer(int uid,int timeout);
void stopBetCoinTimer();
void startTableStartTimer(int timeout);
void stopTableStartTimer();
void startKickTimer(int timeout);
void stopKickTimer();
void startSendCardTimer(int timeout);
void stopSendCardTimer();
void startGameOverTimer(int timeout);
void stopGameOverTimer();
public:
//新增站起和坐下函数
int playerSeatInTab(Player* player, int tabindex);
int playerStandUp(Player* player);
int playerSeatDown(Player* player, int tabindex);
int playerChangeSeat(Player* player, int tabindex);
inline bool isViewers(Player *player) { return m_Viewers.find(player) != m_Viewers.end(); }
void LeaveViewers(Player* player);
void JoinViewers(Player* player);
void SendGift(Player* player, int price, BYTE sendtoall);
//游戏逻辑相关
public:
GameLogic m_GameLogic; //游戏逻辑
BYTE m_cbCenterCardData[MAX_CENTERCOUNT];
//新增站起和坐下
PlayerSet m_Viewers;
public:
int id;
short m_nStatus; //-1不可用 0 空
Player* player_array[GAME_PLAYER];
bool isthrowwin;
bool hassendcard;
int m_nType; //金币场类型
int64_t m_lBigBlind; //大盲
float m_lTax; //税收
int64_t m_lGameLimt; //这局能够下注的最大额度
int m_nMustBetCoin; //必下的金币额度
BYTE m_bCurrRound;
int64_t m_lCurrMax; //当前此轮下注最大的金额
int m_nRaseUid; //加注的用户
int m_nCurrBetUid; //当前下注的人
int64_t m_lSumPool; //底池总共数额
//中途玩牌下注了的人离开的信息
LeaverInfo leaverarry[GAME_PLAYER];
short leavercount;
short m_nCountPlayer;
int m_nMagicCoin; //魔法表情金币
public:
BYTE m_bMaxNum; //当前桌子最大人数
Player* m_pFirstBetter; //第一个下注的人
short m_nDealerIndex; //dealer位置
int m_nDealerUid; //dealer用户ID
short m_nSmallBlindIndex; //小盲的位置
int m_nSmallBlindUid; //小盲的用户ID
short m_nBigBlindIndex; //大盲的位置
int m_nBigBlindUid; //大盲的用户ID
int64_t m_lCanMaxBetCoin;
PoolInfo m_PoolArray[GAME_PLAYER]; //边池的数组
short m_nPoolNum; //边池的个数
bool m_bThisRoundHasAllin; //这轮是否有人allin的标志
bool m_bIsOverTimer; //是否启动结束超时时间
bool m_bIsFirstSetPool; //大小盲之后就有人allin了
//私人房信息
public:
int m_nOwner;
bool m_bHaspasswd;
char tableName[64];
char password[64];
//准备信息,处理第一次进入要倒计时准备的问题
public:
//当前桌子是否是在踢人倒计时
bool kicktimeflag;
time_t KickTime;
//用于进入机器人
public:
time_t m_nRePlayTime;
time_t SendCardTime;
private:
TableTimer timer ;
time_t StartTime; //开始玩牌的时间
time_t EndTime; //结束玩牌的时间
short EndType;
char GameID[64];
};
#endif
|
// Some common utilities needed for IP and web applications
// Author: Guido Socher
// Copyright: GPL V2
//
// 2010-05-20 <jc@wippler.nl>
#include "EtherCard.h"
void EtherCard::copyIp (uint8_t *dst, const uint8_t *src) {
memcpy(dst, src, IP_LEN);
}
void EtherCard::copyMac (uint8_t *dst, const uint8_t *src) {
memcpy(dst, src, ETH_LEN);
}
void EtherCard::printIp (const char* msg, const uint8_t *buf) {
Serial.print(msg);
EtherCard::printIp(buf);
Serial.println();
}
void EtherCard::printIp (const uint8_t *buf) {
for (uint8_t i = 0; i < IP_LEN; ++i) {
Serial.print( buf[i], DEC );
if (i < 3)
Serial.print('.');
}
}
|
/**
* @author:divyakhetan
* @date: 2/1/2019
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
do{
cout << s << endl;
}while(next_permutation(s.begin(), s.end()));
}
|
/**
* Copyright 2015 ViajeFacil
* @author Hugo Ferrando Seage
*/
#include <string>
#include "./owner.hpp"
#include "./nego.hpp"
#include "./pelVector.hpp"
Owner::Owner() : nombre_("") {}
Owner::Owner(std::string nombre) : nombre_(nombre) {}
Owner::~Owner() {}
void Owner::setNombre(std::string nombre) { nombre_ = nombre; }
std::string Owner::getNombre() { return nombre_; }
pel::Vector<Oficina> &Owner::getOficinas() { return oficinas_; }
pel::Vector<std::shared_ptr<Nego>> &Owner::getNegos() { return negos_; }
|
#include <array>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <functional>
#include <chrono>
using namespace std;
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include "osc/OscOutboundPacketStream.h"
#include "ip/UdpSocket.h"
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
// Myo armband
#include <myo/myo.hpp>
typedef std::array<int8_t, 8> DataPacket;
typedef std::function<void(const DataPacket&)> NewDataCallback;
class DataSource {
public:
virtual ~DataSource() { };
virtual void poll() = 0;
void setCallback(NewDataCallback cb) { mNewDataCallback = cb; }
protected:
NewDataCallback mNewDataCallback;
};
class RandomDataSource : public DataSource {
public:
RandomDataSource()
: mLastTime(RandomClock::now())
, mFPS(std::chrono::milliseconds((int) (1000.0f / 30.0f)))
{
}
virtual void poll() {
if (RandomClock::now() - mLastTime < mFPS)
return;
DataPacket p;
for (int i = 0; i < p.size(); i++) {
p[i] = (((float) rand() / (float) RAND_MAX) * 255.0f) - 127.0f;
}
mNewDataCallback(p);
}
private:
typedef std::chrono::system_clock RandomClock;
RandomClock::time_point mLastTime;
RandomClock::duration mFPS;
};
class DataCollector : public DataSource, public myo::DeviceListener {
public:
DataCollector()
: emgSamples()
, mConnected(false)
{
}
~DataCollector() {
delete mHub;
}
bool connect()
{
try {
std::cout << "Creating hub" << std::endl;
mHub = new myo::Hub("com.bzztbomb.myo_server");
std::cout << "Searching for arm band" << std::endl;
// Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo
// immediately.
// waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and
// if that fails, the function will return a null pointer.
mMyo = mHub->waitForMyo(10000);
// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
if (!mMyo) {
throw std::runtime_error("Unable to find a Myo!");
}
// We've found a Myo.
std::cout << "Connected to a Myo armband!" << std::endl << std::endl;
// Next we enable EMG streaming on the found Myo.
mMyo->setStreamEmg(myo::Myo::streamEmgEnabled);
// Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause
// Hub::run() to send events to all registered device listeners.
mHub->addListener(this);
} catch (std::exception e) {
std::cout << "Failed to connect: " << e.what() << std::endl;
return false;
}
return true;
}
void poll() {
if (!mConnected) {
mConnected = connect();
}
mHub->run(1000/20);
}
// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
void onUnpair(myo::Myo* myo, uint64_t timestamp)
{
// We've lost a Myo.
// Let's clean up some leftover state.
emgSamples.fill(0);
if (mNewDataCallback)
mNewDataCallback(emgSamples);
mConnected = false;
std::cout << "Lost connection!" << std::endl;
}
virtual void onDisconnect(myo::Myo* myo, uint64_t timestamp) {
onUnpair(myo, timestamp);
}
// onEmgData() is called whenever a paired Myo has provided new EMG data, and EMG streaming is enabled.
void onEmgData(myo::Myo* myo, uint64_t timestamp, const int8_t* emg)
{
for (int i = 0; i < 8; i++) {
emgSamples[i] = emg[i];
}
if (mNewDataCallback)
mNewDataCallback(emgSamples);
}
// There are other virtual functions in DeviceListener that we could override here, like onAccelerometerData().
// For this example, the functions overridden above are sufficient.
private:
myo::Hub* mHub;
myo::Myo* mMyo;
// The values of this array is set by onEmgData() above.
std::array<int8_t, 8> emgSamples;
bool mConnected;
};
//#define ADDRESS "127.0.0.1"
//#define PORT 7000
//
#define OUTPUT_BUFFER_SIZE 1024
std::vector<UdpTransmitSocket*> oscOutputs;
void addOscOutput(const std::string& in_address, bool broadcast) {
auto pos = find(in_address.begin(), in_address.end(), ':');
if (pos == in_address.end()) {
cerr << in_address << " does specifiy a port, should be address:port" << endl;
exit(1);
}
string address = in_address.substr(0, pos - in_address.begin());
int port = stoi(in_address.substr(pos - in_address.begin() + 1));
// Initialize the broadcast sockets
UdpTransmitSocket* output = new UdpTransmitSocket(IpEndpointName(address.c_str(), port));
output->SetAllowReuse(true);
if (broadcast)
output->SetEnableBroadcast(true);
oscOutputs.push_back(output);
cout << "OSC: " << (broadcast ? "Broadcasting on " : "Sending to ") << address << ", port: " << port << endl;
}
typedef websocketpp::server<websocketpp::config::asio> server;
typedef websocketpp::connection_hdl connection_hdl;
typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;
server print_server;
con_list connections;
void on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) {
std::cout << msg->get_payload() << std::endl;
}
void on_open(connection_hdl hdl) {
connections.insert(hdl);
}
void on_close(connection_hdl hdl) {
connections.erase(hdl);
}
void print(const DataPacket& packet) {
// Clear the current line
// std::cout << '\r';
//
// // Print out the EMG data.
// for (size_t i = 0; i < packet.size(); i++) {
// std::ostringstream oss;
// oss << static_cast<int>(packet[i]);
// std::string emgString = oss.str();
//
// std::cout << '[' << emgString << std::string(4 - emgString.size(), ' ') << ']';
// }
//
// std::cout << std::flush;
// Send OSC
char buffer[OUTPUT_BUFFER_SIZE];
osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );
p << osc::BeginBundleImmediate << osc::BeginMessage( "/myo" );
for (int i = 0; i < packet.size(); i++)
p << packet[i];
p << osc::EndMessage << osc::EndBundle;
for (auto i : oscOutputs)
i->Send(p.Data(), p.Size());
std::stringstream val;
val << "[ ";
for (int i = 0; i < packet.size(); i++)
val << to_string(packet[i]) << (i != packet.size() - 1 ? "," : "");
val << "]";
// Send WebSocket
for (auto i : connections) {
try {
print_server.send(i, val.str(),websocketpp::frame::opcode::text);
}
catch (websocketpp::exception const & e) {
std::cout << "Exception during send: " << e.what() << std::endl;
}
}
}
int main(int argc, char** argv)
{
bool random_source = false;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("oscbroadcast", po::value< vector<string> >(), "broadcast packets on this address:port")
("oscsend", po::value< vector<string> >(), "send packets directly to address:port")
("randomsource", po::value<bool>(&random_source)->default_value(false), "use random numbers instead of emg data")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
std::vector<std::pair<string, bool>> oscOuts = {
{ "oscbroadcast", true },
{ "oscsend", false }
};
for (auto option : oscOuts) {
if (vm.count(option.first)) {
for (auto i : vm[option.first].as< vector<string> >())
addOscOutput(i, option.second);
}
}
RandomDataSource random;
DataCollector collector;
DataSource* activeSource = &random;
if (!random_source)
{
activeSource = &collector;
}
activeSource->setCallback(print);
print_server.set_open_handler(&on_open);
print_server.set_close_handler(&on_close);
print_server.set_message_handler(&on_message);
print_server.init_asio();
print_server.listen(9002);
print_server.start_accept();
websocketpp::server<websocketpp::config::asio> server;
print_server.clear_access_channels(websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload);
// this will turn off console output for frame header and payload
print_server.clear_access_channels(websocketpp::log::alevel::all);
// this will turn off everything in console output
while (1) {
activeSource->poll();
print_server.get_io_service().poll();
this_thread::sleep_for(chrono::milliseconds(1));
}
}
|
//
// CommStation.h
// SAD
//
// Created by Marquez, Richard A on 4/9/15.
// Copyright (c) 2015 Richard Marquez. All rights reserved.
//
#pragma once
#include <StandardCplusplus.h>
#include <vector>
#include <SoftwareSerial.h>
#include "Drone.h"
#include "Packet.h"
#include "Rangefinder.h"
#include "Command.h"
#include "main.h"
using namespace std;
// Bluetooth LE (KEDSUM)
#define BT_TX_PIN 12
#define BT_RX_PIN 11
#define BAUD_RATE 9600
class CommStation {
private:
Drone drone;
SoftwareSerial* serial;
public:
CommStation();
static CommStation& getInstance();
bool isAvailable();
bool isBusy();
Command getCmd();
void sendString(String data);
void sendPacket(Packet packet);
};
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.UX.FileSource.h>
#include <Uno.UX.Property-1.h>
namespace g{namespace Fuse{namespace Controls{struct Image;}}}
namespace g{namespace Uno{namespace UX{struct PropertyObject;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{struct app18_FuseControlsImage_File_Property;}
namespace g{
// internal sealed class app18_FuseControlsImage_File_Property :336
// {
::g::Uno::UX::Property1_type* app18_FuseControlsImage_File_Property_typeof();
void app18_FuseControlsImage_File_Property__ctor_3_fn(app18_FuseControlsImage_File_Property* __this, ::g::Fuse::Controls::Image* obj, ::g::Uno::UX::Selector* name);
void app18_FuseControlsImage_File_Property__Get1_fn(app18_FuseControlsImage_File_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::UX::FileSource** __retval);
void app18_FuseControlsImage_File_Property__New1_fn(::g::Fuse::Controls::Image* obj, ::g::Uno::UX::Selector* name, app18_FuseControlsImage_File_Property** __retval);
void app18_FuseControlsImage_File_Property__get_Object_fn(app18_FuseControlsImage_File_Property* __this, ::g::Uno::UX::PropertyObject** __retval);
void app18_FuseControlsImage_File_Property__Set1_fn(app18_FuseControlsImage_File_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::UX::FileSource* v, uObject* origin);
struct app18_FuseControlsImage_File_Property : ::g::Uno::UX::Property1
{
uWeak< ::g::Fuse::Controls::Image*> _obj;
void ctor_3(::g::Fuse::Controls::Image* obj, ::g::Uno::UX::Selector name);
static app18_FuseControlsImage_File_Property* New1(::g::Fuse::Controls::Image* obj, ::g::Uno::UX::Selector name);
};
// }
} // ::g
|
int check=0;
int flag=0;
int i;
int duration=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(13,INPUT_PULLUP);
pinMode(2,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
check=digitalRead(13);
if(check==0)
{
digitalWrite(2,HIGH);
Serial.println(check);
flag=1;
}
else if(check==1&&flag==1){
/*方法一
for(i=0;i<=20;i+=1){
digitalWrite(2,HIGH);
delay(250);
digitalWrite(2,LOW);
delay(250);
}*/
//方法二
int starttime=millis();
while(duration<=5000){
digitalWrite(2,HIGH);
delay(250);
digitalWrite(2,LOW);
delay(250);
duration=millis()-starttime;
Serial.println(duration);
}
flag=0;
duration=0;
}
else{
digitalWrite(2,LOW);
}
}
|
#include <sstream>
#include <pthread.h>
#include <chrono>
#include "libs/cache/OptionsFunction.h"
#include "options/Option.hpp"
#include "options/OptionCall.hpp"
#include "binomial_method/case/Case.hpp"
#include "binomial_method/method/BinomialMethod.hpp"
#include "graphs_generator/GraphsGenerator.h"
#include "binomial_method/method/regular/euro/EuroBinomialMethod.hpp"
#include "binomial_method/method/regular/euro/EuroBinomialMethod2.hpp"
#include "binomial_method/method/regular/american/AmericanBinomialMethod.hpp"
#include "binomial_method/method/regular/american/AmericanBinomialMethod2.hpp"
#include "binomial_method/method/regular/american/AmericanBinomialMethod3.hpp"
#include "options/OptionPut.hpp"
#include "black_scholes/BlackScholesMerton.hpp"
#include "black_scholes/BlackScholesMertonCall.hpp"
#include "greekjet/greekjet3/GreekJet3.h"
#include "finite_diffrence_methods/method/transformed_diffusion_equation/implicit/EuroImplicitHeatEqMethod.hpp"
#include "finite_diffrence_methods/method/transformed_diffusion_equation/explicit/EuroExplicitHeatEqMethod.hpp"
#include "finite_diffrence_methods/method/regular/crank_nicolson/EuroCNMethod.hpp"
#include "finite_diffrence_methods/method/regular/explicit/EuroExplicitMethod.hpp"
// SETTINGS
//#define STEPS 400
#define CORES 4
#define FROM 250
#define TO 350
#define STEP 1
#define FILE_NAME "/home/agnieszka/Studia/masters-document/chapter_bm_implementation_results/diagrams/greeks/deltaWithQ.txt"
// END OF SETTINGS
#define INTERVAL_LEN ((TO-FROM)/CORES)
typedef GreekJet3 GreekJet;
class EuroRegularPutB : public OptionsFunction<double> {
public:
double calculate(const double &s, const double &t, const double &r, const double &sigma, const int steps) override {
// GreekJet i_s(s, GreekJetVar ::S), i_r(r, GreekJetVar ::R), i_t(t, GreekJetVar ::T),
// i_sigma(sigma, GreekJetVar ::SIGMA), i_e(105.);
double i_s(s), i_r(r), i_t(t), i_sigma(sigma), i_e(100.);
double xl = 0.0;
double xu = 2 * i_s;
int M = 100;
Option<double> *option = new OptionPut<double>(i_t, i_s, i_r, i_sigma, i_e);
FDMethod<double> *method = new EuroExplicitMethod<double>(option, xl, xu, steps, M);
method->solve(false);
double result = method->average_approximation();
delete method;
delete option;
return result;
// BlackScholesMertonPut bs(i_s, i_e, i_r, i_sigma, i_t);
// return bs.calculate(0.0);
}
};
class arg_struct {
public:
double s = 0.0;
double t = 0.0;
double r = 0.0;
double sigma = 0.0;
double from = 0.0;
double to = 0.0;
double step = 0.0;
int steps = 500;
string var = "S";
std::string fileName = "";
};
void *Thread(void *args) {
auto *a = new EuroRegularPutB();
auto *arg = (arg_struct *) args;
GraphsGenerator s(a);
s.generate(arg->s, arg->t, arg->r, arg->sigma, arg->steps, arg->from, arg->to, arg->step, arg->fileName, arg->var);
delete arg;
delete a;
return nullptr;
}
pthread_t threads[CORES];
std::string createFileName(int i) {
std::stringstream sstm;
sstm << "tmp" << i;
std::string result = sstm.str();
return result;
}
const void createThread(double from, double to, int i) {
auto *args = new arg_struct();
args->fileName = createFileName(i + 1);
args->s = 100.;
args->t = 1. / 12;
args->r = 0.05;
args->sigma = 0.2;
args->from = from;
args->to = to;
args->step = STEP;
args->var = "STEPS";
pthread_create(&threads[i], nullptr, Thread, (void *) args);
}
int main() {
std::string name = FILE_NAME;
double from = FROM;
for (int i = 0; i < CORES; i++) {
createThread(from, from + INTERVAL_LEN, i);
from = from + INTERVAL_LEN + STEP;
}
for (auto thread : threads) {
pthread_join(thread, nullptr);
}
ofstream output(name, ios_base::trunc);
output << "x y" << endl;
for (int i = 0; i < CORES; i++) {
ifstream file(createFileName(i + 1));
output << file.rdbuf();
file.close();
remove(createFileName(i).c_str());
}
output.close();
}
|
#include "roommanager.h"
#include "YIMPlatformDefine.h"
#include "globalsetting.h"
#include "ui_roommanager.h"
#include "httprequester.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QStringList>
#include <QDebug>
#include <QProcess>
RoomManagerDialog::RoomManagerDialog(XString roomID, QWidget *parent) :
QDialog(parent),
ui(new Ui::RoomManager)
,m_roomID(roomID)
{
ui->setupUi(this);
setWindowTitle(QStringLiteral("房间管理"));
m_requester = new HttpRequester();
ui->label_roomNum->setText(QString::fromStdWString(roomID));
connect(ui->btn_room_cnt, SIGNAL(clicked()), this, SLOT(slot_room_cnt()));
connect(ui->btn_add_robots, SIGNAL(clicked()), this, SLOT(slot_add_robot_in_room()));
connect(ui->btn_del_robots,SIGNAL(clicked()), this, SLOT(slot_kickoff()));
connect(ui->btn_all_rooms, SIGNAL(clicked()), this, SLOT(slot_room_list()));
connect(m_requester, SIGNAL(data_recved(QByteArray)),
this, SLOT(slot_setup_data(QByteArray)));
YIMManager::CreateInstance()->SetChatRoomCallback(this);
}
void RoomManagerDialog::setUp()
{
m_process = new QProcess(this);
m_process->start("");
}
void RoomManagerDialog::slot_room_cnt()
{
YIMManager* im = YIMManager::CreateInstance();
YIMErrorcode code =
im->GetChatRoomManager()->GetRoomMemberCount(m_roomID.c_str());
if (code != YIMErrorcode_Success) {
qDebug() << "Call GetRoomMemberCount Failed " << code;
}else {
qDebug() << "Call GetRoomMemberCount success " << code;
}
}
void RoomManagerDialog::OnGetRoomMemberCount(YIMErrorcode errorcode,
const XString &chatRoomID,
unsigned int count)
{
if (errorcode != YIMErrorcode_Success)
qDebug() << "GetRoomMemberCount callback error , code is" << errorcode;
qDebug() << "Room " << XStringToLocal(chatRoomID).c_str() << " number :" << count;
ui->lineedit_room_cnt->setText(QString::number(count));
}
void RoomManagerDialog::slot_kickoff()
{
//踢人踢出用户
}
void RoomManagerDialog::slot_add_robot_in_room()
{
//用restapi像房间里加人
//To Do
QString host = GlobalSettings::getInstance()->getHost(true);
QString strUrl = host + "v1/im/query_im_enter_channel";
int number = ui->spinBox_add->value();
for (int i = 1; i <= number; ++i) {
QString userID = QString("robot_") + QString::number(10000 + i);
QString body = QString("{\"UserID\": \"%1\", \"ChannelID\": \"%2\"}")
.arg(userID)
.arg(QString::fromStdWString(m_roomID));
m_requester->youme_sendData(strUrl, body);
}
}
void RoomManagerDialog::slot_room_list()
{
QString host = GlobalSettings::getInstance()->getHost();
QString strUrl = host + "v1/im/get_room_list";
QString body = QString("{}");
m_requester->youme_sendData(strUrl, body);
}
void RoomManagerDialog::slot_setup_data(QByteArray data)
{
QJsonObject object = QJsonDocument::fromJson(data).object();
int room_cnt = object["room_cnt"].toInt();
QJsonArray room_list = object["room_list"].toArray();
QStringList ls;
foreach (QJsonValue member, room_list) {
QJsonObject objectItem = member.toObject();
ls << objectItem["room_name"].toString();
}
ui->textEdit_room_list->append(QString::number(room_cnt));
ui->textEdit_room_list->append(ls.join(","));
}
RoomManagerDialog::~RoomManagerDialog()
{
delete ui;
delete m_requester;
m_requester = nullptr;
YIMManager::CreateInstance()->SetChatRoomCallback(nullptr);
}
|
// timeoperator.h
#ifndef _TIMEOPERATOR_H_
#define _TIMEOPERATOR_H_
class Time{
public:
Time();
Time(int h, int m=0);
void AddMin(int m);
void AddHour(int h);
void Reset(int h=0, int m=0);
Time operator+(const Time& t) const;
Time operator-(const Time& t) const;
Time operator*(double n) const;
// Time Sum(const Time& t) const;
void Show() const;
~Time();
private:
int hours;
int minutes;
};
#endif
|
#ifndef _FILENAME_TIME
#define _FILENAME_TIME
#include <afxwin.h> // MFC 核心和标准组件
#include <string>
class FilenameTime{
std::string name;
CTime time;
public:
FilenameTime(){}
FilenameTime(std::string filename, CTime related_time)
{
name = filename;
time = related_time;
}
std::string get_name()const
{
return name;
}
CTime get_time()const
{
return time;
}
bool name_equal(const FilenameTime &right)const
{
return name == right.get_name();
}
};
bool time_less_than(const FilenameTime &left,const FilenameTime &right);
#endif //_FILENAME_TIME
|
/*
* Copyright 2019 LogMeIn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
// C++ Coroutine TS Trait implementations
#ifdef ASYNCLY_HAS_COROUTINES
#include <experimental/coroutine>
namespace asyncly {
namespace detail {
template <typename T>
coro_awaiter<T>::coro_awaiter(Future<T>* future)
: future_{ future }
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_awaiter::coro_awaiter"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
template <typename T> coro_awaiter<T>::~coro_awaiter()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_awaiter::~coro_awaiter"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
template <typename T> bool coro_awaiter<T>::await_ready()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_ready()"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return false;
}
// todo: use bool-version to shortcut ready futures
template <typename T>
void coro_awaiter<T>::await_suspend(std::experimental::coroutine_handle<> coroutine_handle)
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
auto executor = this_thread::get_current_executor();
future_
->catch_error([this, coroutine_handle, executor](auto e) mutable {
error_ = e;
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "catch_error: coroutine_handle.resume() on thread "
<< std::this_thread::get_id() << std::endl;
#endif
executor->post([coroutine_handle]() mutable { coroutine_handle.resume(); });
})
.then([this, coroutine_handle, executor](T value) mutable {
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "then: coroutine_handle.resume() with value " << value << " on thread "
<< std::this_thread::get_id() << std::endl;
#endif
value_.emplace(value);
executor->post([coroutine_handle]() mutable { coroutine_handle.resume(); });
});
}
template <typename T> T coro_awaiter<T>::await_resume()
{
if (error_) {
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_resume with error on thread " << std::this_thread::get_id()
<< std::endl;
#endif
std::rethrow_exception(error_);
} else {
auto value = *value_;
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_resume with value " << value << " on thread "
<< std::this_thread::get_id() << std::endl;
#endif
return value;
}
}
inline coro_awaiter<void>::coro_awaiter(Future<void>* future)
: future_{ future }
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_awaiter::coro_awaiter"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
inline coro_awaiter<void>::~coro_awaiter()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_awaiter::~coro_awaiter"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
inline bool coro_awaiter<void>::await_ready()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_ready()"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return false;
}
// todo: use bool-version to shortcut ready futures
inline void
coro_awaiter<void>::await_suspend(std::experimental::coroutine_handle<> coroutine_handle)
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
auto executor = this_thread::get_current_executor();
future_
->catch_error([this, coroutine_handle, executor](auto e) mutable {
error_ = e;
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "catch_error: coroutine_handle.resume() on thread "
<< std::this_thread::get_id() << std::endl;
#endif
executor->post([coroutine_handle]() mutable { coroutine_handle.resume(); });
})
.then([coroutine_handle, executor]() mutable {
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "then: coroutine_handle.resume() on thread " << std::this_thread::get_id()
<< std::endl;
#endif
executor->post([coroutine_handle]() mutable { coroutine_handle.resume(); });
});
}
inline void coro_awaiter<void>::await_resume()
{
if (error_) {
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_resume with error on thread " << std::this_thread::get_id()
<< std::endl;
#endif
std::rethrow_exception(error_);
} else {
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "await_resume on thread " << std::this_thread::get_id() << std::endl;
#endif
return;
}
}
template <typename T> std::experimental::suspend_never coro_promise<T>::initial_suspend()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "initial_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return {};
}
template <typename T> std::experimental::suspend_never coro_promise<T>::final_suspend()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "final_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return {};
}
template <typename T>
coro_promise<T>::coro_promise()
: promise_{ new Promise<T>(std::get<1>(make_lazy_future<T>())) }
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::coro_promise"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
template <typename T> void coro_promise<T>::unhandled_exception()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::set_exception"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
promise_->set_exception(std::current_exception());
}
template <typename T> void coro_promise<T>::return_value(T value)
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::return_value"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
promise_->set_value(value);
}
inline coro_promise<void>::coro_promise()
: promise_{ new Promise<void>(std::get<1>(make_lazy_future<void>())) }
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::coro_promise"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
inline coro_promise<void>::~coro_promise()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::~coro_promise"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
}
inline Future<void> coro_promise<void>::get_return_object()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::get_return_object"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return promise_->get_future();
}
std::experimental::suspend_never coro_promise<void>::initial_suspend()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::initial_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return {};
}
std::experimental::suspend_never coro_promise<void>::final_suspend()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::final_suspend"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
return {};
}
void coro_promise<void>::unhandled_exception()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::set_exception"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
promise_->set_exception(std::current_exception());
}
void coro_promise<void>::return_void()
{
#ifdef ASYNCLY_FUTURE_DEBUG
std::cerr << "coro_promise::return_void"
<< " on thread " << std::this_thread::get_id() << std::endl;
#endif
promise_->set_value();
}
}
}
#endif
|
#pragma once
#include <Poco/Runnable.h>
#include <Poco/SharedPtr.h>
namespace BeeeOn {
class StoppableRunnable : public Poco::Runnable {
public:
typedef Poco::SharedPtr<StoppableRunnable> Ptr;
virtual ~StoppableRunnable();
/**
* Stop the runnable. The call should not block.
*/
virtual void stop() = 0;
};
}
|
#include "mouse_picker.h"
namespace sloth {
MousePicker::MousePicker(const RawCamera & camera, const glm::mat4 & projection, const Terrain &terrain)
:m_Projection(projection), m_Camera(camera), m_Terrain(terrain)
{
m_View = camera.getViewMatrix();
m_CurrentRay = calculateMouseRay();
}
void MousePicker::update()
{
m_View = m_Camera.getViewMatrix();
m_CurrentRay = calculateMouseRay();
if (intersectionInRange(0.0f, MOUSE_PICKER_RAY_CASTING_RANGE, m_CurrentRay)) {
m_TerrainPosition = binarySearch(MOUSE_PICKER_RECURSION_COUNT, 0.0f, MOUSE_PICKER_RAY_CASTING_RANGE, m_CurrentRay);
}
}
glm::vec3 MousePicker::calculateMouseRay()
{
// 获取鼠标位置
float mouseX = (float) Input::cursorPosX;
float mouseY = (float) Input::cursorPosY;
// 将鼠标位置转换为OpenGL内NDC坐标
auto normalizedCoord = glm::vec2((2.0f * mouseX) / SCREEN_WIDTH - 1.0f, 1.0f - (2.0f * mouseY) / SCREEN_HEIGHT);
// 将NDC坐标转换为投影后坐标,由于不需要深度,不需要完全
// 逆向透视除法,将z设为-1.0f即可
auto clipCoord = glm::vec4(normalizedCoord, -1.0f, 1.0f);
// 将投影后坐标转换为相机空间,
// 由于不保存深度,需要将z分量设为-1.0f
// 此时的向量只保存方向,故将w分量设为0.0f
auto cameraCoord = glm::inverse(m_Projection) * clipCoord;
cameraCoord.z = -1.0f;
cameraCoord.w = 0.0f;
// 将相机空间坐标转换为世界坐标
auto worldCoord = glm::inverse(m_View) * cameraCoord;
// 只需要三个分量,返回单位向量
return glm::normalize(glm::vec3(worldCoord.x, worldCoord.y, worldCoord.z));
}
glm::vec3 MousePicker::binarySearch(int count, float start, float finish, const glm::vec3 & ray)
{
int times = 0;
float half = start + (finish - start) / 2.0f;
while (count != times) {
// TODO!多地图集增加判断
// Terrain *terrain = getTerrain(...)
if (intersectionInRange(start, half, ray)) {
++times;
finish = half;
}
else {
++times;
start = half;
}
half = start + (finish - start) / 2.0f;
}
return getPointOnRay(ray, half);
}
bool MousePicker::intersectionInRange(float start, float finish, const glm::vec3 & ray) const
{
// 如果start点在地面之上且finish点在地面之下,则返回true
return !isUnderGround(getPointOnRay(ray, start)) &&
isUnderGround(getPointOnRay(ray, finish)) ? true : false;
}
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
long long int test,i,n,k,p,a,b,c;
while(scanf("%lld",&test)==1)
{
for(i=1; i<=test; i++)
{
scanf("%lld %lld %lld",&n,&k,&p);
if(2<=n<=23 && 1<=k<=n && 1<=p<=200)
{
for(a=k,b=0; b<=p ; a++,b++ )
{
if(a>n && b<=p)
{
a=1;
}
}
printf("Case %lld: %lld\n",i,a-1);
}
}
}
return 0;
}
|
#include <iostream>
#include "password.h"
#include "Hashbook.h"
using namespace std;
int main()
{
Password secret;
secret.make_password();
secret.get_password();
system("pause");
return 0;
}
|
#include "BufferChain.hpp"
char g_read_medium[BUFFER_SIZE_MEDIUM] = {};
char g_read_large[BUFFER_SIZE_LARGE] = {};
BufferChain::BufferChain()
{
}
BufferChain::BufferChain(BufferChain& buff)
{
_chain = buff._chain;
}
BufferChain& BufferChain::operator=(BufferChain& chain)
{
flush();
_chain = chain._chain;
return (*this);
}
BufferChain::~BufferChain()
{
flush();
}
void BufferChain::pushBack(std::string* toadd)
{
_chain.push_back(toadd);
}
void BufferChain::pushFront(std::string* toadd)
{
_chain.push_front(toadd);
}
std::string* BufferChain::getFirst()
{
if (_chain.empty())
return NULL;
return _chain.front();
}
std::string* BufferChain::getLast()
{
if (_chain.empty())
return NULL;
return _chain.back();
}
void BufferChain::popFirst()
{
_chain.pop_front();
}
BufferChain::iterator BufferChain::begin()
{
return _chain.begin();
}
BufferChain::iterator BufferChain::end()
{
return _chain.end();
}
size_t BufferChain::size()
{
return _chain.size();
}
size_t BufferChain::totalSize()
{
size_t total = 0;
for (std::list<std::string*>::iterator it = _chain.begin(); it != _chain.end(); *it++)
{
total += (*it)->size();
}
return total;
}
void BufferChain::flush()
{
std::string* tmp;
while (_chain.size() > 0)
{
tmp = getFirst();
delete tmp;
popFirst();
}
}
int BufferChain::writeBufferToFd(BufferChain& chain, FD fd)
{
int ret;
std::string* buff;
buff = chain.getFirst();
ret = write(fd, buff->c_str(), buff->size());
if (ret == -1)
throw IOError();
return ret;
}
int BufferChain::readToBuffer(BufferChain& chain, FD fd)
{
int ret;
ret = read(fd, g_read_large, BUFFER_SIZE_LARGE);
if (ret == -1)
throw IOError();
if (ret > 0)
{
std::string* n = new std::string(g_read_large, ret);
chain.pushBack(n);
}
return ret;
}
const char* BufferChain::IOError::what() const throw()
{
return "An input or output error has occurred";
}
#include <algorithm>
std::ostream& operator<<(std::ostream& out, BufferChain& chain)
{
BufferChain::iterator it = chain.begin();
out << "BufferChain: .size=" << chain.size() << std::endl;
while (it != chain.end())
{
std::string toprint;
if ((**it).size() > 1000)
std::string toprint = (**it).size() > 10 ? std::string(**it, 0, 7).append("...") : **it;
else
toprint = **it;
std::replace(toprint.begin(), toprint.end(), '\n', 'N');
std::replace(toprint.begin(), toprint.end(), '\r', 'R');
out << "|";
out << toprint;
out << "|" << "size: " << (**it).size() << " ";
it++;
}
out << std::endl;
return out;
}
|
#include "Lista.h"
template <typename T>
Lista<T>::Lista() {
prim = NULL;
ult = NULL;
}
template <typename T>
Lista<T>::Lista(const Lista<T>& l) : Lista() {
//Inicializa una lista vacía y luego utiliza operator= para no duplicar el código de la copia de una lista.
*this = l;
}
template <typename T>
Lista<T>::~Lista() {
Nodo* posActual = prim;
while (posActual != NULL) {
Nodo* siguiente = (*posActual).siguiente;
(*posActual).anterior = NULL;
(*posActual).siguiente = NULL;
delete posActual;
posActual = siguiente;
}
prim = NULL;
ult = NULL;
}
template <typename T>
Lista<T>& Lista<T>::operator=(const Lista<T>& aCopiar) {
Nodo* posActual = prim;
while (posActual != NULL) {
Nodo* siguiente = (*posActual).siguiente;
(*posActual).anterior = NULL;
(*posActual).siguiente = NULL;
delete posActual;
posActual = siguiente;
}
prim = NULL;
ult = NULL;
if(aCopiar.prim == NULL) {
prim = NULL;
ult = NULL;
} else {
Nodo* iterador = aCopiar.prim;
Nodo* actual = new Nodo((*iterador).valor, NULL, NULL);
prim = actual;
iterador = (*iterador).siguiente;
while (iterador != NULL) {
Nodo* nuevo = new Nodo((*iterador).valor, actual, NULL);
(*actual).siguiente = nuevo;
actual = nuevo;
iterador = (*iterador).siguiente;
}
ult = actual;
}
return *this;
}
template <typename T>
void Lista<T>::agregarAdelante(const T& elem) {
Nodo* nuevo = new Nodo(elem, NULL, NULL);
if (prim == NULL) {
prim = nuevo;
ult = nuevo;
} else {
Nodo* primPos = prim;
prim = nuevo;
(*nuevo).siguiente = primPos;
(*primPos).anterior = nuevo;
}
}
template <typename T>
void Lista<T>::agregarAtras(const T& elem) {
Nodo* nuevo = new Nodo(elem, NULL, NULL);
if (ult == NULL) {
prim = nuevo;
ult = nuevo;
} else {
Nodo* ultPos = ult;
ult = nuevo;
(*nuevo).anterior = ultPos;
(*ultPos).siguiente = nuevo;
}
}
template <typename T>
void Lista<T>::eliminar(Nat i) {
if (longitud() == 1) {
Nodo* unico = prim;
prim = NULL;
(*unico).anterior = NULL;
(*unico).siguiente = NULL;
delete unico;
}else if (i == 0) {
Nodo* primero = prim;
Nodo* siguiente = (*primero).siguiente;
prim = siguiente;
(*siguiente).anterior = NULL;
(*primero).siguiente = NULL;
delete primero;
} else if (i == longitud()-1) {
Nodo* ultimo = ult;
Nodo* anterior = (*ultimo).anterior;
ult = anterior;
(*anterior).siguiente = NULL;
(*ultimo).anterior = NULL;
delete ultimo;
} else {
int iterador = 0;
Nodo* posActual = prim;
Nodo* anterior = NULL;
Nodo* siguiente = (*posActual).siguiente;
while (iterador != i) {
anterior = posActual;
posActual = siguiente;
siguiente = (*siguiente).siguiente;
iterador++;
}
(*anterior).siguiente = siguiente;
(*siguiente).anterior = anterior;
(*posActual).siguiente = NULL;
(*posActual).anterior = NULL;
delete posActual;
}
}
template <typename T>
int Lista<T>::longitud() const {
int largo = 0;
Nodo* posActual = prim;
while (posActual != NULL) {
largo++;
posActual = (*posActual).siguiente;
}
return largo;
}
template <typename T>
const T& Lista<T>::iesimo(Nat i) const {
int iterador = 0;
Nodo* posActual = prim;
while (iterador != i) {
posActual = (*posActual).siguiente;
iterador++;
}
return (*posActual).valor;
}
template <typename T>
T& Lista<T>::iesimo(Nat i) {
int iterador = 0;
Nodo* posActual = prim;
while (iterador != i) {
posActual = (*posActual).siguiente;
iterador++;
}
return (*posActual).valor;
}
template <typename T>
void Lista<T>::mostrar(ostream& o) {
// Completar
}
|
#include "login.h"
#include "ui_login.h"
#include"QtSql"
#include"QFileInfo"
#include <QDialog>
#include"QMessageBox"
#include<QMessageBox>
#include"test.h"
#include"signup.h"
#include"QDebug"
#define Path_to_DB "C:/Users/nayan/Desktop/sql/project.sqlite"
login::login(QWidget *parent) :
QDialog(parent),
ui(new Ui::login)
{
ui->setupUi(this);
QPixmap pix("C:\\Users\\nayan\\Desktop\\candidat.png");
ui->label_5->setPixmap(pix);
QFileInfo checkFile(Path_to_DB);
if(checkFile.isFile())
{
if(connopen())
{
ui->label->setText("connected :)");
}
}
else
{
ui->label->setText("Disconnected :(");
}
}
login::~login()
{
delete ui;
qDebug()<<"Closing the connection to data base file";
mydb.close();
}
void login::on_pushButton_clicked()
{
QString username;
QString password;
username=ui->lineEdit->text();
password=ui->lineEdit_2->text();
if(username=="")
{
QMessageBox::critical(this,tr("Error "),tr("User name cant be empty"));
}
else if(password=="")
{
QMessageBox::critical(this,tr("Error "),tr("Password cant be empty"));
}
else
{
if(username=="test" && password=="test")
{
}
else
{
if(!connopen())
{
qDebug()<<"Failed to open";
return;
}
connopen();
QSqlQuery qry;
qry.prepare("select username,password from main where username=\'"+ username+ "\'and password=\'"+password+"\'");
if(qry.exec())
{
if(qry.next())
{
ui->label->setText("Valid user name and password :)");
QString msg ="username ="+qry.value(0).toString()+"\n"+
"password ="+qry.value(1).toString();
connclose();
hide();
test u;
u.setModal(true);
u.exec();
//QMessageBox::warning(this,"Login was successful",msg);
}else{
// ui->label->setText("Wrong user name password");
QMessageBox::warning(this,"login","Wrong user name password");
}
}
}
}
}
void login::on_pushButton_3_clicked()
{
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
}
void login::on_pushButton_2_clicked()
{
hide();
signup s;
s.setModal(true);
s.exec();
}
|
#include <iostream>
#include "variable.h"
Variable::Variable(std::string name)
{
this->name = name;
}
Variable::~Variable()
{
for (std::list<Term*>::iterator it = termList.begin(); it != termList.end(); it++)
{
delete *it;
}
}
void Variable::setRange(double rangeLow, double rangeHigh)
{
this->rangeLow = rangeLow;
this->rangeHigh = rangeHigh;
}
float Variable::getRangeLow()
{
return rangeLow;
}
float Variable::getRangeHigh()
{
return rangeHigh;
}
void Variable::addTerm(Term* term)
{
term->setVariableName(name);
termList.push_back(term);
}
std::string Variable::getName() const
{
return name;
}
Term* Variable::getTermToName(std::string name)
{
for (std::list<Term*>::iterator it = termList.begin(); it != termList.end(); it++)
{
if ((*it)->getName().compare(name) == 0)
{
return *it;
}
}
return NULL;
}
void Variable::createFuzzySets(std::ofstream& file)
{
for (std::list<Term*>::iterator it = termList.begin(); it != termList.end(); it++)
{
(*it)->createFuzzySet(file);
}
file << std::endl;
}
void Variable::debugPrint()
{
std::cout << "Name: " << name << " Range: " << rangeLow << " - " << rangeHigh << std::endl;
for (std::list<Term*>::iterator it = termList.begin(); it != termList.end(); it++)
{
(*it)->debugPrint();
}
}
|
// Created on: 1994-05-27
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_TransformStandard_HeaderFile
#define _IFSelect_TransformStandard_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_SequenceOfGeneralModifier.hxx>
#include <IFSelect_Transformer.hxx>
#include <Standard_Integer.hxx>
class IFSelect_Selection;
class Interface_CopyControl;
class IFSelect_Modifier;
class Interface_Graph;
class Interface_Protocol;
class Interface_CheckIterator;
class Interface_InterfaceModel;
class Interface_CopyTool;
class Standard_Transient;
class TCollection_AsciiString;
class IFSelect_TransformStandard;
DEFINE_STANDARD_HANDLE(IFSelect_TransformStandard, IFSelect_Transformer)
//! This class runs transformations made by Modifiers, as
//! the ModelCopier does when it produces files (the same set
//! of Modifiers can then be used, as to transform the starting
//! Model, as at file sending time).
//!
//! First, considering the resulting model, two options :
//! - modifications are made directly on the starting model
//! (OnTheSpot option), or
//! - data are copied by the standard service Copy, only the
//! remaining (not yet sent in a file) entities are copied
//! (StandardCopy option)
//!
//! If a Selection is set, it forces the list of Entities on which
//! the Modifiers are applied. Else, each Modifier is considered
//! its Selection. By default, it is for the whole Model
//!
//! Then, the Modifiers are sequentially applied
//! If at least one Modifier "May Change Graph", or if the option
//! StandardCopy is selected, the graph will be recomputed
//! (by the WorkSession, see method RunTransformer)
//!
//! Remark that a TransformStandard with option StandardCopy
//! and no Modifier at all has the effect of computing the
//! remaining data (those not yet sent in any output file).
//! Moreover, the Protocol is not changed
class IFSelect_TransformStandard : public IFSelect_Transformer
{
public:
//! Creates a TransformStandard, option StandardCopy, no Modifier
Standard_EXPORT IFSelect_TransformStandard();
//! Sets the Copy option to a new value :
//! - True for StandardCopy - False for OnTheSpot
Standard_EXPORT void SetCopyOption (const Standard_Boolean option);
//! Returns the Copy option
Standard_EXPORT Standard_Boolean CopyOption() const;
//! Sets a Selection (or unsets if Null)
//! This Selection then defines the list of entities on which the
//! Modifiers will be applied
//! If it is set, it has priority on Selections of Modifiers
//! Else, for each Modifier its Selection is evaluated
//! By default, all the Model is taken
Standard_EXPORT void SetSelection (const Handle(IFSelect_Selection)& sel);
//! Returns the Selection, Null by default
Standard_EXPORT Handle(IFSelect_Selection) Selection() const;
//! Returns the count of recorded Modifiers
Standard_EXPORT Standard_Integer NbModifiers() const;
//! Returns a Modifier given its rank in the list
Standard_EXPORT Handle(IFSelect_Modifier) Modifier (const Standard_Integer num) const;
//! Returns the rank of a Modifier in the list, 0 if unknown
Standard_EXPORT Standard_Integer ModifierRank (const Handle(IFSelect_Modifier)& modif) const;
//! Adds a Modifier to the list :
//! - <atnum> = 0 (default) : at the end of the list
//! - <atnum> > 0 : at rank <atnum>
//! Returns True if done, False if <atnum> is out of range
Standard_EXPORT Standard_Boolean AddModifier (const Handle(IFSelect_Modifier)& modif, const Standard_Integer atnum = 0);
//! Removes a Modifier from the list
//! Returns True if done, False if <modif> not in the list
Standard_EXPORT Standard_Boolean RemoveModifier (const Handle(IFSelect_Modifier)& modif);
//! Removes a Modifier from the list, given its rank
//! Returns True if done, False if <num> is out of range
Standard_EXPORT Standard_Boolean RemoveModifier (const Standard_Integer num);
//! Performs the Standard Transformation, by calling Copy then
//! ApplyModifiers (which can return an error status)
Standard_EXPORT Standard_Boolean Perform (const Interface_Graph& G, const Handle(Interface_Protocol)& protocol, Interface_CheckIterator& checks, Handle(Interface_InterfaceModel)& newmod) Standard_OVERRIDE;
//! This the first operation. It calls StandardCopy or OnTheSpot
//! according the option
Standard_EXPORT void Copy (const Interface_Graph& G, Interface_CopyTool& TC, Handle(Interface_InterfaceModel)& newmod) const;
//! This is the standard action of Copy : its takes into account
//! only the remaining entities (noted by Graph Status positive)
//! and their proper dependances of course. Produces a new model.
Standard_EXPORT void StandardCopy (const Interface_Graph& G, Interface_CopyTool& TC, Handle(Interface_InterfaceModel)& newmod) const;
//! This is the OnTheSpot action : each entity is bound with ...
//! itself. The produced model is the same as the starting one.
Standard_EXPORT void OnTheSpot (const Interface_Graph& G, Interface_CopyTool& TC, Handle(Interface_InterfaceModel)& newmod) const;
//! Applies the modifiers sequentially.
//! For each one, prepares required data (if a Selection is associated as a filter).
//! For the option OnTheSpot, it determines if the graph may be
//! changed and updates <newmod> if required
//! If a Modifier causes an error (check "HasFailed"),
//! ApplyModifier stops : the following Modifiers are ignored
Standard_EXPORT Standard_Boolean ApplyModifiers (const Interface_Graph& G, const Handle(Interface_Protocol)& protocol, Interface_CopyTool& TC, Interface_CheckIterator& checks, Handle(Interface_InterfaceModel)& newmod) const;
//! This methods allows to know what happened to a starting
//! entity after the last Perform. It reads result from the map
//! which was filled by Perform.
Standard_EXPORT Standard_Boolean Updated (const Handle(Standard_Transient)& entfrom, Handle(Standard_Transient)& entto) const Standard_OVERRIDE;
//! Returns a text which defines the way a Transformer works :
//! "On the spot edition" or "Standard Copy" followed by
//! "<nn> Modifiers"
Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_TransformStandard,IFSelect_Transformer)
private:
Standard_Boolean thecopy;
Handle(IFSelect_Selection) thesel;
IFSelect_SequenceOfGeneralModifier themodifs;
Handle(Interface_CopyControl) themap;
};
#endif // _IFSelect_TransformStandard_HeaderFile
|
#include <iostream>
#include <vector>
#include <set>
#include <queue>
int n, k;
std::vector<int> Cube;
std::vector<int> Switch[9];
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> k;
Cube.resize(n);
for(int i = 0; i < n; i++)
{
std::cin >> Cube[i];
}
for(int i = 1; i <= k; i++)
{
int c;
std::cin >> c;
Switch[i].resize(c);
for(int j = 0; j < c; j++)
{
std::cin >> Switch[i][j];
}
}
std::queue<std::pair<int, std::vector<int>>> q;
std::set<std::vector<int>> visited;
q.push({0, Cube});
visited.insert(Cube);
while(!q.empty())
{
auto [p, now] = q.front();
q.pop();
bool FLAG = true;
for(int i = 1; i < n; i++)
{
if(now[i] != now[0])
{
FLAG = false;
break;
}
}
if(FLAG)
{
std::cout << p << '\n';
return 0;
}
for(int i = 1; i <= k; i++)
{
std::vector<int> next = now;
for(auto pos : Switch[i])
{
next[pos - 1] = (next[pos - 1] + i) % 5;
}
if(visited.find(next) == visited.end())
{
q.push({p + 1, next});
visited.insert(next);
}
}
}
std::cout << "-1\n";
return 0;
}
|
#include<iostream>
using namespace std;
int m[2][12]={31,28,31,30,31,30,31,31,30,31,30,31,31,29,31,30,31,30,31,31,30,31,30,31};
int y[2]={365,366};
int year,mo,d;
int isleap()
{
if((year%4==0&&year%100!=0)||(year%400==0))
return 1;
else return 0;
}
void increment(long long N)
{
int temp;
while(N>0)
{
int t=isleap();
if(N>=y[t])
{
if(d!=1||mo!=0)
{
if(d!=1)
{
temp=(m[t][mo]-d)+1;
N-=temp;
d=1;mo++;if(mo>11){mo=0;year++;}
}
if(mo!=0)
{
for(int i=mo;i<12;i++)
N-=m[t][i];
mo=0;year++;
}
}
else {
N-=y[t];
year++;
}
}
else
{
if(N>=(m[t][mo]-d+1))
{
N-=(m[t][mo]-d+1);
d=1;
mo++;
if(mo>11){mo=0;year++;}
}
else
{
d+=N;
N=0;
}
}
}
}
int main()
{
long long N;
while(1)
{
cin>>N>>d>>mo>>year;
if(N==0)break;
mo--;
increment(N);
++mo;
cout<<d<<" "<<mo<<" "<<year<<endl;
}
return 0;
}
|
#include "TextureManager.h"
#include "FreeImage.h"
#include "EngineUtil.h"
#include "Image.h"
#include "Sampler.h"
TextureManager::TextureManager()
{
namegen = new NameGenerator("texture");
CreateTextureFromImage("white_texture.jpg");
}
Texture* TextureManager::CreateTextureFromImage(string filename, string texname)
{
Image* image = ImageManager::getInstance().CreateImageFromFile(filename);
if (image == NULL) return NULL;
Texture* texture = GlobalResourceManager::getInstance().m_TextureFactory->create();
texture->image = image;
texture->width = image->width;
texture->height = image->height;
if (texname == "")
texture->name = image->name;
else
texture->name = texname;
texture->setFormatFromImage(image);
add(texture);
return texture;
}
void TextureManager::LoadTexturePreset(string filename)
{
string file_content = ReadFiletoString(filename);
m_presets_doc.Parse(file_content.c_str());
auto& ps = m_presets_doc["Texture_Presets"];
rapidjson::Value* pv;
for (auto it = ps.MemberBegin(); it != ps.MemberEnd(); it++){
auto& v = it->value;
string name=v["preset_name"].GetString();
presets[name] = v;
}
}
Texture* TextureManager::CreateTextureFromPreset(string preset_name)
{
auto it = presets.find(preset_name);
if (it == presets.end())
return NULL;
;
Texture* tex = GlobalResourceManager::getInstance().m_TextureFactory->create();
auto& v = it->second;
string type=v["type"].GetString();
if (type == "2D") tex->texture_type = Texture::Texture_2D;
if (type == "Cube") tex->texture_type = Texture::Texture_Cube;
if (type == "3D") tex->texture_type = Texture::Texture_3D;
type = v["format"].GetString();
if (type == "RGBA") tex->texture_internal_format=Texture::RGBA8;
if (type == "Depth24") tex->texture_internal_format = Texture::DEPTH24;
if (type == "RGBA32F") tex->texture_internal_format = Texture::RGBA32F;
if (type == "RGBA16UI") tex->texture_internal_format = Texture::RGBA16UI;
if (type == "RG32UI") tex->texture_internal_format = Texture::RG32UI;
{
string w = "sampler";
if (v.HasMember(w.c_str())){
type = v[w.c_str()].GetString();
if (type == "ClampPoint") tex->texture_sampler = SamplerManager::getInstance().get("ClampPoint");
if (type == "RepeatPoint") tex->texture_sampler = SamplerManager::getInstance().get("RepeatPoint");
if (type == "RepeatLinear") tex->texture_sampler = SamplerManager::getInstance().get("RepeatLinear");
if (type == "ClampLinear") tex->texture_sampler = SamplerManager::getInstance().get("ClampLinear");
}
}
string w = "mipmap_mode";
if (v.HasMember(w.c_str())){
type = v[w.c_str()].GetString();
if (type == "auto") tex->mipmap_mode = Texture::TextureMipmap_Auto;
if (type == "none") tex->mipmap_mode = Texture::TextureMipmap_None;
if (type == "manual") tex->mipmap_mode = Texture::TextureMipmap_Manual;
}
return tex;
}
Texture* TextureManager::CreateTextureCubeMap(vector<string> paths, string texname /*= ""*/)
{
auto images = ImageManager::getInstance().CreateImageListFromFiles(paths);
if (images.size()!=6) return NULL;
Texture* texture = GlobalResourceManager::getInstance().m_TextureFactory->create();
texture->texture_type = Texture::Texture_Cube;
texture->image_cube = images;
auto first_image = images[0];
texture->width = first_image->width;
texture->height = first_image->height;
if (texname == "")
texture->name = first_image->name;
else
texture->name = texname;
texture->setFormatFromImage(first_image);
add(texture);
return texture;
}
Texture* TextureManager::CreateTextureCubeMapEmpty(string texname)
{
Texture* texture = GlobalResourceManager::getInstance().m_TextureFactory->create();
texture->texture_type = Texture::Texture_Cube;
texture->name = texname;
add(texture);
return texture;
}
|
#ifndef __PILLAR_H__
#define __PILLAR_H__
#include "cocos2d.h"
// Base class for all pillars
class Pillar : public cocos2d::Node
{
public:
// Initialize instance (sprites)
virtual bool init() override;
// Spawns pillar randomly
void spawn();
protected:
cocos2d::Sprite* topPillar_ = nullptr;
cocos2d::Sprite* botPillar_ = nullptr;
};
#endif // __PILLAR_H__
|
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;
CCLabelTTF* pGreeButtonText;
CCSprite* pSprite;
CCSprite* pIcon = NULL;
int gThumbFlag = 0;
CCImage *pThumb = NULL;
int gFriendFlag = 0;
CCArray *pFriends = NULL;
int gNumOfFriend = 0;
#define FRIEND_X_OFFSET (100)
#define FRIEND_Y_OFFSET (100)
void HelloWorld::showResult(std::string* str1, std::string* str2){
CCMessageBox(str1->c_str(), str2->c_str());
}
void HelloWorld::authorizeAuthorized(){
CCLog("++++++ %s", __func__);
CCGreeUser *user = CCGreePlatform::getLocalUser();
std::string str1 = "Callback";
std::string str2 = "authorize Success";
showResult(&str2, &str1);
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCMoveTo *action = CCMoveTo::actionWithDuration(0.5f, ccp(0, size.height - 100));
pSprite->runAction(action);
CCMenu* pMenu = CCMenu::create(NULL, NULL);
// User Information
CCSprite *pSUser = CCSprite::create("friends.png");
pSUser->setPosition( ccp(size.width/2 - 100, size.height - 60) );
this->addChild(pSUser, 0);
CCLabelTTF *textUser = CCLabelTTF::create("Get User Info", "Thonburi", 20);
CCMenuItemLabel* pUser = CCMenuItemLabel::create(textUser, this, menu_selector(HelloWorld::menuUserCallback));
pUser->setPosition(ccp(size.width/2, size.height - 60));
// Friend Infomation
CCSprite *pSFri = CCSprite::create("friends.png");
pSFri->setPosition( ccp(size.width/2 - 100, size.height - 110) );
this->addChild(pSFri, 0);
CCLabelTTF *textFri = CCLabelTTF::create("Get Friend Info", "Thonburi", 20);
CCMenuItemLabel* pFri = CCMenuItemLabel::create(textFri, this, menu_selector(HelloWorld::menuFriendCallback));
pFri->setPosition(ccp(size.width/2, size.height - 110));
// Payment Infomation
CCSprite *pSPay = CCSprite::create("payment.png");
pSPay->setPosition( ccp(size.width/2 - 100, size.height - 160) );
this->addChild(pSPay, 0);
CCLabelTTF *textPay = CCLabelTTF::create("Request Payment", "Thonburi", 20);
CCMenuItemLabel* pPay = CCMenuItemLabel::create(textPay, this, menu_selector(HelloWorld::menuPaymentCallback));
pPay->setPosition(ccp(size.width/2, size.height - 160));
//Dialog
CCLabelTTF *textShare = CCLabelTTF::create("Share Dialog", "Thonburi", 20);
CCMenuItemLabel* pShare = CCMenuItemLabel::create(textShare, this, menu_selector(HelloWorld::menuShareCallback));
pShare->setPosition(ccp(size.width/2, size.height - 190));
CCLabelTTF *textInvite = CCLabelTTF::create("Invite Dialog", "Thonburi", 20);
CCMenuItemLabel* pInvite = CCMenuItemLabel::create(textInvite, this, menu_selector(HelloWorld::menuInviteCallback));
pInvite->setPosition(ccp(size.width/2, size.height - 220));
CCLabelTTF *textLogout = CCLabelTTF::create("Logout User", "Thonburi", 20);
CCMenuItemLabel* pLogout = CCMenuItemLabel::create(textLogout, this, menu_selector(HelloWorld::menuLogoutCallback));
pLogout->setPosition(ccp(size.width/2, 50));
pMenu->setPosition(CCPointZero);
pMenu->addChild(pUser, 1000);
pMenu->addChild(pPay, 1001);
pMenu->addChild(pFri, 1002);
pMenu->addChild(pShare, 1003);
pMenu->addChild(pInvite, 1004);
//pMenu->addChild(pAch, 1003);
//pMenu->addChild(pLea, 1004);
pMenu->addChild(pLogout, 1010);
this->addChild(pMenu, 1);
//authFlag = 1;
}
// User
void HelloWorld::loadThumbnailSuccess(CCGreeUser* user, CCImage *img){
img->retain();
CCLog("++++++ %s", __func__);
std::string str1 = "Callback";
std::string str2 = "loadThumbnail Success";
showResult(&str2, &str1);
pThumb = img;
gThumbFlag = 1;
}
void HelloWorld::loadFriendsSuccess(CCGreeUser *user, int index, int count, CCArray *userArray){
CCLog("++++++ %s", __func__);
std::string str1 = "Callback";
std::string str2 = "loadFriends Success";
showResult(&str2, &str1);
gFriendFlag = 1;
pFriends = userArray;
CCObject *it;
CCARRAY_FOREACH(userArray, it){
CCGreeUser *user = dynamic_cast<CCGreeUser *>(it);
dumpUserInfo(user);
//CCLog(" name %s", user->getNickname()->getCString());
}
gNumOfFriend = count;
}
//Payment
void HelloWorld::paymentRequestSuccess(CCGreePayment *payment, int responseCode, CCString *paymentId){
CCLog("++++++ %s", __func__);
std::string str1 = "Callback";
std::string str2 = "paymentRequest Success : ";
str2.append(paymentId->getCString());
showResult(&str2, &str1);
}
void HelloWorld::paymentRequestCancel(CCGreePayment *payment, int responseCode, CCString* paymentId){
CCLog("++++++ %s", __func__);
std::string str1 = "Callback";
std::string str2 = "paymentRequest Cancel : ";
str2.append(paymentId->getCString());
showResult(&str2, &str1);
}
void HelloWorld::paymentRequestFailure(CCGreePayment *payment, int responsCode, CCString *paymentID, CCString *response){
CCLog("++++++ %s", __func__);
std::string str1 = "Callback";
std::string str2 = "paymentRequest Failure : ";
str2.append(response->getCString());
showResult(&str2, &str1);
}
void HelloWorld::shareDialogOpened(CCGreeShareDialog *dialog){
std::string str1 = "Callback";
std::string str2 = "ShareDialog Opened";
showResult(&str2, &str1);
}
void HelloWorld::shareDialogCompleted(CCGreeShareDialog *dialog, CCArray *userArray){
std::string str1 = "Callback";
std::string str2 = "ShareDialog Completed";
showResult(&str2, &str1);
}
void HelloWorld::shareDialogClosed(CCGreeShareDialog *dialog){
std::string str1 = "Callback";
std::string str2 = "ShareDialog Closed";
showResult(&str2, &str1);
}
void HelloWorld::inviteDialogOpened(CCGreeInviteDialog *dialog){
std::string str1 = "Callback";
std::string str2 = "InviteDialog Opened";
showResult(&str2, &str1);
}
void HelloWorld::inviteDialogCompleted(CCGreeInviteDialog *dialog, CCArray *userArray){
std::string str1 = "Callback";
std::string str2 = "InviteDialog Completed";
showResult(&str2, &str1);
}
void HelloWorld::inviteDialogClosed(CCGreeInviteDialog *dialog){
std::string str1 = "Callback";
std::string str2 = "InviteDialog Closed";
showResult(&str2, &str1);
}
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback) );
pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition( CCPointZero );
this->addChild(pMenu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34);
// ask director the window size
CCSize size = CCDirector::sharedDirector()->getWinSize();
// position the label on the center of the screen
pLabel->setPosition( ccp(size.width / 2, size.height - 20) );
// add the label as a child to this layer
this->addChild(pLabel, 1);
// add "HelloWorld" splash screen"
pSprite = CCSprite::create("HelloWorld.png");
// position the sprite on the center of the screen
pSprite->setPosition( ccp(size.width/2, size.height/2) );
// add the sprite as a child to this layer
this->addChild(pSprite, 0);
// GreeButton
pGreeButtonText = CCLabelTTF::create("Log in", "Thonburi", 34);
pGreeButtonText->setPosition(ccp(size.width - 60, size.height - 40));
this->addChild(pGreeButtonText, 1);
CCMenuItemImage *pGree = CCMenuItemImage::create("gree.png", "gree.png", this, menu_selector(HelloWorld::menuGreeButtonCallback));
pGree->setPosition(ccp(size.width - 60, size.height - 80));
CCMenu* pGreeMenu = CCMenu::create(pGree, NULL);
this->addChild(pGreeMenu, 1);
pGreeMenu->setPosition(CCPointZero);
pGree->setScaleY(2.0);
pGree->setScaleX(2.0);
// Set Scheduled Func
this->schedule(schedule_selector(HelloWorld::Func), 1.0);
return true;
}
void HelloWorld::dumpUserInfo(CCGreeUser *user){
CCString *nickName = user->getNickname();
CCString *dispName = user->getDisplayName();
CCString *id = user->getId();
CCString *region = user->getRegion();
CCString *subRegion = user->getSubregion();
CCString *lang = user->getLanguage();
CCString *timeZone = user->getTimezone();
CCString *me = user->getAboutMe();
CCString *birthDay = user->getBirthday();
//CCString *url = pUser->getProfileUrl();
//CCLog("++++++ ProfileUrl %s", url->getCString());
CCString *gender = user->getGender();
CCString *age = user->getAge();
CCString *blood = user->getBloodType();
bool hasApp = user->getHasApp();
CCString *hash = user->getUserHash();
CCString *type = user->getUserType();
int grade = user->getUserGrade();
CCLog("++++++ NickName %s", nickName->getCString());
CCLog("++++++ DisplayName %s", dispName->getCString());
CCLog("++++++ Id %s", id->getCString());
CCLog("++++++ Region %s", region->getCString());
CCLog("++++++ Subregion %s", subRegion->getCString());
CCLog("++++++ Language %s", lang->getCString());
CCLog("++++++ Timezone %s", timeZone->getCString());
CCLog("++++++ me %s", me->getCString());
CCLog("++++++ BirthDay %s", birthDay->getCString());
CCLog("++++++ Gender %s", gender->getCString());
CCLog("++++++ Age %s", age->getCString());
CCLog("++++++ BloodType %s", blood->getCString());
CCLog("++++++ HasApp %d", hasApp);
CCLog("++++++ UserHash %s", hash->getCString());
CCLog("++++++ UserType %s", type->getCString());
CCLog("++++++ grade %d", grade);
}
void HelloWorld::Func(float dt){
//CCLog("++++++ %s", __func__);
CCSize size = CCDirector::sharedDirector()->getWinSize();
// User Information
if(gThumbFlag == 1){
CCGreeUser *pUser = CCGreePlatform::getLocalUser();
dumpUserInfo(pUser);
if(pThumb != NULL){
CCTexture2D *tex = CCTextureCache::sharedTextureCache()->addUIImage(pThumb, "key_name");
pIcon = CCSprite::spriteWithTexture(tex);
pIcon->setPosition(ccp(100, size.height - 100));
this->addChild(pIcon, 0);
}
gThumbFlag = 0;
}
// Friend List
if(gFriendFlag == 1){
CCLabelTTF *lname[gNumOfFriend];
CCLabelTTF *lbir[gNumOfFriend];
CCLabelTTF *lage[gNumOfFriend];
CCObject *it;
int i = 0;
CCLabelTTF *fList = CCLabelTTF::create("Friends List", "Thonburi", 40);
fList->setPosition(ccp(FRIEND_X_OFFSET, size.height - FRIEND_Y_OFFSET));
this->addChild(fList, 1);
CCARRAY_FOREACH(pFriends, it){
CCGreeUser *user = dynamic_cast<CCGreeUser *>(it);
dumpUserInfo(user);
lname[i] = CCLabelTTF::create(user->getNickname()->getCString(), "Thonburi", 30);
lbir[i] = CCLabelTTF::create(user->getBirthday()->getCString(), "Thonburi", 30);
lage[i] = CCLabelTTF::create(user->getAge()->getCString(), "Thonburi", 30);
lname[i]->setPosition(ccp(FRIEND_X_OFFSET, size.height - FRIEND_Y_OFFSET - 50 - i*100));
lbir[i]->setPosition(ccp(FRIEND_X_OFFSET, size.height - FRIEND_Y_OFFSET - 50 - 30 - i*100));
lage[i]->setPosition(ccp(FRIEND_X_OFFSET, size.height - FRIEND_Y_OFFSET - 50 - 60 - i*100));
this->addChild(lname[i], 1);
this->addChild(lbir[i], 1);
this->addChild(lage[i], 1);
i++;
}
gFriendFlag = 0;
}
}
void HelloWorld::menuGreeButtonCallback(CCObject *pSender){
if(CCGreeAuthorizer::isAuthorized() != true){
CCGreePlatform::setAuthorizerDelegate(this);
CCGreePlatform::setUserDelegate(this);
CCGreePlatform::setPaymentDelegate(this);
CCGreePlatform::setInviteDialogDelegate(this);
CCGreePlatform::setShareDialogDelegate(this);
CCGreeAuthorizer::authorize();
}
}
void HelloWorld::menuUserCallback(CCObject *pSender){
// Load Thumbnail
//CCGreeUser::loadUserWithId("1000020828");
CCGreeUser *user = CCGreePlatform::getLocalUser();
//user->load
user->loadThumbnail(UserThumbnailSizeHuge);
//user->loadIgnoredUserIds(0, 10);
}
void HelloWorld::menuFriendCallback(CCObject *pSender){
// Load Friend list
CCGreeUser *user = CCGreePlatform::getLocalUser();
user->loadFriends(1, 10);
}
void HelloWorld::menuPaymentCallback(CCObject *pSender){
// Reqest Payment
CCGreePaymentItem *item1 = CCGreePaymentItem::create("01234", "TestItem1", 100, 2);
CCGreePaymentItem *item2 = CCGreePaymentItem::create("56789", "TestItem2", 200, 30);
std::string str1 = "new CCGreePaymentItem 1";
std::string str2 = "ItemId : ";
str2.append(item1->getItemId()->getCString());
str2.append(" ItemName : ");
str2.append(item1->getItemName()->getCString());
str2.append(" UnitPrice : ");
char text[48];
sprintf(text, "%f", item1->getUnitPrice());
str2.append(text);
str2.append(" Quantity : ");
sprintf(text, "%d", item1->getQuantity());
str2.append(text);
str2.append(" ImageUrl : ");
str2.append(item1->getImageUrl()->getCString());
str2.append(" Desc : ");
str2.append(item1->getDescription()->getCString());
showResult(&str2, &str1);
CCArray *itemArray = new CCArray();
itemArray->addObject(item1);
itemArray->addObject(item2);
//CCGreePayment *pay = new CCGreePayment("Payment Test", itemArray);
CCGreePayment *pay = CCGreePayment::create("Payment Test", itemArray);
pay->request();
}
void HelloWorld::menuShareCallback(CCObject *pPay){
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCRenderTexture *tex = CCRenderTexture::renderTextureWithWidthAndHeight(size.width, size.height);
tex->setPosition(ccp(size.width/2, size.height/2));
tex->begin();
this->visit();
tex->end();
CCImage *img = tex->newCCImage();
CCGreeShareDialog *dialog = CCGreeShareDialog::create();
CCDictionary *dict = CCDictionary::create();
dict->setObject(new CCString("This is test share"), GD_SHARE_DIALOG_PARAM_KEY_MESSAGE);
dict->setObject(img, GD_SHARE_DIALOG_PARAM_KEY_IMG);
dialog->setParams(dict);
dialog->show();
}
void HelloWorld::menuInviteCallback(CCObject *pPay){
//InviteDialog
CCGreeInviteDialog *dialog = CCGreeInviteDialog::create();
CCDictionary *dict = CCDictionary::create();
CCArray *array = new CCArray();
array->addObject(new CCString("1000038120"));
array->addObject(new CCString("1000038121"));
dict->setObject(array, GD_INVITE_DIALOG_PARAM_KEY_TOUSERID);
dict->setObject(new CCString("TestInviteBody"), GD_INVITE_DIALOG_PARAM_KEY_BODY);
dialog->setParams(dict);
dialog->show();
}
void HelloWorld::menuLogoutCallback(CCObject *pSender){
CCGreeAuthorizer::logout();
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
|
#pragma once
#include "main.h"
class CD3DHook {
public:
IDirect3DDevice9 *getdevice();
private:
IDirect3DDevice9 *device;
};
|
#include <Polycode.h>
#include <PolycodeView.h>
int
main()
{
using namespace Polycode;
auto view = new PolycodeView("foo");
auto core = new POLYCODE_CORE(view, 480, 270, false, true, 0, 0, 90, 0, true);
auto cs = CoreServices::getInstance();
cs->getRenderer()->setClearColor(0, 0, 0, 0);
auto rm = cs->getResourceManager();
rm->addDirResource("resources");
auto scene = new Scene(Scene::SCENE_2D);
scene->getActiveCamera()->setOrthoSize(core->getScreenWidth(), core->getScreenHeight());
auto entity = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, core->getScreenWidth(), core->getScreenHeight());
entity->setMaterialByName("Ripple");
scene->addChild(entity);
auto binding = entity->getLocalShaderOptions();
auto center = binding->addParam(ProgramParam::PARAM_VECTOR2, "center");
auto radius = binding->addParam(ProgramParam::PARAM_NUMBER, "radius");
auto width = binding->addParam(ProgramParam::PARAM_NUMBER, "width");
center->setVector2(Vector2(.5*core->getScreenWidth(), .5*core->getScreenHeight()));
width->setNumber(30);
Number t = 0;
do {
t += core->getElapsed();
radius->setNumber(fmod(200.*t, 400.));
} while (core->updateAndRender());
}
|
#include "midi.h"
static void anonCallback(double deltatime, std::vector<unsigned char> *message, void *userData = nullptr) {
((MIDIInFunc *) userData)->callback(deltatime, message);
}
QMap<quint8,QString> MIDIEvent::nibToType = {{0x9,"Note On"}, {0x8,"Note Off"}, {0xB,"Ctrl Change"}, {0xE,"Pitch Wheel"}};
QMap<QString,quint8> MIDIEvent::typeToNib = {{"Note On", 0x9}, {"Note Off",0x8}, {"Ctrl Change",0xB}, {"Pitch Wheel",0xE}};
Q_INVOKABLE MIDIInFunc::MIDIInFunc(QObject *parent): QObject(parent), gates(MIDIPOLY), vocts(MIDIPOLY), vels(MIDIPOLY),
keyed(MIDIPOLY), keys(MIDIPOLY), keyPos(0) {
lastEv = QVariant();
for (int i = 0; i < MIDIPOLY; i++) {
gates[i] = new MutableFunc();
vocts[i] = new MutableFunc();
vels[i] = new MutableFunc();
keyed[i] = keys[i] = 0;
}
}
Q_INVOKABLE MIDIInFunc::~MIDIInFunc() {
for (int i = 0; i < MIDIPOLY; i++) {
delete gates[i];
delete vocts[i];
delete vels[i];
}
}
QStringList MIDIInFunc::listDevices() {
unsigned int nPorts = midiin.getPortCount();
QStringList devList;
for (unsigned int i = 0; i < nPorts; i++) {
try { devList << QString::fromStdString(midiin.getPortName(i)); }
catch ( RtMidiError &error ) {
devList << QString::fromStdString(error.getMessage());
qDebug() << "Error querying MIDI ports:" << QString::fromStdString(error.getMessage());
}
}
return devList;
}
void MIDIInFunc::open(unsigned int portNum) {
unsigned int nPorts = midiin.getPortCount();
if (portNum >= nPorts) return;
midiin.openPort( portNum );
midiin.setCallback( &anonCallback, this );
midiin.ignoreTypes( false, false, false );
}
Q_INVOKABLE QVariant MIDIInFunc::lastEvent() {
return lastEv;
}
void MIDIInFunc::callback(double, std::vector<unsigned char> *message) {
MIDIEvent ev(message->data(), (unsigned long) message->size());
if (!chanFilter.contains(ev.channel)) return;
if (!typeFilter.contains(ev.type)) return;
if (!keyFilter.contains(ev.key)) return;
lastEv = ev.asVariant();
int pos;
if (ev.type == 0x9) {
for (pos = 0; pos < MIDIPOLY; pos++)
if (gates[pos]->val < 3)
break;
if (pos == MIDIPOLY) {
int minkeyed = 99999999;
int minpos = -1;
for (pos = 0; pos < MIDIPOLY; pos++)
if (keyed[pos] < minkeyed) {
minkeyed = keyed[pos];
minpos = pos;
}
pos = minpos;
}
vocts[pos]->val = ((double)ev.key - 53.0)/12.0;
vels[pos]->val = ev.val / 127.0 * 10;
gates[pos]->val = 10;
keyed[pos] = ++keyPos;
keys[pos] = ev.key;
} else if (ev.type == 0x8) {
for (pos = 0; pos < MIDIPOLY; pos++)
if (keys[pos] == ev.key && gates[pos]->val > 3)
break;
if (pos == MIDIPOLY)
qDebug() << "shouldnt be here";
else
gates[pos]->val = 0;
} else if (ev.type == 0xB) {
cv.val = ev.val / 127.0 * 20 - 10;
} else if (ev.type == 0xE) {
wheel.val = (((ev.key & 0x3f) << 8) & (ev.val)) / 16383.0 * 20 - 10;
}
}
Q_INVOKABLE void MIDIInFunc::setJSCallback(QJSValue cb) {
if (cb.isCallable()) jsCallback = cb;
}
Q_INVOKABLE void MIDIInFunc::setChanFilter(QVariantList chans) {
chanFilter.clear();
for (QVariant chan : chans)
chanFilter.insert(chan.toInt()-1);
}
Q_INVOKABLE void MIDIInFunc::setTypeFilter(QStringList types) {
typeFilter.clear();
for(QString type : types) {
if (MIDIEvent::typeToNib.contains(type))
typeFilter.insert(MIDIEvent::typeToNib[type]);
}
}
Q_INVOKABLE void MIDIInFunc::setKeyFilter(QVariantList keys) {
keyFilter.clear();
for(QVariant key : keys)
keyFilter.insert(key.toInt());
}
|
// C++ includes
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
// C includes
#include <cstdlib>
#include <cstdio>
#include <cstring>
// OS-specific
#include <readline/readline.h>
#include <readline/history.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "builtin_registry.h"
#include "command.h"
#include "job_control.h"
#include "sample_module.h"
#include "shell.h"
#include "util.h"
namespace microshell {
namespace core {
using namespace std;
using namespace microshell::modules;
const int SHELL_FATAL = -1;
// Singleton initialization.
Shell* Shell::instance = nullptr;
void handle_sigint(int signo) {
// TODO(andrei) This will be invalid for a brief moment between when this
// signal handler is set up and when the shell initialization finishes.
Shell *shell = Shell::get();
if(SIGINT != signo) {
// TODO(andrei) Signal2name.
shell->fatal("Signal mismatch. Expecting SIGINT, got " + to_string(signo));
}
if(shell->get_waiting_for_child()) {
shell->info("C-c while child was running.");
}
else {
shell->info("C-c while NO child was running. Terminating shell.");
// TODO(andrei) Ensure that we synchronize properly.
shell->exit();
}
}
void handle_sigtstp(int signo) {
Shell *shell = Shell::get();
if(SIGTSTP != signo) {
shell->fatal(
"Signal mismatch. Expecting SIGTSTP, got " +
string(strsignal(signo)) +
"."
);
}
if(shell->get_waiting_for_child()) {
shell->info("Suspending foreground job. Use `fg' to continue it in the "
"foreground, or `bg' to continue it in the background.");
}
// Otherwise, we just ignore the signal.
}
Shell::Shell(const vector<string> &) :
exit_requested(false),
home_directory(util::get_current_home()),
standard_output(cout),
error_output(cerr),
name("ush"),
username(util::get_current_user()),
waiting_for_child(false) {
this->load_default_modules();
cout << "Welcome to microshell, " << username << "!" << endl;
if(!util::getcwd(&this->working_directory)) {
eout("Failed to get the current working directory.");
// TODO(andrei) Display what `~' resolves to between parentheses. If it
// can't be resolved, use `/' instead.
eout("Defaulting to `~'.");
// TODO(andrei) Use setter and actually resolve $HOME.
this->working_directory = "~";
}
string envpath = getenv("PATH");
this->path = util::split(envpath, ':');
this->info("Setting up signal handlers...");
if(SIG_ERR == signal(SIGINT, handle_sigint)) {
this->fatal("Could not set up SIGINT handler (C-c terminate support).");
}
if(SIG_ERR == signal(SIGTSTP, handle_sigtstp)) {
this->fatal("Could not set up SIGTSTP handler (C-z suspend support).");
}
}
int Shell::interactive() {
while (!exit_requested) {
string command_text = read_command();
if(0 == command_text.length()) {
cout << endl;
continue;
}
shared_ptr<Command> command;
string error;
if(parse_command(command_text, command, &error)) {
interpret_command(*command);
}
else {
eout(error);
}
}
return 0;
}
string Shell::expand(const string& param) const {
// TODO(andrei) Variable expansions happen first.
if(0 == param.find("~")) {
string rest = param.substr(1);
return util::merge_paths(home_directory, rest);
}
return param;
}
string Shell::resolve_path(const string& path) const {
if(util::is_absolute_path(path)) {
return path;
}
// The VFS can handle the `..' sequences, but we want to handle them
// ourselves in order to display the path in a clearer way.
return util::merge_paths(working_directory, path);
}
string& Shell::get_working_directory() {
return working_directory;
}
void Shell::set_working_directory(const string& directory) {
util::setcwd(directory);
working_directory = directory;
}
string Shell::get_working_directory() const {
return working_directory;
}
const Shell* Shell::out(const string& message) {
this->standard_output << message << endl;
return this;
}
const Shell* Shell::eout(const string& message) {
this->error_output << message << endl;
return this;
}
const Shell* Shell::info(const string& message) {
this->out(this->name + ": " + message);
return this;
}
const Shell* Shell::warning(const string& message) {
this->out(this->name + " (warning): " + message);
return this;
}
const Shell* Shell::error(const string& message) {
this->eout(this->name + " (error): " + message);
return this;
}
void Shell::fatal(const string& message) {
this->eout("FATAL: " + message);
::exit(SHELL_FATAL);
}
void Shell::exit() {
if(this->exit_requested) {
this->fatal("Requested exit twice.");
}
// This way, the shell gets a chance to shut down in a clean fashion without
// having to call `exit()'.
// TODO(andrei) Test that nothing else is ever run after `exit_requested' is
// set, no matter where.
this->exit_requested = true;
}
template<class MODULE_TYPE>
int Shell::load_module(shared_ptr<MODULE_TYPE> module) {
module->initialize(*this);
auto builtins = module->get_builtins();
for(auto bf = builtins.begin(); bf != builtins.end(); ++bf) {
// TODO(andrei) Use managed memory in builtin registry.
// TODO(andrei) Builtin factories should know the builtin's name.
BuiltinRegistry::instance()->register_factory<MODULE_TYPE>(
(*bf)->get_name(), *bf
);
}
loaded_modules.push_back(module);
return 0;
}
string Shell::get_prompt() const {
return "(" + this->working_directory + ") " + this->prompt;
}
string Shell::read_command() {
unique_ptr<char> line(readline(get_prompt().c_str()));
// This happens if e.g. the user enters an EOF character (C-D).
if(!line) {
this->exit();
return "";
}
string command(line.get());
if(command.size() > 0) {
add_history(line.get());
}
return command;
}
int Shell::interpret_command(Command &cmd) {
return cmd.invoke(this);
}
bool Shell::parse_command(const string& command_text,
shared_ptr<Command> &command,
string *error) const {
// TODO(andrei) YACC this.
// TODO(andrei) Customizable IFS variable.
vector<string> argv = util::split(command_text, ' ');
// Perform expansion for every parameter.
for(string& arg : argv) {
arg = expand(arg);
}
const string& program_name = argv[0];
if(is_builtin(argv[0])) {
command = construct_builtin(argv);
}
else {
// If the path actually points to a directory, we want to catch that.
string full_path = resolve_path(program_name);
if (util::is_directory(full_path)) {
// TODO(andrei) zsh-like auto-cd functionality could go here.
*error = "Cannot execute [" + argv[0] + "]. It's a directory.";
return false;
}
string binary_path;
if(resolve_binary_name(argv[0], &binary_path)) {
argv[0] = binary_path;
command = make_shared<DiskCommand>(new DiskCommand(argv));
} else {
*error = "Command not found: [" + argv[0] + "]";
return false;
}
}
return true;
}
bool Shell::resolve_binary_name(const string& name, string* full_path) const {
// No lookup needed for absolute paths.
if(util::is_absolute_path(name)) {
*full_path = name;
return true;
}
// Search in our current directory.
{
string path = util::merge_paths(working_directory, name);
if(util::is_file(path)) {
*full_path = path;
return true;
}
}
// Search the PATH.
for(const string& p : this->path) {
string path = util::merge_paths(p, name);
if(util::is_file(path)) {
*full_path = path;
return true;
}
}
return false;
}
bool Shell::is_builtin(const string& builtin_name) const {
return BuiltinRegistry::instance()->is_registered(builtin_name);
}
shared_ptr<BuiltinCommand> Shell::construct_builtin(const vector<string>& argv) const {
return BuiltinRegistry::instance()->build(argv);
}
int Shell::load_default_modules() {
this->load_module(
make_shared<sample_module::SampleModule>(sample_module::SampleModule())
);
this->load_module(
make_shared<job_control::JobControl>(job_control::JobControl())
);
return 0;
}
bool Shell::get_waiting_for_child() const {
return this->waiting_for_child;
}
// TODO(andrei) Restructure this method. In many cases a child may not have an
// exit status, such as in the case when it is killed by a signal (9, force
// kill or 11, out of memory).
int Shell::wait_child(int child_pid) {
int child_status;
int child_exit_code = -1;
int waitpid_options = WUNTRACED;
this->waiting_for_child = true;
// TODO(andrei) Consider using wait4 and logging rusage data.
while(true) {
pid_t ret = waitpid(child_pid, &child_status, waitpid_options);
if(-1 == ret) {
this->error(strerror(errno));
this->fatal("`waitpid' has encountered a fatal error.");
}
if(0 == ret) {
this->fatal("waitpid should not return 0");
}
this->info("Woken up!");
if(WIFEXITED(child_status)) {
child_exit_code = WEXITSTATUS(child_status);
this->info(
"Child exited normally (exit code: " + to_string(child_exit_code) + ")."
);
break;
}
else if(WIFSIGNALED(child_status)) {
int child_murdering_signal = WTERMSIG(child_status);
this->info(strsignal(child_murdering_signal));
this->info(
"Child killed by signal " + to_string(child_murdering_signal) + "."
);
break;
}
else if(WIFSTOPPED(child_status)) {
int child_stopper = WSTOPSIG(child_status);
this->info(strsignal(child_stopper));
this->info("Child stopped by signal " + to_string(child_stopper) + ".");
break;
}
else {
this->fatal("Unexpected child process state. Terminating.");
}
}
this->waiting_for_child = false;
// TODO(andrei) This is broken on killed/suspended children.
return child_status;
}
} // namespace core
} // namespace microshell
|
#include "GameScene.h"
#include "ResultScene.h"
#include <DxLib.h>
#include <string>
#include "Game.h"
#include "Peripheral.h"
#include "Player.h"
#include "BackGround.h"
#include "EnemyFactory.h"
#include "Enemy.h"
#include "CharacterObject.h"
#include "CollisionDetector.h"
#include "Stage.h"
#include "Ground.h"
#include "Camera.h"
const int screen_x_size = 512;
const int screen_y_size = 480;
const int offset = 16;
const char* grImg = "image/Ground.png";
const char* crImg = "image/Condor.png";
const char* itImg = "image/nasu.png";
const char* goImg = "image/GameOver.png";
void GameScene::StartUpdate(const Peripheral & p)
{
}
void GameScene::NormalUpdate(const Peripheral & p)
{
auto scroll = camera->ScrollValue();
player->Update(p); //プレイヤーの更新
for (auto& enemy : efactory->GetLegion()) { //敵の更新
enemy->Update();
}
//ブロックとプレイヤーの当たり判定
for (int i = 0; i < stageheight; i++) {
for (int j = 0; j < stagewidth; j++) {
int idx = (stage->GetStageData()[j + i * stagewidth]);
if (idx != 4) {
Position2 pos = Position2(j * blockSize * 2 + blockSize, i*blockSize * 2 - (stageheight*blockSize * 2 - screen_y_size) + blockSize - offset * 2);
for (auto& prect : player->GetActionRects()) {
if (prect.rt == RectType::damage) {
Rect rc;
rc.center = pos;
rc.size.width = blockSize * 2;
rc.size.height = blockSize * 2;
if (CollisionDetector::IsCollided(player->GetActuralRectForAction(prect.rc), rc)) {
if (player->GetFall()) {
player->OnGround(rc.Top());
camera->CheckPos(pos);
}
else {
player->HitBlock(rc);
if (idx != 0) {
br_blocks.push_back(BREAK_BLOCK(Position2f(pos.x, pos.y), idx, Vector2f(player->GetTurn() ? 1.0f : -1.0f, -5.0f), player->GetTurn()));
stage->SetStageData(j + i * stagewidth, 4);
++blockCnt;
}
}
}
}
}
DxLib::DrawRectRotaGraph(pos.x, pos.y - scroll, idx*blockSize, 0, blockSize, blockSize, 2, DX_PI / 180 * 45, blockgh, true, false);
//DebugDraw(pos);
}
}
}
if (!br_blocks.empty()) {
for (auto& block : br_blocks) {
block.pos += block.vel;
DxLib::DrawRectRotaGraph(block.pos.x, block.pos.y - scroll, block.id*blockSize, 0, blockSize, blockSize, 2, block.vel.y >= 0 ? DX_PI / 180 * 90 : 0, blockgh, true, !block.turnflag);
block.vel.y += Game::Instance().GetGravity();
}
}
player->Draw();
if (player->GetPos().y > camera->GetViewport().Bottom()) {
DxLib::DrawRotaGraph(256, 240,2,0, gameovergh, true);
if (p.IsPressing(PAD_INPUT_10)) {
Game::Instance().ChangeScene(new ResultScene());
}
}
}
void GameScene::BonusUpdate(const Peripheral & p)
{
}
void GameScene::DebugDraw(Position2 pos)
{
Rect rc;
rc.center = pos;
rc.size.width = blockSize * 2;
rc.size.height = blockSize * 2;
auto scroll = camera->ScrollValue();
DxLib::DrawBox(rc.Left(), rc.Top()-scroll, rc.Right(), rc.Bottom() - scroll, 0xff0000, false);
}
GameScene::GameScene()
{
stage.reset(new Stage());
camera.reset(new Camera(*stage));
player.reset(new Player(*camera));
ground.reset(new Ground());
background.reset(new BackGround(*camera));
efactory.reset(new EnemyFactory(*camera, *player, *ground));
camera->SetFocus(player);
_updater = &GameScene::NormalUpdate;
blockgh = DxLib::LoadGraph(grImg);
condorgh = DxLib::LoadGraph(crImg);
nasugh = DxLib::LoadGraph(itImg);
gameovergh=DxLib::LoadGraph(goImg);
blockSize = stage->GetData().chipSize;
stageheight = stage->GetData().range.Height();
stagewidth = stage->GetData().range.Width();
}
GameScene::~GameScene()
{
}
void GameScene::Update(const Peripheral & p)
{
camera->Update();
const std::string enemyname[] = { "","Topi","Nitpicker"};
auto enemies = stage->GetEnemyData(camera->GetViewport().Left(), camera->GetViewport().Right());
auto& mapsize = stage->GetStageRange();
for (auto& enemy : enemies) {
if (enemyname[enemy] != "") {
if (enemyname[enemy] == "Nitpicker") {
efactory->Create(enemyname[enemy].c_str(), Position2f((float)((cnt / (mapsize.size.height / blockSize*2)) * blockSize*2), (float)(cnt % (mapsize.size.height / blockSize*2) * 32.0f)));
}
else {
efactory->Create(enemyname[enemy].c_str(), Position2f((cnt / (mapsize.size.height / blockSize*2)) * blockSize*2, cnt % (mapsize.size.height / blockSize*2) * blockSize*2 - 96.0f));
}
}
++cnt;
}
background->Draw();
///敵の表示
for (auto& enemy : efactory->GetLegion()) {
enemy->Draw();
}
(this->*_updater)(p);
}
|
// Talent Competition.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
// Adding methods outside of the main
void getJudgeData(double &);
//Needed to change it from a void to a double
double calcScore(double, double, double, double, double);
// These next two function need to be called by the calcScore function....probably needs to be changed to either a double or a flaot...
// Will more than likely be using a double for the two below
int findLowest(double, double, double, double, double);
int findHighest(double, double, double, double, double);
int main()
{
double judge1,
judge2,
judge3,
judge4,
judge5;
//Lets call the getJudgeData function for each judge score
getJudgeData(judge1);
getJudgeData(judge2);
getJudgeData(judge3);
getJudgeData(judge4);
getJudgeData(judge5);
//Print out contestants score
cout << "The contestants score is: " << calcScore(judge1, judge2, judge3, judge4, judge5);
return 0;
}
// Get judge score input with a validation
void getJudgeData(double &judgeScore)
{
// Make a do while loop so it doesn't become an infinite loop
do
{
// Ask user to put in the judges score
cout << "Enter a judges score: ";
cin >> judgeScore;
//Here is the validation so that way if they try to put anything less than 0 or greater that 10, it's covered.
if (judgeScore < 0 || judgeScore > 10)
{
cout << "\nError: Judges score must be greater than 0 and less than 10.\n";
}
} while (judgeScore < 0 || judgeScore > 10);
}
// Do some math in this function to find the final score after dropping the lowest and highest
double calcScore(double judge1, double judge2, double judge3, double judge4, double judge5)
{
double high, low;
double finalScore;
// Calculating the highest and lowest score while passing the scores
high = findHighest(judge1, judge2, judge3, judge4, judge5);
low = findLowest(judge1, judge2, judge3, judge4, judge5);
// Adding if statements
if ( low == judge1)
{
if (high == judge2)
{
finalScore = (judge3 + judge4 + judge5) / 3;
}
else if (high == judge3)
{
finalScore = (judge2 + judge4 + judge5) / 3;
}
else if (high == judge4)
{
finalScore = (judge2 + judge3 + judge5) / 3;
}
else
{
finalScore = (judge2 + judge3 + judge4) / 3;
}
}
else if (low == judge2)
{
if (high == judge1)
{
finalScore = (judge3 + judge4 + judge5) / 3;
}
else if (high == judge3)
{
finalScore = (judge1 + judge4 + judge5) / 3;
}
else if (high == judge4)
{
finalScore = (judge1 + judge3 + judge5) / 3;
}
else
{
finalScore = (judge1 + judge3 + judge4) / 3;
}
}
else if (low == judge3)
{
if (high == judge1)
{
finalScore = (judge2 + judge4 + judge5) / 3;
}
else if (high == judge2)
{
finalScore = (judge1 + judge4 + judge5) / 3;
}
else if (high == judge4)
{
finalScore = (judge1 + judge2 + judge5) / 3;
}
else
{
finalScore = (judge1 + judge2 + judge4) / 3;
}
}
else if (low == judge4)
{
if (high == judge1)
{
finalScore = (judge2 + judge3 + judge5) / 3;
}
else if (high == judge2)
{
finalScore = (judge1 + judge3 + judge5) / 3;
}
else if (high == judge3)
{
finalScore = (judge1 + judge2 + judge5) / 3;
}
else
{
finalScore = (judge1 + judge2 + judge3) / 3;
}
}
else
{
if (high == judge1)
{
finalScore = (judge2 + judge3 + judge4) / 3;
}
else if(high == judge2)
{
finalScore = (judge1 + judge3 + judge4) / 3;
}
else if(high == judge3)
{
finalScore = (judge1 + judge2 + judge4) / 3;
}
else
{
finalScore = (judge1 + judge2 + judge3) / 3;
}
}
// Print contestants score
return finalScore;
}
// Do some math to find the highest score
int findHighest(double judge1, double judge2, double judge3, double judge4, double judge5)
{
if ((judge1 > judge2) && (judge1 > judge3) && (judge1 > judge4) && (judge1 > judge5))
{
return judge1;
}
else if ((judge2 > judge1) && (judge2 > judge3) && (judge2 > judge4) && (judge2 > judge5))
{
return judge2;
}
else if ((judge3 > judge1) && (judge3 > judge2) && (judge3 > judge4) && (judge3 > judge5))
{
return judge3;
}
else if ((judge4 > judge1) && (judge4 > judge2) && (judge4 > judge3) && (judge4 > judge5))
{
return judge4;
}
else
{
return judge5;
}
}
// Do some math to find the lowest score
int findLowest(double judge1, double judge2, double judge3, double judge4, double judge5)
{
if ((judge1 < judge2) && (judge1 < judge3) && (judge1 < judge4) && (judge1 < judge5))
{
return judge1;
}
else if ((judge2 < judge1) && (judge2 < judge3) && (judge2 < judge4) && (judge2 < judge5))
{
return judge2;
}
else if ((judge3 < judge1) && (judge3 < judge2) && (judge3 < judge4) && (judge3 < judge5))
{
return judge3;
}
else if ((judge4 < judge1) && (judge4 < judge2) && (judge4 < judge3) && (judge4 < judge5))
{
return judge4;
}
else
{
return judge5;
}
}
/*
A particular talent competition has five judges, each of whom awards a score between 0 and 10 to each performer. Fractional scores, such as 8.3, are allowed. A performer's final score is determined by dropping the highest and lowest score received, then averaging the three remaining scores. Write a program that uses this method to calculate a contestant's score. It should include the following functions:
void getJudgeData() should ask the user for a judge's score, store it in a reference parameter variable, and validate it. This function should be called by main once for each of the five judges.
void calcScore() should calculate and display the average of the three scores that remain after dropping the highest and lowest scores the performer received. This function should be called just once by main and should be passed the five scores.
The last two functions, described below, should be called by calcScore, which uses the returned information to determine which of the scores to drop.
int findLowest() should find and return the lowest of the five scores passed to it.
int findHighest() should find and return the highest of the five scores passed to it.
Input Validation: Do not accept judge scores lower than 0 or higher than 10.
*/
|
#include "components/ai/activityai.hpp"
#include "components/ai/callbackai.hpp"
#include "entities/citizen.hpp"
#include "city.hpp"
#include "defs.hpp"
#include "components/furniture.hpp"
#include "entities/garbage.hpp"
#include "components/ai/ifai.hpp"
#include "components/ai/ifai.hpp"
#include "log.hpp"
#include "components/ai/pathai.hpp"
#include "components/room.hpp"
#include "components/ai/sequenceai.hpp"
#include "job/job.hpp"
#include "job/joblist.hpp"
#include "windows.hpp"
#include "entities/workroom.hpp"
#include <cstdlib>
#include <random>
#include <memory>
using namespace ai;
enum Designations : char
{
D_DIG = 1,
D_BUILD = 2
};
point City::random_point() {
// Try to find a point 5 times randomly.
for (int x = 0; x < 5; ++x) {
point p = { rand() % getXSize(), rand() % getYSize() };
if (tile(p.first, p.second).walkable()) {
return p;
}
}
// If we've failed 5 times, (maybe big map with small walkable area?), just do a walk
for (int x = 0; x < xsz; ++x) {
for (int y = 0; y < ysz; ++y) {
if (tile(x, y).walkable()) {
return { x, y };
}
}
}
std::abort();
}
int City::getXSize() const { return xsz; }
int City::getYSize() const { return ysz; }
Tile City::tile(int x, int y) const { return tiles.data[xsz*y + x]; }
Tile& City::tile(int x, int y) { return tiles.data[xsz*y + x]; }
const City::ents_t& City::ent(int x, int y) const { return ents.data[xsz*y + x]; }
City::ents_t& City::ent(int x, int y) { return ents.data[xsz*y + x]; }
void City::add_ent(int x, int y, ecs::Ent* e) {
ent(x, y).insert(e);
}
void City::del_ent(int x, int y, ecs::Ent* e) {
ent(x, y).erase(e);
}
bool City::check(int x, int y) const {
return (x >= 0 && x < xsz) && (y >= 0 && y < ysz);
}
City::City() : xsz(0), ysz(0),
tiles(xsz,ysz),
ents(xsz,ysz),
designs(xsz,ysz),
furniture(xsz,ysz){}
void City::generate(struct CityProperties const& cityP) {
xsz = cityP.width;
ysz = cityP.height;
tiles.resize(xsz, ysz);
ents.resize(xsz, ysz);
designs.resize(xsz, ysz);
furniture.resize(xsz, ysz);
randomgen(*this, cityP);
}
void City::resize(int x, int y) {
xsz = x;
ysz = y;
furniture.resize(x, y);
tiles.resize(x, y);
ents.resize(x, y);
designs.resize(x, y);
}
wistream& operator>>(wistream& is, City& c) {
c.xsz = 0;
c.ysz = 0;
size_t x = 0;
size_t y = 0;
wstring s;
while (getline(is, s)) {
// LOGGER::error() << "'" << s. << "'" << endl;
if (s.size() == 0)
continue;
if (y == 0)
x = s.size();
if (s.size() != x)
throw runtime_error("invalid c format");
for (size_t i = 0; i < x; ++i) {
c.tile(i, y) = { (Tile::TileKind)s[i] };
c.ent(i, y).clear();
}
++y;
}
if (y == 0)
throw runtime_error("invalid c size");
c.resize(x, y);
LOGGER::verbose() << "C is " << x << " by " << y << endl;
// Now generate rooms
for (int j = 0; j < c.getYSize(); ++j) {
for (int i = 0; i < c.getXSize(); ++i) {
char ch = c.tile(i, j).type;
if (ch == Tile::wall || ch == Tile::ground) {
} else if (ch == 'E') {
// Citizen* e = new Citizen(i,j,Security::RED, c);
// e->insert_after(c.ent(i,j));
new_citizen({ &c, i, j }, Security::RED);
c.tile(i, j).type = Tile::ground;
} else if (ch == 'O') {
// Citizen* e = new Citizen(i,j,Security::ORANGE, c);
// e->insert_after(c.ent(i,j));
new_citizen({ &c, i, j }, Security::ORANGE);
c.tile(i, j).type = Tile::ground;
} else if (ch == 'D') {
// Dwarf* e = new Dwarf(i,j, c);
// e->insert_after(c.ent(i,j));
c.tile(i, j).type = Tile::ground;
} else {
// figure out how wide and high the room is
int kx, ky, w, h;
for (kx = i; kx < c.getXSize(); ++kx) {
if (c.tile(kx, j).type != ch)
break;
}
for (ky = j; ky < c.getYSize(); ++ky) {
for (int x = i; x < kx; ++x) {
if (c.tile(x, ky).type != ch)
goto finish_loop;
}
}
finish_loop:
w = kx - i;
h = ky - j;
for (int y = j; y < ky; ++y) {
for (int x = i; x < kx; ++x) {
c.tile(x, y).type = Tile::ground;
}
}
// room's top-left is i,j and dimensions are w x h
c.rooms.push_back(make_workroom({ &c, i, j, w, h })->assert_get<Room>());
}
}
}
for (auto r : c.rooms)
LOGGER::verbose() << r->r.w << 'x' << r->r.h << " Room @ " << r->r.x << ", " << r->r.y << endl;
for (int j = 0; j < c.getYSize(); ++j) {
for (int i = 0; i < c.getXSize(); ++i)
LOGGER::verbose() << (char)c.tile(i, j).type;
LOGGER::verbose() << '\n';
}
return is;
}
void add_wall_dig_job(City* city, int x1, int y1, int digx, int digy) {
clearance c = { Security::ALL, Department::ALL };
auto wall_cb = [=](AI*) {
return city->designs(digx, digy) & D_DIG && city->tile(digx, digy).type == Tile::wall;
};
auto dig_cb = [=](AI*) { city->remove_wall(digx, digy); };
auto s1 = make_shared<SequenceAI>();
s1->add_task(make_shared<ActivityAI>(100));
s1->add_task(new_ifscript(wall_cb, make_callbackai(dig_cb)));
auto s2 = make_shared<SequenceAI>();
s2->add_task(make_shared<PathAI>(point(x1, y1)));
s2->add_task(new_ifscript(wall_cb, s1));
auto job = std::make_shared<job::Job>("Dig", c, s2);
job::JobList::getJoblist().add_job(job);
}
void add_wall_build_job(City* city, int x1, int y1, int digx, int digy) {
clearance c = { Security::ALL, Department::ALL };
auto wall_cb = [=](AI*) {
return city->designs(digx, digy) & D_BUILD && city->tile(digx, digy).type == Tile::ground;
};
struct BuildWallAI : AIScript {
BuildWallAI(City* city, int digx, int digy) : m_city(city), m_x(digx), m_y(digy), desc("Building Wall") { }
virtual AI::timer_t start(AI* ai) {
// If there are entities at the target location, we can't build a wall.
if (m_city->ent(m_x, m_y).size() > 0) {
return ai->fail_script();
}
// Same for furniture
if (m_city->furniture(m_x, m_y) != nullptr) {
return ai->fail_script();
}
m_city->add_wall(m_x, m_y);
return ai->pop_script();
}
virtual const std::string& description() const override {
return desc;
}
private:
City* m_city;
int m_x;
int m_y;
std::string desc;
};
auto s1 = make_shared<SequenceAI>();
s1->add_task(make_shared<ActivityAI>(100));
s1->add_task(new_ifscript(wall_cb, make_shared<BuildWallAI>(city, digx, digy)));
auto s2 = make_shared<SequenceAI>();
s2->add_task(make_shared<PathAI>(point(x1, y1)));
s2->add_task(new_ifscript(wall_cb, s1));
auto job = std::make_shared<job::Job>("Build Wall", c, s2);
job::JobList::getJoblist().add_job(job);
}
void City::add_room(Room* r) {
assert(r != nullptr);
assert(std::find(rooms.begin(), rooms.end(), r) == rooms.end());
rooms.push_back(r);
}
void City::del_room(Room* r) {
assert(r != nullptr);
auto it = std::find(rooms.begin(), rooms.end(), r);
assert(it != rooms.end());
rooms.erase(it);
}
void City::add_furniture(Furniture* f) {
assert(furniture(f->x(), f->y()) == nullptr);
furniture(f->x(), f->y()) = f;
}
void City::del_furniture(Furniture* f) {
assert(furniture(f->x(), f->y()) == f);
furniture(f->x(), f->y()) = nullptr;
}
std::vector<Room*> City::find_rooms(int x, int y) {
std::vector<Room*> ret;
for (auto r : rooms)
if (r->contains(x, y))
ret.push_back(r);
return ret;
}
std::vector<Furniture*> City::find_furniture(int x, int y, int w, int h) {
std::vector<Furniture*> ret;
for (int i = x; i < x + w; ++i) {
for (int j = y; j < y + h; ++j) {
if (furniture(i, j) != nullptr)
ret.push_back(furniture(i, j));
}
}
return ret;
}
std::vector<Furniture*> City::find_furniture(Rect r) {
return find_furniture(r.x, r.y, r.w, r.h);
}
void City::toggle_dig_wall(int x, int y) {
if (tile(x, y).type == Tile::wall) {
designs(x, y) ^= D_DIG; // Mark for digging
if (designs(x, y) & D_DIG) {
for (auto o : offs) {
if (tile(x + o.first, y + o.second).walkable()) {
add_wall_dig_job(this, x + o.first, y + o.second, x, y);
break;
}
}
}
}
}
void City::toggle_build_wall(int x, int y) {
if (tile(x, y).type == Tile::ground) {
designs(x, y) ^= D_BUILD; // Mark for digging
if (designs(x, y) & D_BUILD) {
for (auto o : offs) {
if (tile(x + o.first, y + o.second).walkable()) {
add_wall_build_job(this, x + o.first, y + o.second, x, y);
break;
}
}
}
}
}
void City::remove_wall(int x, int y) {
if (tile(x, y).type != Tile::wall)
{
return;
}
designs(x, y) &= ~D_DIG;
tile(x, y).type = Tile::ground;
// For each adjacent tile
for (auto o : offs) {
// If the adjacent tile does not have a pending dig or build
if (!(designs(x + o.first, y + o.second) & (D_DIG | D_BUILD))) {
// Skip this adjacent tile
continue;
}
// Count the number of walkable tiles adjacent to the target
int facings = 0;
for (auto o2 : offs) {
if (tile(x + o.first + o2.first, y + o.second + o2.second).walkable()) {
++facings;
}
}
// If this change has created the only walkable tile, add a job to complete the desired designation.
if (facings == 1) {
if (designs(x + o.first, y + o.second) & D_DIG) {
add_wall_dig_job(this, x, y, x + o.first, y + o.second);
}
if (designs(x + o.first, y + o.second) & D_BUILD) {
add_wall_build_job(this, x, y, x + o.first, y + o.second);
}
}
}
}
void City::add_wall(int x, int y) {
if (tile(x, y).type != Tile::ground)
return;
designs(x, y) &= ~D_BUILD;
tile(x, y).type = Tile::wall;
}
|
//p10827 with O(n^3) complexity
#include<iostream>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define MAX(a,b) (a)>(b)?(a):(b)
using namespace std;
int main()
{
int i,j,N,start,end,A[75][75][75],t;//A[row][startcol][endcol]
long totsum,currsum,negsum,maxsum;
cin>>t;
while(t--)
{
cin>>N;
FOR0(i,N)FOR0(j,N)
cin>>A[i][j][j];
FOR0(i,N)
FOR0(start,N)
{
FOR(end,start+1,N)
A[i][start][end]=A[i][start][end-1]+A[i][end][end];
FOR(end,0,start)
A[i][start][end]=A[i][start][N-1]+A[i][0][end];
}
maxsum=-127*N*N;
FOR0(start,N)
FOR0(end,N)
{
currsum=0; totsum=0;
bool pos=false,neg=false;
FOR0(i,N)
{
int curr=A[i][start][end];
currsum+=curr;
totsum+=curr;
if(curr<0)neg=true;
else pos=true;
maxsum=MAX(maxsum,currsum);
if(currsum<0)currsum=0;
}
negsum=-127*N*N;
if(pos&&neg)
{
currsum=0;
FOR0(i,N)
{
int curr=A[i][start][end];
currsum-=curr;
negsum=MAX(negsum,currsum);
if(currsum<0)currsum=0;
}
}
maxsum=MAX(maxsum,totsum+negsum);
}
cout<<maxsum<<endl;
}
return 0;
}
|
#pragma once
#include "GameObject.h"
#include "OBJLoader.h"
#include <xnamath.h>
class Tree
{
private:
XMFLOAT3 pos;
public:
GameObject treeTrunk;
GameObject treeTop;
ID3D11ShaderResourceView* g_treeTrunkTexture;
ID3D11ShaderResourceView* g_treeTopTexture;
Tree();
~Tree();
void TreeInit(ID3D11Device *_pd3dDevice);
void loadTextures(ID3D11Device *_pd3dDevice);
void Update(float t);
XMFLOAT4X4 getWorld(GameObject t);
void Draw(ID3D11Device * pd3dDevice, ID3D11DeviceContext * pImmediateContext);
};
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <cassert>
using namespace std;
int main(){
int n,t;
cin >> n;
// assert(1 <= n and n <= 10);
for(int i = 0; i < n; i++){
cin >> t;
set<string>mystr;
// assert(1 <= t and n <= 100000);
for(int j = 0; j < t; j++){
string str;
cin >> str;
// assert(1 <= str.size() and str.size() <= 100000);
mystr.insert(str);
}
set<string>::iterator it;
for(it = mystr.begin(); it!=mystr.end(); it++){
cout << *it << "\n";
}
}
return 0;
}
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QRect>
#include <QKeyEvent>
class Breakout : public QWidget
{
Q_OBJECT
public:
Breakout(QWidget *parent = 0);
~Breakout() = default;
protected:
void paintEvent(QPaintEvent *);
void timerEvent(QTimerEvent *);
void keyPressEvent(QKeyEvent *);
private:
enum Direction {
UpLeft,
Up,
UpRight,
DownLeft,
Down,
DownRight
};
enum PaddleDirection {
None,
Left,
Right
};
private:
void game_step();
void game_finished(const QString & message);
void move_ball();
void move_paddle();
void switch_direction(const QRect & rect);
void bounce_top();
void bounce_right();
void bounce_left();
void check_boundaries();
private:
static const int WIDTH = 600;
static const int HEIGHT = 400;
static const int SPEED = 15;
static const int DELAY = 70;
private:
bool m_in_game;
bool m_won;
Direction m_direction;
PaddleDirection m_paddle_direction;
QRect m_paddle;
std::vector<QRect> m_bricks;
int m_ball_x;
int m_ball_y;
int m_ball_radius;
int m_timer_id;
};
#endif // WIDGET_H
|
#ifndef SURFACE_FEATURE_H
#define SURFACE_FEATURE_H
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <set>
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Surface_mesh.h>
#include <CGAL/Vector_3.h>
#include <boost/graph/graph_traits.hpp>
#include <CGAL/boost/graph/properties.h>
#include <CGAL/Polygon_mesh_processing/stitch_borders.h>
#include <CGAL/boost/graph/iterator.h>
#include <algorithm>
namespace SurfaceFeatureExtractor
{
typedef CGAL::Simple_cartesian<double> K;
typedef CGAL::Surface_mesh<K::Point_3> Mesh;
typedef Mesh::Vertex_index vertex_descriptor;
typedef K::Point_3 Point;
typedef Mesh::Face_index face_descriptor;
typedef CGAL::Vector_3<K> Vector;
typedef size_t vertex_id;
typedef size_t triangle_id;
typedef size_t patch_id;
struct SurfaceFeature
{
double surfaceArea;
double holeArea;
double surfaceToHoleRatio;
int numberOfPatches;
double patchRatio; //biggest to smallest
};
class TriangleData
{
public:
TriangleData(size_t _index, double _longest_side, double _area, bool _isHole) : index(_index), longest_side(_longest_side), area(_area), isHole(_isHole){}
TriangleData(){}
size_t index;
double longest_side;
double area;
bool isHole;
};
const double line_treshold_mulitplicator = 2;
const double preset_hole_factor = 2;
SurfaceFeature getSurfaceFeatureLongestLineMethodExportToPlyWithoutCgal (const std::vector<glm::dvec3>& _verts, const std::vector<glm::ivec3>& _tris, const double hole_factor = preset_hole_factor, std::string _filename = "default_patch_vertice_method_name.ply");
std::pair<double,double> getSurfaceAndHoleArea(const std::vector<TriangleData>& _triangleData);
std::pair<double,double> getLongestSideAndArea(const std::vector<glm::dvec3>& _verts, const glm::ivec3& _tris);
void exportHolesAndSurface(const std::string _filename, const std::vector<glm::dvec3>& _verts, const std::vector<glm::ivec3>& _tris, const double hole_factor = preset_hole_factor);
std::pair<std::map<triangle_id,patch_id>, size_t> clusterPatches(const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const std::vector< TriangleData >& _triangleData);
void fillVertexToTriangleLookup(const std::vector<glm::ivec3> &_tris, const std::vector< TriangleData >& _triangleData, std::map<vertex_id, std::vector<triangle_id> >& _lookup);
void visitVertex(vertex_id _vertex_id, std::map<triangle_id,patch_id>& _triangleToPatchLookup, std::set<vertex_id>& _visitedVerts, patch_id _patchid, const std::map<vertex_id, std::vector<triangle_id> >& _vertexToTriangleLookup, const std::vector<glm::ivec3> &_tris);
SurfaceFeature getSurfaceFeatureLongestLineMethodWithoutCgal(const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const double hole_factor = 2.0);
}
#endif
|
#include "SPI.h"
#include "Adafruit_WS2801.h"
/*****************************************************************************
*
* X-Mas lights by m.nu.
*
* Based on https://learn.adafruit.com/12mm-led-pixels/overview by Adafruit.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Example written by Limor Fried/Ladyada for Adafruit Industries.
* BSD license, all text above must be included in any redistribution
*
*****************************************************************************/
#define COLOR_WHEEL_MAX 1536
const int number_of_strands = 4; // number of LED strands to address
const int leds_per_strand = 50; //Number of LEDs per strand
const int number_of_leds = leds_per_strand * number_of_strands; //Total number of LEDs
// values used by the "snow glitter" mode
/* ************************************************************************************** */
const int diodes = leds_per_strand/3; //Truncated, so if 50 LEDs per strand, 16 will be lit at a time
int diode_pos[diodes]; //One third of the LEDs will be lit at one time
int diode_progress[diodes]; //Progress of specific LED, 0-170
boolean diode_fade_in[diodes]; //Is LED fading in or out?
int colors[number_of_leds];
int twinkle_diodes[number_of_leds/10]; // Twinkle with ten percent of all leds.
int twinkle_diode_counter[number_of_leds/10]; // Twinkle with ten percent of all leds.
int fade_step = 0;
int shift_counter = 0;
/* ************************************************************************************** */
uint8_t data_pin = 17; // Analog 3 (Analog pins used to simplify wiring. By using Analog pins we only need to have wires on one side of the Arduino Nano
uint8_t clock_pin = 19; // Analog 5
uint8_t button_pin = 3; // Digital 3
uint8_t analog_pin = 14; // Analog 0 - Potentiometer wiper (middle terminal) connected to analog pin 0
// outside leads to ground and +5V
enum modes
{
white_color_run,
rainbow_cycle,
rgb_color_wipe,
red_white_color_run,
snow_glitter,
color_select,
white_dim,
random_color_cycle,
random_color_cycle_twinkle,
random_color_cycle_shift,
big_color_cycle,
color_shifting_tree,
mode_max
};
//Variables used to keep track of button presses
volatile int button_state = HIGH; // current state of the button
volatile long last_debounce_time = 0; // previous state of the button
volatile int debounce_delay = 10;
volatile int last_state = HIGH;
volatile int current_mode = (int) modes::random_color_cycle;
int stored_mode = current_mode;
//wait is used to store data from the potentiometer.
int wait = 0;
// Set the first variable to the number_of_leds of pixels.
Adafruit_WS2801 strip = Adafruit_WS2801(number_of_leds, data_pin, clock_pin);
void button_up();
void button_down();
// Work around for debounces
void button_up()
{
long current_time = millis();
if ((current_time - last_debounce_time) > debounce_delay)
{
last_debounce_time = current_time;
if (button_state == LOW)
{
button_state = HIGH;
attachInterrupt(digitalPinToInterrupt(button_pin), button_down, FALLING);
}
}
}
void button_down()
{
long current_time = millis();
if ((current_time - last_debounce_time) > debounce_delay)
{
last_debounce_time = current_time;
if (button_state == HIGH)
{
button_state = LOW;
current_mode++;
if (current_mode == mode_max)
{
current_mode = (int) white_color_run;
}
attachInterrupt(digitalPinToInterrupt(button_pin), button_up, RISING);
}
}
}
void setup()
{
pinMode(button_pin, INPUT_PULLUP); //init Pins
pinMode(analog_pin, INPUT);
pinMode(clock_pin, OUTPUT);
pinMode(data_pin, OUTPUT);
Serial.begin(57600);
attachInterrupt(digitalPinToInterrupt(button_pin), button_down, FALLING);
strip.begin(); //Lets start!
}
void loop()
{
// We've just started or switched mode, store current mode and reset all leds
store_current_mode();
reset_all_leds();
switch (current_mode)
{
case white_color_run:
Serial.println("Mode: color_run");
white_color_run_mode();
break;
case rainbow_cycle:
Serial.println("Mode: rainbow_cycle");
rainbow_cycle_mode();
break;
case rgb_color_wipe:
Serial.println("Mode: rgb_color_wipe");
rgb_color_wipe_mode();
case red_white_color_run:
Serial.println("Mode: red_white_color_run");
red_white_color_run_mode();
break;
case snow_glitter:
Serial.println("Mode: snow_glitter");
snow_glitter_mode();
break;
case color_select:
Serial.println("Mode: color_select");
color_select_mode();
break;
case white_dim:
Serial.println("Mode: white_dim");
white_dim_mode();
break;
case random_color_cycle:
case random_color_cycle_twinkle:
case random_color_cycle_shift:
Serial.println("Mode: random_color_cycle");
random_color_cycle_mode(current_mode == random_color_cycle_twinkle, current_mode == random_color_cycle_shift);
break;
case big_color_cycle:
Serial.println("Mode: big_color_cycle");
big_color_cycle_mode();
break;
case color_shifting_tree:
Serial.println("Mode: color_shifting_tree");
color_shifting_tree_mode();
break;
}
}
//run 10 white pixels thru the entire LED strip.
void white_color_run_mode()
{
while (true)
{
color_run(create_24bit_color_value(255, 255, 255), 10);
if (mode_change()) //Button is pressed, exit
{
break;
}
}
}
//run a nice rainbow effect
void rainbow_cycle_mode()
{
while (true)
{
rainbow_cycle_effect();
if (mode_change()) //Button is pressed, exit
{
break;
}
}
}
//Fill the strip with off pixels.
void rgb_color_wipe_mode()
{
while (true)
{
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(255, 0, 0)); //Fill the strip with red pixels
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(0, 0, 0)); //Fill the strip with off pixels.
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(0, 255, 0)); //Fill the strip with green pixels
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(0, 0, 0)); //Fill the strip with off pixels.
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(0, 0, 255)); //Fill the strip with blue pixels.
if (mode_change()) //Button is pressed, exit
{
break;
}
color_wipe(create_24bit_color_value(0, 0, 0));
}
}
void red_white_color_run_mode()
{
while (true)
{
color_run(create_24bit_color_value(255, 0, 0), 5); //run 5 red pixels throu the strip
if (mode_change()) //Button is pressed, exit
{
break;
}
color_run(create_24bit_color_value(255, 255, 255), 5); //run 5 white pixels throu the strip
if (mode_change()) //Button is pressed, exit
{
break;
}
}
}
void snow_glitter_mode()
{
color_run(create_24bit_color_value(255, 255, 255), 10);
//Setup of snow glitter
boolean fade_in = true; //Used below to set fade in or fade out
int random_led; // Used for generating random numbers
//Setup phase, choose random LEDs to start with, randomize fade progress and set fade in/out
for (int i = 0; i < diodes; i++)
{
fade_in = !fade_in;
find_new_led(i);
diode_progress[i] = random(85); //set random progress in the fade sequence
diode_fade_in[i] = fade_in; //set fade in or fade out for this diode
}
while (true)
{
snow_glitter_effect();
if (mode_change()) //Button is pressed, exit
{
break;
}
}
}
void color_select_mode()
{
while (!mode_change())
{
int color_value = analogRead(analog_pin)*1.5;
Serial.println(color_value);
uint32_t color = big_wheel(color_value, 255);
for (int i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, color);
}
strip.show();
}
}
void white_dim_mode()
{
while (!mode_change())
{
int color_value = analogRead(analog_pin)/8;
uint32_t color = create_24bit_color_value(color_value, color_value, color_value);
for (int i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, color);
}
strip.show();
}
}
void rainbow_cycle_effect() //rainbow effect (By Adafruit)
{
for (int j = 0; j < 256 * 20; j++) // 5 cycles of all 25 colors in the wheel
{
for (int i = 0; i < strip.numPixels(); i++)
{
// tricky math! we use each pixel as a fraction of the full 96-color wheel
// (thats the i / strip.numPixels() part)
// Then add in j which makes the colors go around per pixel
// the % 96 is to make the wheel cycle around
strip.setPixelColor(i, small_wheel( ((i * 256 / strip.numPixels()) + j) % 256) );
}
if (mode_change()) //is button pressed?
{
break;
}
strip.show(); // write all the pixels out
wait = analogRead(analog_pin)/10/number_of_strands;
delay(wait);
}
}
// Randomize the value for each diode and cycle through each one through the big colour wheel
void random_color_cycle_mode(bool enable_twinkle_effect, bool shift_pixels)
{
byte max = analogRead(analog_pin) / 4;
for (int i = 0; i < strip.numPixels(); i++)
{
colors[i] = random(0, COLOR_WHEEL_MAX-1);
strip.setPixelColor(i, big_wheel(colors[i], max));
}
if (enable_twinkle_effect)
{
twinkle_setup(max);
}
strip.show(); // write all the pixels out
while (!mode_change())
{
max = analogRead(analog_pin) / 4;
if (shift_pixels)
{
if (shift_counter > 10)
{
int first_pixel = colors[0];
for (int i = 0; i < (strip.numPixels()-1); i++)
{
colors[i] = colors[i+1];
}
colors[strip.numPixels()-1] = first_pixel;
shift_counter = 0;
}
else
{
shift_counter++;
}
}
for (int i = 0; i < strip.numPixels(); i++)
{
colors[i]++;
if (colors[i] > (COLOR_WHEEL_MAX-1))
{
colors[i] = 0;
}
if ((enable_twinkle_effect && !contains(twinkle_diodes, i)) || !enable_twinkle_effect)
{
strip.setPixelColor(i, big_wheel(colors[i], max));
}
}
if (enable_twinkle_effect) // randomly switch off 10% of all diodes
{
twinkle(max);
}
strip.show(); // write all the pixels out
if (shift_pixels)
{
shift_counter++;
}
else
{
shift_counter = 0;
}
}
}
void big_color_cycle_mode()
{
int color_step = COLOR_WHEEL_MAX / strip.numPixels();
for (int i = 0; i < strip.numPixels(); i++)
{
colors[i] = i * color_step;
strip.setPixelColor(i, big_wheel(colors[i], 255));
}
strip.show(); // write all the pixels out
while (!mode_change())
{
for (int i = 0; i < strip.numPixels(); i++)
{
colors[i]++;
if (colors[i] > (COLOR_WHEEL_MAX-1))
{
colors[i] = 0;
}
strip.setPixelColor(i, big_wheel(colors[i], 255));
}
strip.show(); // write all the pixels out
wait = analogRead(analog_pin)/10/number_of_strands;
delay(wait);
}
}
void color_shifting_tree_mode()
{
int color = 0;
while(!mode_change())
{
for (int i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, big_wheel(color, 255));
}
strip.show();
color++;
if (color > (COLOR_WHEEL_MAX-1))
{
color = 0;
}
}
}
// fill the dots one after the other with said color
// good for testing purposes
void color_run (uint32_t c, uint32_t l) //By Adafruit
{
for (int i = 0; i < strip.numPixels() + l + 1; i++)
{
strip.setPixelColor(i, c);
if (i > l)
{
strip.setPixelColor(i - l - 1, 0);
}
strip.show();
if (mode_change())
{
break;
}
wait = analogRead(analog_pin)/10/number_of_strands;
delay(wait);
}
}
void color_wipe(uint32_t c) //By Adafruit
{
for (int i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, c);
strip.show();
if (mode_change())
{
break;
}
wait = analogRead(analog_pin)/10/number_of_strands;
delay(wait);
}
}
void snow_glitter_effect() //By www.m.nu
{
for (int i = 0; i < diodes; i++)
{
//reverse fade direction if diode is at the end, if faded out randomize new diode
if (diode_progress[i] < 1)
{
find_new_led(i);
diode_fade_in[i] = true;
}
else if (diode_progress[i] > 40)
{
diode_fade_in[i] = false;
}
//set LED light (based on diode_progress)
//"show" below to speed up processing
for (int j = 0; j < number_of_strands; j++)
{
strip.setPixelColor(diode_pos[i]+(j*leds_per_strand), white_fade(diode_progress[i]));
}
if (diode_fade_in[i])
{
diode_progress[i] += 1;
}
else
{
diode_progress[i] -= 1;
}
if (mode_change())
{
break;
}
wait = analogRead(analog_pin)/30/number_of_strands;
// 1 is optimal pause for this mode
delay(wait);
}
strip.show();
}
/* Helper functions */
// Create a 24 bit color value from R,G,B
uint32_t create_24bit_color_value(byte r, byte g, byte b)
{
uint32_t c;
c = r;
c <<= 8;
c |= g;
c <<= 8;
c |= b;
return c;
}
//A three position colour wheel, will for example miss yellow, magenta and cyan
//Input a value 0 to 255 to get a color value.
//The colours are a transition r - g -b - back to r
uint32_t small_wheel(byte wheel_pos)
{
if (wheel_pos < 85) {
return create_24bit_color_value(wheel_pos * 3, 255 - wheel_pos * 3, 0);
}
else if (wheel_pos < 170) {
wheel_pos -= 85;
return create_24bit_color_value(255 - wheel_pos * 3, 0, wheel_pos * 3);
}
else {
wheel_pos -= 170;
return create_24bit_color_value(0, wheel_pos * 3, 255 - wheel_pos * 3);
}
}
//A twelve position colour wheel
//Input a value 0 to COLOR_WHEEL_MAX to get a color value, and a value to set a dimming effect
//It cycles through red, orange, yellow, spring green, green, turquiose, cyan, ocean, blue, violet, magenta, raspberry, red
uint32_t big_wheel(int wheel_pos, byte max) // by www.m.nu
{
int color_step = COLOR_WHEEL_MAX / 6;
wheel_pos = wheel_pos % COLOR_WHEEL_MAX;
byte value = 0;
if (wheel_pos < color_step)
{
value = wheel_pos;
return create_24bit_color_value(max, value * max / 255, 0); // red to orange to yellow
}
else if (wheel_pos < (color_step * 2))
{
wheel_pos -= color_step;
value = wheel_pos;
return create_24bit_color_value(max - value * max / 255, max, 0); // yellow to spring green to green
}
else if (wheel_pos < (color_step * 3))
{
wheel_pos -= (color_step * 2);
value = wheel_pos;
return create_24bit_color_value(0, max, value * max / 255); // green to turquiose to cyan
}
else if (wheel_pos < (color_step * 4))
{
wheel_pos -= (color_step * 3);
value = wheel_pos;
return create_24bit_color_value(0, max - value * max / 255, max); // cyan to ocean to blue
}
else if (wheel_pos < (color_step * 5))
{
wheel_pos -= (color_step * 4);
value = wheel_pos;
return create_24bit_color_value(value * max / 255, 0, max); // blue to violet to magenta
}
else if (wheel_pos < COLOR_WHEEL_MAX)
{
wheel_pos -= (color_step * 5);
value = wheel_pos;
return create_24bit_color_value(max, 0, max - value * max / 255); // magenta to raspberry to red
}
}
//return next color value in sequence (white fade-in/-out)
uint32_t white_fade(byte pos)
{
int value = pos;
value = value * 6;
return create_24bit_color_value(value, value, value);
}
//check whether array contains an integer value
boolean contains(int array[], int val)
{
for (int i = 0; i < diodes; i++)
{
if (array[i] == val)
{
return true;
}
}
return false;
}
//Works with global variables at the top. When a LED has finished its sequence,
// it uses this function to find a new LED.
void find_new_led(int diode_position)
{
int random_led = 0;
//If the random value is already present, choose a new one until a unique one is found
//definition of "contains" is below
do
{
random_led = random(0, leds_per_strand);
}
while (contains(diode_pos, random_led));
diode_pos[diode_position] = random_led;
}
void twinkle_setup(byte max)
{
fade_step = max / 20;
for (int i = 0; i < strip.numPixels()/10; i++)
{
twinkle_diodes[i] = random(0, strip.numPixels());
twinkle_diode_counter[i] = random(0, 41);
if (twinkle_diode_counter[i] < 21) // fade out
{
strip.setPixelColor(twinkle_diodes[i], big_wheel(colors[twinkle_diodes[i]], (20 - twinkle_diode_counter[i]) * fade_step));
}
else // fade in
{
strip.setPixelColor(twinkle_diodes[i], big_wheel(colors[twinkle_diodes[i]], fade_step * (twinkle_diode_counter[i] - 20)));
}
}
}
// Fade in or out some pixels in the colors array
void twinkle(byte max)
{
fade_step = max / 20;
for (int i = 0; i < strip.numPixels()/10; i++)
{
if (twinkle_diode_counter[i] < 21) // fade out
{
strip.setPixelColor(twinkle_diodes[i], big_wheel(colors[twinkle_diodes[i]], (20 - twinkle_diode_counter[i]) * fade_step));
}
else // fade in
{
strip.setPixelColor(twinkle_diodes[i], big_wheel(colors[twinkle_diodes[i]], fade_step * (twinkle_diode_counter[i] - 20)));
}
twinkle_diode_counter[i]++;
if (twinkle_diode_counter[i] > 41)
{
twinkle_diode_counter[i] = 0;
int random_led = 0;
do
{
random_led = random(0, strip.numPixels());
} while (contains(twinkle_diodes, random_led));
twinkle_diodes[i] = random_led;
}
}
}
bool mode_change()
{
return (stored_mode != current_mode);
}
void store_current_mode()
{
stored_mode = current_mode;
}
void reset_all_leds()
{
for (int i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, 0);
}
}
|
#pragma once
#include <Component.h>
namespace breakout
{
class TimerComponent : public BaseComponent
{
public:
static EComponentType GetType()
{
return EComponentType::Timer;
};
bool bActivated = false;
float m_Duration = 0.f;
float m_DecaySpeed = 0.f;
};
}
|
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#include "backend.hh"
#include <iostream>
#include <regex>
#include <stdexcept>
#include "storage/backend_local.hh"
#include "storage/backend_s3.hh"
#include "storage/backend_gs.hh"
#include "storage/backend_redis.hh"
#include "storage/backend_simpledb.hh"
#include "storage/backend_gg.hh"
#include "thunk/ggutils.hh"
#include "util/digest.hh"
#include "util/optional.hh"
#include "util/uri.hh"
#include "util/tokenize.hh"
using namespace std;
bool StorageBackend::is_available( const std::string & hash )
{
return roost::exists( remote_index_path_ / hash );
}
void StorageBackend::set_available( const std::string & hash )
{
roost::atomic_create( "", remote_index_path_ / hash );
}
unique_ptr<StorageBackend> StorageBackend::create_backend( const string & uri )
{
ParsedURI endpoint { uri };
unique_ptr<StorageBackend> backend;
if ( endpoint.protocol == "s3" ) {
backend = make_unique<S3StorageBackend>(
( endpoint.username.length() or endpoint.password.length() )
? AWSCredentials { endpoint.username, endpoint.password }
: AWSCredentials {},
endpoint.host,
endpoint.options.count( "region" )
? endpoint.options[ "region" ]
: "us-east-1" );
}
else if ( endpoint.protocol == "gs" ) {
backend = make_unique<GoogleStorageBackend>(
( endpoint.username.length() or endpoint.password.length() )
? GoogleStorageCredentials { endpoint.username, endpoint.password }
: GoogleStorageCredentials {},
endpoint.host );
}
else if ( endpoint.protocol == "redis" ) {
RedisClientConfig config;
config.ip = endpoint.host;
config.port = endpoint.port.get_or( config.port );
config.username = endpoint.username;
config.password = endpoint.password;
backend = make_unique<RedisStorageBackend>( config );
}
else if (endpoint.protocol == "sdb") {
SimpleDBClientConfig config;
if (endpoint.options.size() > 0)
{
config.num_ = (unsigned) stoul(endpoint.options["num"]);
for (unsigned i = 0; i < config.num_; i++)
{
string host;
uint16_t port = 8080;
auto parts = split(endpoint.options["host" + to_string(i)], ":");
host = parts[0];
if (parts.size() > 1)
port = (uint16_t) stoul(parts[1]);
config.address_.emplace_back(host, port);
}
}
else
{
config.num_ = 1;
config.address_.emplace_back(endpoint.host, endpoint.port.get_or(8080));
}
backend = make_unique<SimpleDBStorageBackend>(config);
}
else if (endpoint.protocol == "gg") {
uint16_t port = 8080;
GGObjectStoreConfig config( endpoint.host, endpoint.port.get_or( port ) );
backend = make_unique<GGStorageBackend>(config);
}
else {
throw runtime_error( "unknown storage backend" );
}
if ( backend != nullptr ) {
backend->remote_index_path_ = gg::paths::remote( digest::sha256( uri ) );
}
return backend;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define ll long long
#define fi first
#define se second
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))
#define FOREACH(a, b) for (auto&(a) : (b))
#define REP(i, n) FOR(i, 0, n)
#define REPN(i, n) FORN(i, 1, n)
#define dbg(x) cout << (#x) << " is " << (x) << endl;
#define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl;
#define dbgarr(x, sz) \
for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << ' '; \
cout << endl;
#define dbgarr2(x, rose, colin) \
for (int asdf2 = 0; asdf2 < rose; asdf2++) { \
dbgarr(x[asdf2], colin); \
}
#define dbgitem(x) \
for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << ' '; \
cout << endl;
const int mod = 1e9 + 7, dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
double pts[3][2], pi = 2 * acos(0.0);
struct Solution {
double solve() {
auto a = dist(pts[0][0], pts[0][1], pts[1][0], pts[1][1]), b = dist(pts[2][0], pts[2][1], pts[1][0], pts[1][1]), c = dist(pts[0][0], pts[0][1], pts[2][0], pts[2][1]);
double s = (a + b + c) / 2, r = a * b * c / (4 * sqrt(s * (s - a) * (s - b) * (s - c)));
double A = acos((b * b + c * c - a * a) / (2 * b * c)), B = acos((a * a + c * c - b * b) / (2 * a * c)), C = acos((a * a + b * b - c * c) / (2 * a * b));
double g = gcd(gcd(A, B), C), n = pi / g;
// dbg(g);
return r * r * n / 2 * sin(2 * pi / n);
}
double gcd(double x, double y) {
return fabs(y) < 0.0001 ? x : gcd(y, fmod(x, y));
}
double dist(double x1, double y1, double x2, double y2) {
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
REP(i, 3)
cin >> pts[i][0] >> pts[i][1];
Solution test;
cout << fixed << setprecision(7) << test.solve() << endl;
}
|
#include <string>
#include <sstream>
#include <map>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string.h>
#ifndef _VOCAB_H
#define _VOCAB_H
namespace vcb
{
enum list{csys, mnemoSchema, log, plot,
main, lockers, recipe, systema,
sources, gases, valves, pumps,
opend, closed, control, error,
open_cmd, close_cmd, init_cmd, shutter,
ETMOP, ETMCL, EBNOP, EBNCL, ECMD, ETMNC,
air, argon, oxygen, lnk,
TMERR, CSERR, PRERR,
freqHz, thickA, rateAs, tempC,
tool, mat, out, in, presMb,
ctrl1, ctrl2, middle, ETMMD, EBNMD,
SPERR, RGERR, NOLNK, WRERR,
full_speed, start_cmd, stop_cmd,
ETMON, ETMOF, INERR,
set, reset, DEVERR
};
struct vocab:std::map<unsigned int, const char*>
{
vocab();
static vocab& get();
};
}
#endif
|
/**
******************************************************************************
* @file grab_stream.cpp
* @author FrankChen
* @version V1.0.1
* @date 28-May-2016
* @brief This file provides basic funtion that grab video stream from video device/file or ros message.
* and provide preview window that from input stream and output stream.
* This programme also support ros launch file parameter set.
* @TODO add Gige Vision grab feature
******************************************************************************
*/
//include ros library
#include "ros/ros.h"
//include std/string libraries
#include<sstream>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
//include messege libraries
#include "sensor_msgs/image_encodings.h"
#include "image_transport/image_transport.h"
#include "cv_bridge/cv_bridge.h"
//include opencv libraries
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/calib3d/calib3d.hpp"
using namespace cv;
using namespace std;
#define TOPICT
image_transport::Publisher image_pub;
image_transport::Subscriber image_sub;
void usage()
{
printf( "This is a video stream grab programm. \n"
"Usage: Grab Stream\n"
" -s <source device/file> #Video Device Index or video file path \"default <-1 or path/video.avi>\"\n"
" -i <camera instrinsic file> #The Camera Intrinsic File \"default <path/calibration.yml>\"\n"
" -ri <ROS topic in> #ROS topic input \"default <camera/in>\"\n"
" -ro <ROS topic out> #ROS topic output \"default <camera/out>\"\n"
" -rp <ROS Launch para> #Get parameter from launch file \"default <false>\"\n"
" Expert option. [Warn]: set these parameter may cause image quality bad!\n"
" -w <width> #video width \"default <640>\"\n"
" -h <height> #video height \"default <480>\"\n"
" [-e <exposure>] \n"
" [-b <brightness>] \n"
" [-c <contrast>] \n"
" [-s <saturation>] \n"
" [-h <hue>] \n"
" [-g <gain>] \n"
);
}
void imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
Mat image_in;
cv_bridge::CvImage image_msg;
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8);
image_in = cv_ptr -> image;
image_msg.image = image_in;
image_msg.header.stamp = ros::Time::now();
image_msg.encoding = "bgr8";
image_pub.publish(image_msg.toImageMsg());
}
int main(int argc,char **argv)
{
ros::init(argc, argv, "grab_stream");
ros::NodeHandle n,nh;
image_transport::ImageTransport it(nh);
int CAMERA_INDEX = -1;
const char* inputfile = "video.avi";
const char* TheIntrinsicFile = "calibration.yml";
string ros_in_topic = "/camera/in",ros_out_topic = "/camera/out";
bool read_ros = false;
bool is_device = false;
bool enable_topic_transport = false;
bool enable_undistort = false ;
int width;
int height;
double exposure;
double brightness;
double contrast;
double saturation;
double hue;
double gain;
if(argc <= 1)
{
usage();
return 0;
}
/**************************************************************************
* get parameter from command line.
*
* ***********************************************************************/
for(int i = 1; i < argc; i++)
{
const char* s = argv[i];
if(strcmp( s, "-s" ) == 0)
{
char* ss = argv[++i];
if( isdigit(ss[0]) )
{
sscanf( argv[i], "%d", &CAMERA_INDEX );
is_device = true;
}
else
inputfile = argv[i];
}
else if(strcmp( s, "-i" ) == 0)
{
TheIntrinsicFile = argv[++i];
enable_undistort = true;
}
else if(strcmp( s, "-ri" ) == 0)
{
ros_in_topic = argv[++i];
enable_topic_transport = true;
}
else if(strcmp( s, "-ro" ) == 0)
{
ros_out_topic = argv[++i];
}
else if(strcmp( s, "-rp" ) == 0)
{
if(strcmp( argv[++i], "true" ))
read_ros = true;
}
else if(strcmp( s, "-w" ) == 0)
{
sscanf( argv[++i], "%d", &width );
}
else if(strcmp( s, "-h" ) == 0)
{
sscanf( argv[++i], "%d", &height );
}
else if(strcmp( s, "-e" ) == 0)
{
sscanf( argv[++i], "%lf", &exposure );
}
else if(strcmp( s, "-b" ) == 0)
{
sscanf( argv[++i], "%lf", &brightness );
}
else if(strcmp( s, "-c" ) == 0)
{
sscanf( argv[++i], "%lf", &contrast );
}
else if(strcmp( s, "-s" ) == 0)
{
sscanf( argv[++i], "%lf", &saturation );
}
else if(strcmp( s, "-h" ) == 0)
{
sscanf( argv[++i], "%lf", &hue );
}
else if(strcmp( s, "-g" ) == 0)
{
sscanf( argv[++i], "%lf", &gain );
}
else if(strcmp( s, "-help" ) == 0)
{
usage();
return 0;
}
else
{
printf("Unknow parameter.\n");
usage();
}
}
if(read_ros)
{
nh.param("width", width, int(640));
nh.param("height", height, int(480));
nh.param("exposure", exposure, double(0.2));//0.2
nh.param("brightness", brightness, double(0.5));//0.2
nh.param("contrast", contrast, double(0.6));//0.6
nh.param("saturation", saturation, double(0.5));//0.2
nh.param("hue", hue, double(0.5));//0.15
nh.param("gain", gain, double(0.5));//0.2
}
cv_bridge::CvImagePtr imagePtr;
cv_bridge::CvImage image_out_msg;
image_pub = it.advertise(ros_out_topic, 10);
image_sub = it.subscribe(ros_in_topic , 10, imageCallback);
#ifdef TOPICT
VideoCapture capture;
if( is_device )
{
capture.open(CAMERA_INDEX);
cout<<"open camera device "<<CAMERA_INDEX<<endl;
}
else
{
capture.open(inputfile);
cout<<"open file "<<inputfile<<endl;
}
if( !capture.isOpened())
return fprintf( stderr, "Could not initialize video capture\n"), -2;
// capture.set(CV_CAP_PROP_FOURCC ,CV_FOURCC('M', 'J', 'P', 'G') );
capture.set(CV_CAP_PROP_FRAME_WIDTH ,width);
capture.set(CV_CAP_PROP_FRAME_HEIGHT ,height);
// capture.set(CV_CAP_PROP_EXPOSURE ,exposure);
// capture.set(CV_CAP_PROP_BRIGHTNESS ,brightness);
// capture.set(CV_CAP_PROP_CONTRAST,contrast);
// capture.set(CV_CAP_PROP_SATURATION,saturation);
// capture.set(CV_CAP_PROP_HUE,hue);
// capture.set(CV_CAP_PROP_GAIN,gain);
// capture.set(CV_CAP_PROP_FPS, 25);
#endif
// ros::Subscribler image_sub = n.advertise<geometry_msgs::Vector3>("board_pos",20);
// ros::Publisher camera_pub = n.advertise<geometry_msgs::PoseStamped>("board_pose",20);
// ros::Publisher aux_pub = n.advertise<geometry_msgs::Vector3>("board_rot",20);
//********************read intrinsic file******************************
Mat CM = Mat(3, 3, CV_32FC1);
Mat D;
//************************undistort*********************************
Mat map1,map2;
Mat image;
#ifdef TOPICT
capture >> image;
#endif
if(enable_undistort)
{
FileStorage fs2(TheIntrinsicFile,FileStorage::READ);
fs2["camera_matrix"]>>CM;
fs2["distortion_coefficients"]>>D;
fs2.release();
cout<<"CM: "<<CM<<endl<<"D: "<<D<<endl;
initUndistortRectifyMap(CM,D,Mat(),Mat(),image.size(),CV_32FC1,map1,map2);
}
ros::Rate loopRate(30);
while(nh.ok() && waitKey(30) != 'c' )
{
if(!enable_topic_transport)
{
#ifdef TOPICT
capture >> image;
imshow("image_show",image);
#endif
image_out_msg.image = image;
image_out_msg.header.stamp = ros::Time::now();
image_out_msg.encoding = "bgr8";
image_pub.publish(image_out_msg.toImageMsg());
}
ros::spinOnce();
loopRate.sleep();
}
}
|
#ifndef PLATY_LOG_H
#define PLATY_LOG_H
//#define LOG
#include <exception>
#include <string>
#include <Windows.h>
namespace Platy
{
/// <summary>
/// Singleton class for logging and debugging
/// </summary>
class Log
{
public:
Log() = delete;
~Log();
/// <summary>
/// Initializes logger. Should only be called once in a program
/// </summary>
static void Init();
/// <summary>
/// Disposes logger. Should be called at end of program
/// </summary>
static void Dispose();
#pragma region Debug
/// <summary>
/// Logs debug message
/// </summary>
/// <param name="msg">Message</param>
static void Debug(const std::string& msg);
#pragma endregion Debug
#pragma region Warning
/// <summary>
/// Logs warning
/// </summary>
/// <param name="msg">Message</param>
static void Warning(const std::string& msg);
/// <summary>
/// Logs warning
/// </summary>
/// <param name="e">Any caught exception</param>
/// <param name="msg">Message</param>
static void Warning(const std::exception& e,
const std::string& msg);
#pragma endregion Warning
#pragma region Critical
/// <summary>
/// Logs critical error
/// </summary>
/// <param name="msg">Message</param>
static void Critical(const std::string& msg);
/// <summary>
/// Logs critical error
/// </summary>
/// <param name="e">Any caught exception</param>
/// <param name="msg">Message</param>
static void Critical(const std::exception& e,
const std::string& msg);
#pragma endregion Critical
#pragma region Information
/// <summary>
/// Logs information
/// </summary>
/// <param name="msg">Message</param>
static void Information(const std::string& msg);
#pragma endregion Information
private:
static HANDLE myConsoleHandle;
enum class ELogHeader
{
CRITICAL,
DEBUG,
INFORMATION,
WARNING,
};
#pragma region Private Helpers Methods
static uint16_t HeaderToColour(const ELogHeader& head) noexcept;
static std::string HeaderToString(const ELogHeader& head) noexcept;
static void WriteInColour(const ELogHeader& head, const std::string& str);
static void WriteLogMsg(ELogHeader head, const std::string& msg);
#pragma endregion Private Helper Methods
};
}
#endif
|
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "source.h"
#include "globals.h"
char g_recvbuf[g_DEF_BUFLEN];
struct ResponseValues {
char statusCode[20];
char contentType[30];
char connStatus[20];
char msgBody[100];
char msgLen[5];
ResponseValues(const char *statusCode, const char *contentType, const char *connStatus, const char *msgBody, const char *msgLen) {
strcpy(this->statusCode, statusCode);
strcpy(this->contentType, contentType);
strcpy(this->connStatus, connStatus);
strcpy(this->msgBody, msgBody);
strcpy(this->msgLen, msgLen);
}
};
int main() {
signal(SIGINT, exceptionHandler);
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (checkWinsockError(iResult, "WSA Startup error")) return 1;
const char DEF_PORT[] = "8888";
struct addrinfo *result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL, DEF_PORT, &hints, &result);
if (checkWinsockError(iResult, "getaddrinfo error", false, WSACleanup)) return 1;
SOCKET ListenSocket = INVALID_SOCKET;
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (checkWinsockError(ListenSocket, "Socket Error", true, WSACleanup, result, nullptr, true)) return 1;
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (checkWinsockError(iResult, "Bind Error", true, WSACleanup, result, &ListenSocket)) return 1;
freeaddrinfo(result);
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
callWinsockError(0, "Listen Error", true, WSACleanup, nullptr, &ListenSocket);
return 1;
}
ResponseValues values("200 OK", "text/html", "Closed", "<html>\r\n<head>\r\n</head>\r\n<body>\r\n<h1>Carpe Diem!:(</h1>\r\n</body>\r\n</html>", "82");
static SOCKET *ClientSocket = new SOCKET;
*ClientSocket = INVALID_SOCKET;
printf("Socket on initialisation: %d\n", ClientSocket);
Client* iPhone = new Client(ClientSocket, &ListenSocket);
while (!g_exit) {
printf("Socket before accept: %d\n", ClientSocket);
printf("Socket pointer before accept: %d\n", *ClientSocket);
if (iPhone->acceptConn()) return 1;
printf("Socket after accept: %d\n", ClientSocket);
// printf("Socket pointer after accept: %d\n", *ClientSocket);
printf("Socket reference after accept: %d\n", &ClientSocket);
iResult = iPhone->recvData(ClientSocket);
printf("error: %d\n", WSAGetLastError());
while (iPhone->checkMsg(iResult) == 0) {
iPhone->sendData(values.statusCode, values.contentType, values.connStatus, values.msgBody, values.msgLen);
iResult = iPhone->recvData(ClientSocket);
}
printf("\nerror: %d\n", WSAGetLastError());
printf("Socket before shutdown: %d\n", ClientSocket);
iResult = shutdown(*ClientSocket, SD_SEND);
if (checkWinsockError(iResult, "Shutdown Error", true, WSACleanup, nullptr, ClientSocket)) return 1;
closesocket(*ClientSocket);
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
callWinsockError(0, "Listen Error", true, WSACleanup, nullptr, &ListenSocket);
return 1;
}
/*
ClientSocket = new SOCKET;
*ClientSocket = INVALID_SOCKET;
iPhone->setClient(*ClientSocket);
*/
printf("Socket initialised in new memory: %d\n", ClientSocket);
printf("Socket pointer initialised in new memory: %d\n", *ClientSocket);
}
delete ClientSocket;
WSACleanup();
printf("complete");
HangCMD();
delete iPhone;
return 0;
}
|
class TrieNode
{
public:
TrieNode *next[26];
bool is_word;
// Initialize your data structure here.
TrieNode()
{
memset(next, 0, sizeof(next));
is_word = false;
}
};
class Trie
{
TrieNode *root;
public:
Trie()
{
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string s)
{
TrieNode *p = root;
for(int i = 0; i < s.size(); ++ i)
{
if(p -> next[s[i] - 'a'] == NULL)
p -> next[s[i] - 'a'] = new TrieNode();
p = p -> next[s[i] - 'a'];
}
p -> is_word = true;
}
// Returns if the word is in the trie.
bool search(string key)
{
TrieNode *p = find(key);
return p != NULL && p -> is_word;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix)
{
return find(prefix) != NULL;
}
private:
TrieNode* find(string key)
{
TrieNode *p = root;
for(int i = 0; i < key.size() && p != NULL; ++ i)
p = p -> next[key[i] - 'a'];
return p;
}
};
// one format
class TrieNode {
public:
// Initialize your data structure here.
TrieNode* children[26];
bool isLeaf;
TrieNode() {
memset(children,0,sizeof(children));
isLeaf = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode* p = root;
for(int i = 0; i < word.length(); ++i){
int x = word[i] - 'a';
if(p->children[x] == NULL){
p->children[x] = new TrieNode();
}
p = p->children[x];
}
p->isLeaf = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* p = root;
for(int i = 0; i < word.length(); ++i){
int x = word[i] - 'a';
if(p->children[x] == NULL)
return false;
p = p->children[x];
}
return p->isLeaf;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
int len = prefix.length();
TrieNode* p = root;
for(int i = 0; i < len; ++i){
int x = prefix[i] -'a';
if(p->children[x] == NULL)
return false;
p = p->children[x];
}
return true;
}
private:
TrieNode* root;
};
|
#pragma once
#ifndef CZECHREPUBLIC_HPP
#define CZECHREPUBLIC_HPP
#include "Country.hpp"
/*************************************************************************
* class CzechRepublic
* This is a derived class from Country.
*************************************************************************/
class CzechRepublic : public Country
{
private:
bool moveOn;
bool optionA, optionB, optionC;
bool telescopeFound;
bool bikeSpotted;
bool bike;
public:
CzechRepublic();
~CzechRepublic();
virtual void explore(Player *p);
virtual void hostel(Player *p);
char menu1();
char menu2();
};
#endif
|
#include <mutiplex/TcpServer.h>
#include <mutiplex/CircularBuffer.h>
#include <mutiplex/Connection.h>
#include <mutiplex/ByteBuffer.h>
using namespace muti;
#define NUM_THREADS 1
class EchoServer
{
public:
EchoServer(const std::string& addr)
: server_(addr, NUM_THREADS)
{
ReadCallback cb = [this](ConnectionPtr conn, ByteBuffer* buf, uint64_t timestamp) {
this->hande_read(conn, buf, timestamp);
};
server_.set_established_callback([](ConnectionPtr conn, uint64_t timestamp){
fprintf(stderr, "new connection %s -> %s\n", conn->peer_address().to_string().c_str(), conn->local_address().to_string().c_str());
});
server_.set_read_callback(cb);
}
void run()
{
server_.run();
}
private:
void hande_read(ConnectionPtr conn, ByteBuffer* buf, uint64_t timestamp)
{
conn->write(buf->data(), buf->remaining());
}
TcpServer server_;
};
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("usage %s <addr>\n", argv[0]);
return -1;
}
EchoServer server(argv[1]);
server.run();
}
|
//
// LandruActorAssembler.cpp
// Landru
//
// Created by Nick Porcino on 9/2/14.
//
//
#include "Landru/Landru.h"
#include "LandruActorAssembler.h"
#include "LandruActorVM/Fiber.h"
#include "LandruActorVM/Generator.h"
#include "LandruActorVM/Library.h"
#include "LandruActorVM/MachineDefinition.h"
#include "LandruActorVM/Property.h"
#include "LandruActorVM/State.h"
#include "LandruActorVM/StdLib/StdLib.h"
#include "LandruActorVM/VMContext.h"
#include "LandruActorVM/WiresTypedData.h"
#include "LabText/TextScanner.hpp"
#ifdef LANDRU_HAVE_BSON
#include "LabJson/LabBson.h"
#endif
#include <algorithm>
#include <cassert>
#include <cmath>
#include <exception>
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
#include <cstdlib>
using namespace std;
using Lab::Bson;
namespace Landru {
//-------------------
// assembler context \______________________________________________
class ActorAssembler::Context {
public:
// the result of the assembly
//
map<string, shared_ptr<MachineDefinition>> machineDefinitions;
//
// current state of assembly
//
Library* libs = nullptr;
map<string, string> requireAliases;
shared_ptr<MachineDefinition> currMachineDefinition;
vector<State*> currState;
vector<vector<Instruction>*> currInstr;
struct Conditional {
Conditional() : op(Op::unknown) {}
enum class Op { unknown, eq, eq0, lte0, gte0, lt0, gt0, neq0 };
Op op;
vector<Instruction> conditionalInstructions;
vector<Instruction> contraConditionalInstructions;
};
vector<shared_ptr<Conditional>> currConditional;
vector<pair<string, string>> localVariables; // vector[name-> name,type]
vector<int> localVariableState;
//
Context(Library* l) : libs(l) {}
~Context() {}
void beginMachine(const char* name) {
currMachineDefinition = make_shared<MachineDefinition>();
currMachineDefinition->name.assign(name);
machineDefinitions[currMachineDefinition->name] = currMachineDefinition;
}
void endMachine() {
if (!currState.empty())
AB_RAISE("badly formed state" << currState.back()->name);
if (!currConditional.empty())
AB_RAISE("badly formed conditional");
currMachineDefinition = nullptr;
}
void beginState(const char* name) {
State *s = new State();
s->name = name;
currMachineDefinition->states[s->name] = s;
currState.emplace_back(s);
currInstr.emplace_back(&s->instructions);
}
void endState() {
currState.pop_back();
currInstr.pop_back();
}
int localVariableIndex(const char* name) {
if (localVariables.empty())
return -1;
// parameters were parsed in order into the vector;
// they are indexed backwards from the local stack frame, so if the parameters were a, b, c
// the runtime indices are a:2 b:1 c:0
// search from most recently pushed because of scoping, eg in this case
// for x in range(): for y in range(): local real x ...... ; ;
// the innermost x should be found within the y loop, and the outermost in the x loop
int m = (int)localVariables.size() - 1;
for (int i = m; i >= 0; --i)
if (!strcmp(name, localVariables[i].first.c_str()))
return i;
return -1;
}
};
ActorAssembler::ActorAssembler(Library* l) : _context(new Context(l)) {}
ActorAssembler::~ActorAssembler() {}
Library* ActorAssembler::library() const {
return _context->libs;
}
const std::map<std::string, std::shared_ptr<MachineDefinition>>& ActorAssembler::assembledMachineDefinitions() const {
return _context->machineDefinitions;
}
const std::map<std::string, std::shared_ptr<Landru::Property>>& ActorAssembler::assembledGlobalVariables() const {
return globals;
}
void ActorAssembler::beginMachine(const char* name) {
_context->beginMachine(name);
}
void ActorAssembler::endMachine() {
_context->endMachine();
}
void ActorAssembler::beginState(const char *name) {
_context->beginState(name);
}
void ActorAssembler::endState() {
_context->endState();
}
void ActorAssembler::beginConditionalClause() {
}
void ActorAssembler::beginContraConditionalClause() {
_context->currInstr.pop_back();
_context->currInstr.emplace_back(&_context->currConditional.back()->contraConditionalInstructions);
}
void ActorAssembler::endConditionalClause() {
_context->currInstr.pop_back();
shared_ptr<Context::Conditional> conditional = _context->currConditional.back();
_context->currConditional.pop_back();
switch (conditional->op) {
case Context::Conditional::Op::unknown:
break;
case Context::Conditional::Op::eq:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
float test1 = run.self->pop<float>();
float test2 = run.self->pop<float>();
RunState runstate = RunState::Continue;
if (run.vm->traceEnabled) {
if (test1 == test2) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test1 == test2) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::Eq"));
break;
case Context::Conditional::Op::eq0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test == 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test == 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::Eq0"));
break;
case Context::Conditional::Op::lte0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test <= 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test <= 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::lte0"));
break;
case Context::Conditional::Op::gte0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test >= 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test >= 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::gte0"));
break;
case Context::Conditional::Op::lt0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test < 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test < 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::lte0"));
break;
case Context::Conditional::Op::gt0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test > 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test > 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::gte0"));
break;
case Context::Conditional::Op::neq0:
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState {
RunState runstate = RunState::Continue;
float test = run.self->pop<float>();
if (run.vm->traceEnabled) {
if (test != 0) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else {
for (auto i : conditional->contraConditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
}
else {
if (test != 0) {
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
else {
for (auto i : conditional->contraConditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
return runstate;
}, "Op::neq0"));
break;
}
}
void ActorAssembler::beginForEach(const char *name, const char *type) {
// for each will call Run as if executing substates
// in the case of for body in bodies, type will be varobj and name will be body
// the local parameters will be created, pushed, and cleaned up by the forEach instruction itself
//
_context->localVariables.emplace_back(make_pair(name, type));
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
}
void ActorAssembler::endForEach()
{
shared_ptr<Context::Conditional> conditional = _context->currConditional.back();
_context->currConditional.pop_back();
_context->currInstr.pop_back();
_context->currInstr.back()->emplace_back(Instruction([conditional](FnContext& run)->RunState
{
RunState runstate = RunState::Continue;
auto genVarPtr = run.self->popVar();
auto generatorVar = reinterpret_cast<Wires::Data<shared_ptr<Generator>>*>(genVarPtr.get());
auto generator = generatorVar->value();
auto factory = run.vm->libs->findFactory(generator->typeName());
auto local = factory();
auto var = run.self->push_local(std::string("gen"), std::string(generator->typeName()), factory, local);
for (generator->begin(); !generator->done(); generator->next())
{
generator->generate(var.get());
if (run.vm->traceEnabled) {
for (auto& i : conditional->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else
for (auto& i : conditional->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
generator->finalize(run);
}
run.self->pop_local(); // discard the local variable
return runstate;
}, "endForEach"));
_context->localVariables.pop_back();
}
void ActorAssembler::beginOn() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
// the instructions compiled next will be the on clause, for example
// on time.after(3)
}
void ActorAssembler::beginOnStatements() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
// the statements following are what to do when the on clause is satisfied
}
void ActorAssembler::endOnStatements() {
shared_ptr<Context::Conditional> onStatements = _context->currConditional.back();
_context->currConditional.pop_back();
_context->currInstr.pop_back();
shared_ptr<Context::Conditional> onStatement = _context->currConditional.back();
_context->currConditional.pop_back();
_context->currInstr.pop_back();
_context->currInstr.back()->emplace_back(Instruction([onStatement, onStatements](FnContext& run)->RunState
{
RunState runstate = RunState::Continue;
// push the statements to execute if the on fires
run.self->stack.back().emplace_back(make_shared<Wires::Data<vector<Instruction>>>(onStatements->conditionalInstructions));
// the on-statement must consume the on-statements
if (run.vm->traceEnabled) {
for (auto& i : onStatement->conditionalInstructions) {
i.second.exec(run);
if ((runstate = i.first(run)) != RunState::Continue)
break;
}
}
else
for (auto& i : onStatement->conditionalInstructions)
if ((runstate = i.first(run)) != RunState::Continue)
break;
return runstate;
}, "endOn"));
}
void ActorAssembler::paramsStart() {
}
void ActorAssembler::paramsEnd() {
}
void ActorAssembler::beginLocalVariableScope() {
_context->localVariableState.emplace_back(0);
}
void ActorAssembler::addLocalVariable(const char* name, const char* type)
{
string nStr(name);
string tStr(type);
_context->localVariables.emplace_back(make_pair(name, type));
_context->currInstr.back()->emplace_back(Instruction([nStr, tStr](FnContext& run)->RunState
{
auto factory = run.vm->libs->findFactory(tStr.c_str());
auto local = factory();
run.self->push_local(nStr, tStr, factory, local);
return RunState::Continue;
}, "addLocalVariable"));
}
void ActorAssembler::endLocalVariableScope() {
int localsCount = _context->localVariableState[_context->localVariableState.size() - 1];
_context->localVariableState.pop_back();
for (int i = 0; i < localsCount; ++i)
_context->localVariables.pop_back();
_context->currInstr.back()->emplace_back(Instruction([localsCount](FnContext& run)->RunState
{
for (int i = 0; i < localsCount; ++i)
run.self->locals.pop_back();
return RunState::Continue;
}, "endLocalVariableScope"));
}
void ActorAssembler::addRequire(const char* name, const char* module)
{
_context->requireAliases[name] = module;
}
std::vector<std::string> ActorAssembler::requires()
{
std::vector<std::string> r;
for (auto i : _context->requireAliases)
r.push_back(i.second);
return r;
}
void ActorAssembler::callFunction(const char *fnName)
{
string f(fnName);
vector<string> parts = TextScanner::Split(f, string("."));
if (parts.size() == 0)
AB_RAISE("Invalid function name" << f);
enum class CallOn {
callOnSelf, callOnProperty, callOnRequire
};
CallOn callOn = CallOn::callOnSelf;
int index = 0;
while (index < parts.size() - 1) {
if (_context->currMachineDefinition->properties.find(parts[index]) != _context->currMachineDefinition->properties.end()) {
callOn = CallOn::callOnProperty;
break;
}
if (_context->requireAliases.find(parts[index]) != _context->requireAliases.end()) {
callOn = CallOn::callOnRequire;
break;
}
if (globals.find(parts[index]) != globals.end()) {
callOn = CallOn::callOnProperty;
break;
}
AB_RAISE("Unknown identifier " << parts[index] << " while parsing " << fnName);
}
// finally got to a function to call
switch (callOn) {
case CallOn::callOnSelf: {
Library::Vtable const*const lib = _context->libs->findVtable("fiber");
if (!lib) {
AB_RAISE("No library named fiber exists");
}
auto fnEntry = lib->function(parts[index].c_str());
if (!fnEntry)
AB_RAISE("Function named \"" << parts[index] << "\" does not exist on library: fiber");
auto fn = fnEntry->fn;
string str = "self call to " + parts[index];
_context->currInstr.back()->emplace_back(Instruction([fn, str](FnContext& run)->RunState
{
return fn(run);
}, str.c_str()));
break;
}
case CallOn::callOnRequire: {
auto requiresDef = _context->requireAliases.find(parts[0]);
if (requiresDef == _context->requireAliases.end()) {
// don't allow use of libs unless referenced by a require statement
AB_RAISE("Can't find require library " << parts[0]);
}
int partIndex = 1;
Library::Vtable const* lib = nullptr;
if (parts.size() == 1) {
lib = _context->libs->findVtable(parts[0].c_str());
if (!lib)
AB_RAISE("No std library named " << parts[0] << " exists");
}
else if (parts.size() == 2) {
lib = _context->libs->findVtable(parts[0].c_str());
if (!lib)
for (auto& i : _context->libs->libraries) {
if (i.name == parts[0]) {
lib = i.findVtable(parts[0].c_str());
if (!lib)
AB_RAISE("No vtable for library named " << parts[0]);
}
}
}
else {
std::vector<Library> * libraries = &_context->libs->libraries;
Library * l = nullptr;
for (int part = 0; part < parts.size() - 1; ++part) {
bool found = false;
for (auto& i : *libraries) {
if (i.name == parts[part]) {
libraries = &i.libraries;
l = &i;
found = true;
break;
}
}
if (!found)
AB_RAISE("Couldn't find function " << f);
}
lib = l->findVtable(parts[parts.size() - 2].c_str());
if (!lib)
AB_RAISE("Couldn't find function in " << parts[parts.size() - 2]);
partIndex = int(parts.size()) - 1;
}
auto fnEntry = lib->function(parts[partIndex].c_str());
if (!fnEntry)
AB_RAISE("Function " << parts[partIndex] << " does not exist on library: " << parts[0]);
auto fn = fnEntry->fn;
string str = "library call on " + parts[0] + " to " + parts[partIndex];
string libraryName = lib->name;
_context->currInstr.back()->emplace_back(Instruction([fn, libraryName](FnContext& run)->RunState
{
FnContext fnRun(run);
return fn(fnRun);
}, str.c_str()));
break;
}
case CallOn::callOnProperty:
auto machineProperty = _context->currMachineDefinition->properties.find(parts[0]);
string type;
if (machineProperty == _context->currMachineDefinition->properties.end()) {
auto globalProperty = globals.find(parts[0]);
if (globalProperty == globals.end())
AB_RAISE("Property " << parts[0] << " not found for function call " << f);
type = globalProperty->second->type;
}
else
type = machineProperty->second->type;
vector<string> typeParts = TextScanner::Split(type, ".");
if (typeParts.size() == 0) {
// type must be a std type
Library::Vtable const*const lib = _context->libs->findVtable(typeParts[0].c_str());
if (!lib) {
AB_RAISE("No std library named " << typeParts[0] << " exists for function call " << f << " on property of type " << type);
}
AB_RAISE("@TODO callOnProperty");
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
// we know what the lambda to call is, but we're going to have to look up the property named parts[0] at runtime
// call function on require parts[index] and then clear the params
// &&& @TODO
return RunState::UndefinedBehavior;
}, "callOnStdProperty"));
}
else {
bool found = false;
for (auto& i : _context->libs->libraries) {
if (i.name == typeParts[0]) {
// found the right library, find the vtable on the library, eg audio.buffer
Library::Vtable const*const lib = i.findVtable(typeParts[1].c_str());
if (!lib)
AB_RAISE("No library named " << typeParts[0] << " exists for function call " << f << " on property of type " << type);
auto fnEntry = lib->function(parts[1].c_str());
if (!fnEntry)
AB_RAISE("Function " << parts[1] << " does not exist on library: " << parts[0]);
auto fn = fnEntry->fn;
string str = "library call on property '" + parts[0] + "' to " + type + "." + parts[1];
string propertyName = parts[0];
string libName = i.name;
_context->currInstr.back()->emplace_back(Instruction([propertyName, libName, fn](FnContext& run)->RunState
{
FnContext fnRun(run);
auto property = run.vm->findInstance(run.self, propertyName);
if (!property) {
property = run.vm->findGlobal(propertyName);
if (!property)
VM_RAISE("Couldn't find property: " << propertyName);
}
fnRun.var = property->data.get();
return fn(fnRun);
}, str.c_str()));
found = true;
break;
}
}
if (!found)
AB_RAISE("No library named " << typeParts[0] << " exists for function call " << f << " on property of type " << type);
}
break;
}
}
void ActorAssembler::storeToVar(const char *name)
{
/// @TODO need to decompose name, discover where the variable is and store the appropriate lambda
string parts(name);
string str = "store to " + parts;
// prefer the local scope
int localIndex = _context->localVariableIndex(name);
if (localIndex >= 0)
{
_context->currInstr.back()->emplace_back(Instruction([localIndex](FnContext& run)->RunState
{
auto data = run.self->popVar();
run.self->locals[localIndex]->assign(data, true);
return RunState::Continue;
}, str.c_str()));
}
else if (_context->currMachineDefinition->properties.find(parts) != _context->currMachineDefinition->properties.end())
{
_context->currInstr.back()->emplace_back(Instruction([parts, str](FnContext& run)->RunState
{
auto prop = run.vm->findInstance(run.self, parts); // already checked at compile time
auto data = run.self->popVar();
prop->copy(data, true);
return RunState::Continue;
}, str.c_str()));
}
else {
auto global_iter = globals.find(parts);
if (global_iter != globals.end()) {
_context->currInstr.back()->emplace_back(Instruction([parts, str](FnContext& run)->RunState
{
auto prop = run.vm->findGlobal(parts); // already checked at compile time
auto data = run.self->popVar();
prop->copy(data, true);
return RunState::Continue;
}, str.c_str()));
}
else
AB_RAISE("Couldn't find variable: " << string(name));
}
}
void ActorAssembler::initializeSharedVarIfNecessary(const char * name)
{
/// @TODO need to decompose name, discover where the variable is and store the appropriate lambda
string parts(name);
string str = "initialize shared var " + parts;
if (_context->currMachineDefinition->properties.find(parts) == _context->currMachineDefinition->properties.end()) {
AB_RAISE("Couldn't find shared variable: " << string(name));
return;
}
_context->currInstr.back()->emplace_back(Instruction([parts, str](FnContext& run)->RunState
{
auto prop = run.vm->findInstance(run.self, parts); // already checked at compile time
auto data = run.self->popVar();
if (!prop->assignCount) {
prop->data->copy(data.get());
++prop->assignCount;
}
return RunState::Continue;
}, str.c_str()));
}
void ActorAssembler::addGlobal(const char* name, const char* type)
{
TypeFactory factory = library()->findFactory(type);
std::shared_ptr<Property> prop = std::make_shared<Property>(factory);
prop->name.assign(name);
prop->type.assign(type);
prop->visibility = Property::Visibility::Global;
globals[name] = prop;
}
#ifdef LANDRU_HAVE_BSON
void ActorAssembler::addGlobalBson(const char *name, std::shared_ptr<Lab::Bson> bson)
{
TypeFactory factory = library()->findFactory("bson");
std::shared_ptr<Property> prop = std::make_shared<Property>(factory);
prop->name.assign(name);
prop->type.assign("bson");
prop->visibility = Property::Visibility::Global;
std::shared_ptr<Wires::TypedData> val = std::make_shared<Wires::Data<std::shared_ptr<Lab::Bson>>>(bson);
prop->assign(val, false);
globals[name] = prop;
}
#endif
void ActorAssembler::addGlobalString(const char* name, const char* value) {
TypeFactory factory = library()->findFactory("string");
std::shared_ptr<Property> prop = std::make_shared<Property>(factory);
prop->name.assign(name);
prop->type.assign("string");
prop->visibility = Property::Visibility::Global;
std::shared_ptr<Wires::TypedData> val = std::make_shared<Wires::Data<std::string>>(string(value));
prop->assign(val, false);
globals[name] = prop;
}
void ActorAssembler::addGlobalInt(const char* name, int value) {
TypeFactory factory = library()->findFactory("int");
std::shared_ptr<Property> prop = std::make_shared<Property>(factory);
prop->name.assign(name);
prop->type.assign("int");
prop->visibility = Property::Visibility::Global;
std::shared_ptr<Wires::TypedData> val = std::make_shared<Wires::Data<int>>(value);
prop->assign(val, false);
globals[name] = prop;
}
void ActorAssembler::addGlobalFloat(const char* name, float value) {
TypeFactory factory = library()->findFactory("float");
std::shared_ptr<Property> prop = std::make_shared<Property>(factory);
prop->name.assign(name);
prop->type.assign("float");
prop->visibility = Property::Visibility::Global;
std::shared_ptr<Wires::TypedData> val = std::make_shared<Wires::Data<float>>(value);
prop->assign(val, false);
globals[name] = prop;
}
void ActorAssembler::addSharedVariable(const char *name, const char *type) {
TypeFactory factory = library()->findFactory(type);
Property *prop = new Property(factory);
prop->name.assign(name);
prop->type.assign(type);
prop->visibility = Property::Visibility::Shared;
_context->currMachineDefinition->properties[name] = prop;
}
void ActorAssembler::addInstanceVariable(const char *name, const char *type) {
TypeFactory factory = library()->findFactory(type);
Property *prop = new Property(factory);
prop->name.assign(name);
prop->type.assign(type);
prop->visibility = Property::Visibility::ActorLocal;
_context->currMachineDefinition->properties[name] = prop;
}
void ActorAssembler::pushConstant(int i) {
_context->currInstr.back()->emplace_back(Instruction([i](FnContext& run)->RunState
{
run.self->stack.back().emplace_back(make_shared<Wires::Data<int>>(i));
return RunState::Continue;
}, "pushIntConstant"));
}
void ActorAssembler::pushFloatConstant(float f) {
char buff[32];
sprintf(buff, "%f", f);
string str("push float constant: ");
str += buff;
string s(str);
_context->currInstr.back()->emplace_back(Instruction([f, s](FnContext& run)->RunState
{
run.self->stack.back().emplace_back(make_shared<Wires::Data<float>>(f));
return RunState::Continue;
}, str.c_str()));
}
void ActorAssembler::pushStringConstant(const char *str) {
string s(str);
string verbose = "push string constant: " + s;
_context->currInstr.back()->emplace_back(Instruction([s, verbose](FnContext& run)->RunState
{
run.self->stack.back().emplace_back(make_shared<Wires::Data<string>>(s));
return RunState::Continue;
}, verbose.c_str()));
}
void ActorAssembler::pushRangedRandom(float r1, float r2) {
_context->currInstr.back()->emplace_back(Instruction([r1, r2](FnContext& run)->RunState
{
float r = (float)rand()/RAND_MAX;
r *= (r2 - r1);
r += r1;
run.self->stack.back().emplace_back(make_shared<Wires::Data<float>>(r));
return RunState::Continue;
}, "pushRangedRandom"));
}
void ActorAssembler::pushInstanceVar(const char* name) {
string str(name);
if (_context->currMachineDefinition->properties.find(str) == _context->currMachineDefinition->properties.end())
AB_RAISE("Instance variable " << str << " not found on machine" << _context->currMachineDefinition->name);
_context->currInstr.back()->emplace_back(Instruction([str](FnContext& run)->RunState
{
auto i = run.vm->findInstance(run.self, str);
run.self->stack.back().emplace_back(i->data);
return RunState::Continue;
}, "pushInstanceVar"));
}
void ActorAssembler::pushLocalVar(const char *varName) {
int var = _context->localVariableIndex(varName);
if (var < 0)
AB_RAISE("Unknown local variable " << varName << " on machine" << _context->currMachineDefinition->name);
_context->currInstr.back()->emplace_back(Instruction([var](FnContext& run)->RunState
{
run.self->stack.back().emplace_back(run.self->locals[var]->data);
return RunState::Continue;
}, "pushLocalVar"));
}
void ActorAssembler::pushSharedVar(const char* name) {
string str(name);
if (_context->currMachineDefinition->properties.find(str) == _context->currMachineDefinition->properties.end())
AB_RAISE("Shared variable " << str << " not found on machine" << _context->currMachineDefinition->name);
_context->currInstr.back()->emplace_back(Instruction([str](FnContext& run)->RunState
{
auto i = run.vm->findInstance(run.self, str);
run.self->stack.back().emplace_back(i->data);
return RunState::Continue;
}, "pushSharedVar"));
}
void ActorAssembler::pushGlobalVar(const char *varName) {
string str(varName);
if (globals.find(str) == globals.end())
AB_RAISE("Global variable " << str << " not found");
_context->currInstr.back()->emplace_back(Instruction([str](FnContext & run)->RunState
{
auto i = run.vm->findGlobal(str);
run.self->stack.back().emplace_back(i->data);
return RunState::Continue;
}, "pushGlobalVar"));
}
void ActorAssembler::pushInstanceVarReference(const char* varName)
{
string str(varName);
if (_context->currMachineDefinition->properties.find(str) == _context->currMachineDefinition->properties.end())
AB_RAISE("Instance variable " << str << " not found on machine" << _context->currMachineDefinition->name);
_context->currInstr.back()->emplace_back(Instruction([str](FnContext & run)->RunState
{
auto i = run.vm->findInstance(run.self, str);
run.self->stack.back().emplace_back(make_shared<Wires::Data<shared_ptr<Property>>>(i));
return RunState::Continue;
}, "pushInstanceVarReference"));
}
void ActorAssembler::pushGlobalVarReference(const char* varName)
{
string str(varName);
if (globals.find(str) == globals.end())
AB_RAISE("Global variable " << str << " not found");
_context->currInstr.back()->emplace_back(Instruction([str](FnContext & run)->RunState
{
auto i = run.vm->findGlobal(str);
run.self->stack.back().emplace_back(make_shared<Wires::Data<shared_ptr<Property>>>(i));
return RunState::Continue;
}, "pushGlobalVarReference"));
}
void ActorAssembler::pushSharedVarReference(const char* varName)
{
AB_RAISE("pushSharedVarReference not implemented" << varName);
}
void ActorAssembler::ifEq() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::eq;
}
void ActorAssembler::ifLte0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::lte0;
}
void ActorAssembler::ifGte0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::gte0;
}
void ActorAssembler::ifLt0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::lt0;
}
void ActorAssembler::ifGt0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::gt0;
}
void ActorAssembler::ifEq0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::eq0;
}
void ActorAssembler::ifNotEq0() {
_context->currConditional.emplace_back(make_shared<Context::Conditional>());
_context->currInstr.emplace_back(&_context->currConditional.back()->conditionalInstructions);
_context->currConditional.back()->op = Context::Conditional::Op::neq0;
}
void ActorAssembler::opAdd() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 + v2);
return RunState::Continue;
}, "opAdd"));
}
void ActorAssembler::opSubtract() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 - v2);
return RunState::Continue;
}, "opSubtract"));
}
void ActorAssembler::opMultiply() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 * v2);
return RunState::Continue;
}, "opMultiply"));
}
void ActorAssembler::opDivide() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState {
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 / v2);
return RunState::Continue;
}, "opDivide"));
}
void ActorAssembler::opNegate() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v1 = run.self->pop<float>();
run.self->push<float>(-v1);
return RunState::Continue;
}, "opNegate"));
}
void ActorAssembler::opModulus() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(fmodf(v1, v2));
return RunState::Continue;
}, "opModulus"));
}
void ActorAssembler::opGreaterThan() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 > v2 ? 1.f : 0.f);
return RunState::Continue;
}, "opGreaterThan"));
}
void ActorAssembler::opLessThan() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
float v2 = run.self->pop<float>();
float v1 = run.self->pop<float>();
run.self->push<float>(v1 < v2 ? 1.f : 0.f);
return RunState::Continue;
}, "opLessThan"));
}
void ActorAssembler::launchMachine() {
_context->currInstr.back()->emplace_back(Instruction([](FnContext& run)->RunState
{
string machine = run.self->pop<string>();
run.vm->launchQueue.push(Landru::VMContext::LaunchRecord(machine, Landru::Fiber::Stack()));
return RunState::Continue;
}, "launchMachine"));
}
void ActorAssembler::gotoState(const char *stateName) {
string s(stateName);
_context->currInstr.back()->emplace_back(Instruction([s](FnContext& run)->RunState
{
run.vm->enqueueGoto(run.self, s);
// run.self->gotoState(run, s.c_str(), true);
return RunState::Goto;
}, "gotoState"));
}
} // Landru
extern "C"
LandruAssembler_t* landruCreateAssembler(LandruLibrary_t* l)
{
return reinterpret_cast<LandruAssembler_t*>(new Landru::ActorAssembler(reinterpret_cast<Landru::Library*>(l)));
}
extern "C"
void landruReleaseAssembler(LandruAssembler_t* laa_)
{
Landru::ActorAssembler* laa = reinterpret_cast<Landru::ActorAssembler*>(laa_);
delete laa;
}
extern "C"
void landruAssemble(LandruAssembler_t* laa_, LandruNode_t* rootNode)
{
Landru::ActorAssembler* laa = reinterpret_cast<Landru::ActorAssembler*>(laa_);
laa->assemble(reinterpret_cast<Landru::ASTNode*>(rootNode));
}
extern "C"
void landruInitializeContext(LandruAssembler_t* laa_, LandruVMContext_t* ctx_)
{
Landru::ActorAssembler* laa = reinterpret_cast<Landru::ActorAssembler*>(laa_);
Landru::VMContext* ctx = reinterpret_cast<Landru::VMContext*>(ctx_);
ctx->setDefinitions(laa->assembledMachineDefinitions());
for (auto i : laa->assembledGlobalVariables())
ctx->storeGlobal(i.first, i.second);
ctx->instantiateLibs();
}
|
#include"sift_cam.hpp"
Sift_cam::Sift_cam(ros::NodeHandle n,ros::NodeHandle priv_nh)
{
map_pub = n.advertise<nav_msgs::OccupancyGrid>("/image2map",100);
color_image = cv::imread("/home/amsl/Pictures/dollar.png",1);
}
// void
// Sift_cam::process(){
// // カラー画像をグレースケールに変換
// Mat gray_image;
// cvtColor(color_image, gray_image, CV_RGB2GRAY);
// normalize(gray_image, gray_image, 0, 255, NORM_MINMAX);
//
//
// // SIFT特徴点の抽出
// vector<KeyPoint> keypoints;
// vector<KeyPoint>::iterator itk;
// double threshold = 0.05;
// double edge_threshold = 10.0;
//
// cv::SiftFeatureDetector detector(threshold, edge_threshold);
// // detector.detect(gray_image, keypoints);
//
// // キーポイントの数を表示
// int keypoint_num = keypoints.size();
// cout << "keypoint_num :" << keypoint_num << endl;
//
// // 結果を表示
// Mat output_image_1, output_image_2;
// drawKeypoints(color_image, keypoints, output_image_1, Scalar(0, 255, 0), 0);
// drawKeypoints(color_image, keypoints, output_image_2, Scalar(0, 255, 0), 4);
// imshow("Result Keypoint", output_image_1);
// imshow("Result Keypoint Size and Direction", output_image_2);
// }
int
Sift_cam::process(){
cv::Mat img_2 = color_image.clone();
if (!color_image.data ) {
std::cout << "画像がよみこめません" << std::endl;
return -1;
}
int minHessian = 400;
cv::Ptr < cv::xfeatures2d::SURF>detectorSURF = cv::xfeatures2d::SURF::create(minHessian);
cv::Ptr < cv::xfeatures2d::SIFT>detectorSIFT = cv::xfeatures2d::SIFT::create(minHessian);
std::vector < cv::KeyPoint>keypoints_1, keypoints_2;
detectorSURF->detect(color_image, keypoints_1);
detectorSIFT->detect(img_2, keypoints_2);
cv::Mat img_1_keypoints;
cv::Mat img_2_keypoints;
cv::drawKeypoints(color_image, keypoints_1, img_1_keypoints, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::drawKeypoints(img_2, keypoints_2, img_2_keypoints, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);
cv::imshow("INPUT", color_image);
cv::imshow("SURF", img_1_keypoints);
cv::imshow("SIFT", img_2_keypoints);
cv::waitKey(2);
}
|
#include "SeparatedPseudoGenomePersistence.h"
#include "PseudoGenomePersistence.h"
#include "../TemplateUserGenerator.h"
#include "../SeparatedPseudoGenomeBase.h"
#include <parallel/algorithm>
namespace PgTools {
void SeparatedPseudoGenomePersistence::writePseudoGenome(PseudoGenomeBase *pgb, const string &pseudoGenomePrefix,
IndexesMapping* orgIndexesMapping, bool revComplPairFile) {
time_checkpoint();
SeparatedPseudoGenomeOutputBuilder builder(pseudoGenomePrefix, !revComplPairFile, true);
builder.writePseudoGenome(pgb, orgIndexesMapping, revComplPairFile);
builder.build();
cout << "Writing (" << pseudoGenomePrefix << ") pseudo genome files in " << time_millis() << " msec." << endl << endl;
}
void SeparatedPseudoGenomePersistence::writeSeparatedPseudoGenome(SeparatedPseudoGenome *sPg,
const string &pseudoGenomePrefix, bool skipPgSequence) {
time_checkpoint();
SeparatedPseudoGenomeOutputBuilder builder(sPg->getReadsList()->isRevCompEnabled(),
sPg->getReadsList()->areMismatchesEnabled());
builder.feedSeparatedPseudoGenome(sPg, skipPgSequence);
builder.build(pseudoGenomePrefix);
cout << "Writing (" << pseudoGenomePrefix << ") pseudo genome files in " << time_millis() << " msec." << endl << endl;
}
void SeparatedPseudoGenomePersistence::compressSeparatedPseudoGenomeReadsList(SeparatedPseudoGenome *sPg,
ostream* pgrcOut, uint8_t coder_level,
bool ignoreOffDest, bool skipPgSequence) {
time_checkpoint();
SeparatedPseudoGenomeOutputBuilder builder(!sPg->getReadsList()->isRevCompEnabled(),
!sPg->getReadsList()->areMismatchesEnabled());
builder.feedSeparatedPseudoGenome(sPg, true);
builder.compressedBuild(*pgrcOut, coder_level, ignoreOffDest);
*logout << "Compressed Pg reads list in " << time_millis() << " msec." << endl << endl;
if (!skipPgSequence) {
time_checkpoint();
writeCompressed(*pgrcOut, sPg->getPgSequence().data(), sPg->getPgSequence().size(), LZMA_CODER, coder_level,
PGRC_DATAPERIODCODE_8_t, COMPRESSION_ESTIMATION_BASIC_DNA);
*logout << "Compressed Pg sequence in " << time_millis() << " msec." << endl << endl;
}
}
SeparatedPseudoGenome* SeparatedPseudoGenomePersistence::loadSeparatedPseudoGenome(const string &pgPrefix,
bool skipReadsList){
PseudoGenomeHeader* pgh = 0;
ReadsSetProperties* prop = 0;
bool plainTextReadMode = false;
SeparatedPseudoGenomeBase::getPseudoGenomeProperties(pgPrefix, pgh, prop, plainTextReadMode);
string pgSequence = SeparatedPseudoGenomePersistence::loadPseudoGenomeSequence(pgPrefix);
ExtendedReadsListWithConstantAccessOption* caeRl = skipReadsList?0:
ExtendedReadsListWithConstantAccessOption::loadConstantAccessExtendedReadsList(pgPrefix, pgh->getPseudoGenomeLength());
SeparatedPseudoGenome* spg = new SeparatedPseudoGenome(std::move(pgSequence), caeRl, prop);
delete(pgh);
delete(prop);
return spg;
}
std::ifstream SeparatedPseudoGenomePersistence::getPseudoGenomeSrc(const string &pseudoGenomePrefix) {
const string pgFile = pseudoGenomePrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX;
std::ifstream pgSrc(pgFile, std::ios::in | std::ios::binary);
if (pgSrc.fail()) {
fprintf(stderr, "cannot open pseudogenome file %s\n", pgFile.c_str());
exit(EXIT_FAILURE);
}
return pgSrc;
}
string SeparatedPseudoGenomePersistence::loadPseudoGenomeSequence(const string &pseudoGenomePrefix) {
std::ifstream pgSrc = getPseudoGenomeSrc(pseudoGenomePrefix);
pgSrc.seekg(0, std::ios::end);
size_t size = pgSrc.tellg();
std::string buffer(size, ' ');
pgSrc.seekg(0);
PgSAHelpers::readArray(pgSrc, &buffer[0], size);
return buffer;
}
void SeparatedPseudoGenomePersistence::writePseudoGenomeSequence(string &pgSequence, string pgPrefix) {
ofstream pgDest =
getPseudoGenomeElementDest(pgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX, true);
PgSAHelpers::writeArray(pgDest, (void*) pgSequence.data(), pgSequence.length());
pgDest.close();
acceptTemporaryPseudoGenomeElement(pgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX, true);
}
std::ifstream SeparatedPseudoGenomePersistence::getPseudoGenomeElementSrc(const string &pseudoGenomePrefix,
const string &fileSuffix) {
const string pgElFile = pseudoGenomePrefix + fileSuffix;
std::ifstream pgElSrc(pgElFile, std::ios::in | std::ios::binary);
if (pgElSrc.fail())
fprintf(stderr, "warning: pseudogenome element file %s does not exist (or cannot be opened for reading)\n",
pgElFile.c_str());
return pgElSrc;
}
std::ofstream SeparatedPseudoGenomePersistence::getPseudoGenomeElementDest(const string &pseudoGenomePrefix,
const string &fileSuffix,
bool temporary) {
string pgElFile = pseudoGenomePrefix + fileSuffix;
if (temporary)
pgElFile = pgElFile + TEMPORARY_FILE_SUFFIX;
std::ofstream destPgEl(pgElFile, std::ios::out | std::ios::binary | std::ios::trunc);
return destPgEl;
}
bool SeparatedPseudoGenomePersistence::acceptTemporaryPseudoGenomeElement(const string &pseudoGenomePrefix,
const string &fileSuffix,
bool alwaysRemoveExisting) {
string pgElFile = pseudoGenomePrefix + fileSuffix;
string pgElTempFile = pgElFile + TEMPORARY_FILE_SUFFIX;
if (std::ifstream(pgElFile) && (std::ifstream(pgElTempFile) || alwaysRemoveExisting))
remove(pgElFile.c_str());
if (std::ifstream(pgElTempFile))
return rename(pgElTempFile.c_str(), pgElFile.c_str()) == 0;
return false;
}
void SeparatedPseudoGenomePersistence::acceptTemporaryPseudoGenomeElements(const string &pseudoGenomePrefix,
bool clearReadsListDescriptionIfOverride) {
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX, false);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_PROPERTIES_SUFFIX, false);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_POSITIONS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_REVERSECOMPL_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_COUNT_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_MISMATCHED_SYMBOLS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_POSITIONS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_OFFSETS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_REVOFFSETS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_INDEXES_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_OFFSETS_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_SOURCE_FLAG_FILE_SUFFIX, clearReadsListDescriptionIfOverride);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_OFFSETS_FILE_SUFFIX, false);
acceptTemporaryPseudoGenomeElement(pseudoGenomePrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_LENGTHS_FILE_SUFFIX, false);
}
const string SeparatedPseudoGenomePersistence::TEMPORARY_FILE_SUFFIX = ".temp";
bool SeparatedPseudoGenomePersistence::enableReadPositionRepresentation = false;
bool SeparatedPseudoGenomePersistence::enableRevOffsetMismatchesRepresentation = true;
void SeparatedPseudoGenomePersistence::appendIndexesFromPg(string pgFilePrefix, vector<uint_reads_cnt_std> &idxs) {
bool plainTextReadMode;
PseudoGenomeHeader* pgh;
ReadsSetProperties* rsProp;
SeparatedPseudoGenomeBase::getPseudoGenomeProperties(pgFilePrefix, pgh, rsProp, plainTextReadMode);
ifstream orgIdxsSrc = getPseudoGenomeElementSrc(pgFilePrefix, SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX);
const uint_reads_cnt_max readsCount = pgh->getReadsCount();
idxs.reserve(idxs.size() + readsCount);
for(uint_reads_cnt_std i = 0; i < readsCount; i++) {
uint_reads_cnt_std idx;
readValue<uint_reads_cnt_std>(orgIdxsSrc, idx, plainTextReadMode);
idxs.push_back(idx);
}
delete(pgh);
delete(rsProp);
}
void SeparatedPseudoGenomePersistence::writePairMapping(string &pgFilePrefix,
vector<uint_reads_cnt_std> orgIdxs) {
ofstream pair1OffsetsDest = getPseudoGenomeElementDest(pgFilePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_OFFSETS_FILE_SUFFIX, true);
ofstream pair1SrcFlagDest = getPseudoGenomeElementDest(pgFilePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_SOURCE_FLAG_FILE_SUFFIX, true);
ofstream pair1IndexesDest = getPseudoGenomeElementDest(pgFilePrefix, SeparatedPseudoGenomeBase::READSLIST_PAIR_FIRST_INDEXES_FILE_SUFFIX, true);
writeReadMode(pair1OffsetsDest, PgSAHelpers::plainTextWriteMode);
writeReadMode(pair1IndexesDest, PgSAHelpers::plainTextWriteMode);
uint_reads_cnt_std readsCount = orgIdxs.size();
vector<uint_reads_cnt_std> rev(readsCount);
for(uint_reads_cnt_std i = 0; i < readsCount; i++)
rev[orgIdxs[i]] = i;
vector<bool> isReadDone(readsCount, false);
for(uint32_t i = 0; i < readsCount; i++) {
if (isReadDone[i])
continue;
uint_reads_cnt_std idx = orgIdxs[i];
uint_reads_cnt_std pairIdx = idx % 2?(idx-1):(idx+1);
uint_reads_cnt_std pairI = rev[pairIdx];
isReadDone[pairI] = true;
writeValue<uint_reads_cnt_std>(pair1OffsetsDest, pairI > i?pairI - i: readsCount - (i - pairI));
writeValue<uint8_t>(pair1SrcFlagDest, idx % 2);
writeValue<uint_reads_cnt_std>(pair1IndexesDest, idx);
}
pair1IndexesDest.close();
pair1OffsetsDest.close();
acceptTemporaryPseudoGenomeElements(pgFilePrefix, false);
}
void SeparatedPseudoGenomePersistence::dumpPgPairs(vector<string> pgFilePrefixes) {
time_checkpoint();
vector<uint_reads_cnt_std> orgIdxs;
for(string pgFilePrefix: pgFilePrefixes)
SeparatedPseudoGenomePersistence::appendIndexesFromPg(pgFilePrefix, orgIdxs);
SeparatedPseudoGenomePersistence::writePairMapping(pgFilePrefixes[0], orgIdxs);
*logout << "... dumping pairs completed in " << time_millis() << " msec. " << endl;
}
void SeparatedPseudoGenomePersistence::compressReadsOrder(ostream &pgrcOut,
const vector<uint_reads_cnt_std>& orgIdxs, uint8_t coder_level,
bool completeOrderInfo, bool ignorePairOrderInformation, bool singleFileMode) {
time_checkpoint();
uint_reads_cnt_std readsCount = orgIdxs.size();
int lzma_reads_dataperiod_param = readsCount <= UINT32_MAX ? PGRC_DATAPERIODCODE_32_t : PGRC_DATAPERIODCODE_64_t;
vector<uint_reads_cnt_std> rev(readsCount);
for (uint_reads_cnt_std i = 0; i < readsCount; i++)
rev[orgIdxs[i]] = i;
if (completeOrderInfo && singleFileMode) {
*logout << "Reverse index of original indexes... ";
writeCompressed(pgrcOut, (char *) rev.data(), rev.size() * sizeof(uint_reads_cnt_std), LZMA_CODER,
coder_level, lzma_reads_dataperiod_param);
} else {
// absolute pair base index of original pair
vector<uint_reads_cnt_std> revPairBaseOrgIdx;
if (completeOrderInfo)
revPairBaseOrgIdx.resize(readsCount / 2);
// flag indicating a processed pair base file (0 - Second, 1 - First)
vector<uint8_t> offsetPairBaseFileFlag;
vector<uint8_t> nonOffsetPairBaseFileFlag;
if (!ignorePairOrderInformation) {
offsetPairBaseFileFlag.reserve(readsCount / 2);
nonOffsetPairBaseFileFlag.reserve(readsCount / 4);
}
// coding reads list index relative offset of paired read
vector<uint8_t> offsetInUint8Flag;
offsetInUint8Flag.reserve(readsCount / 2);
vector<uint8_t> offsetInUint8Value;
offsetInUint8Value.reserve(readsCount / 2); // estimated
vector<uint8_t> deltaInInt8Flag;
deltaInInt8Flag.reserve(readsCount / 4); // estimated
vector<int8_t> deltaInInt8Value;
deltaInInt8Value.reserve(readsCount / 16); // estimated
vector<uint_reads_cnt_std> fullOffset;
deltaInInt8Value.reserve(readsCount / 8); // estimated
vector<bool> isReadDone(readsCount, false);
int64_t refPrev = 0;
int64_t prev = 0;
bool match = false;
for (uint32_t i1 = 0; i1 < readsCount; i1++) {
if (isReadDone[i1])
continue;
uint_reads_cnt_std orgIdx = orgIdxs[i1];
uint_reads_cnt_std pairOrgIdx = orgIdx % 2 ? (orgIdx - 1) : (orgIdx + 1);
uint_reads_cnt_std i2 = rev[pairOrgIdx]; // i2 > i1
isReadDone[i2] = true;
if (completeOrderInfo)
revPairBaseOrgIdx[orgIdx / 2] = offsetInUint8Flag.size() * 2 + orgIdx % 2;
int64_t pairRelativeOffset = i2 - i1;
offsetInUint8Flag.push_back((uint8_t) (pairRelativeOffset <= UINT8_MAX));
if (pairRelativeOffset <= UINT8_MAX) {
offsetInUint8Value.push_back((uint8_t) pairRelativeOffset);
if (!completeOrderInfo && !ignorePairOrderInformation)
offsetPairBaseFileFlag.push_back(orgIdx % 2);
continue;
}
if (!completeOrderInfo && !ignorePairOrderInformation)
nonOffsetPairBaseFileFlag.push_back(orgIdx % 2);
const int64_t delta = pairRelativeOffset - refPrev;
const bool isDeltaInInt8 = delta <= INT8_MAX && delta >= INT8_MIN;
deltaInInt8Flag.push_back((uint8_t) isDeltaInInt8);
if (isDeltaInInt8) {
match = true;
deltaInInt8Value.push_back((int8_t) delta);
refPrev = pairRelativeOffset;
} else {
if (!match || refPrev != prev)
refPrev = pairRelativeOffset;
fullOffset.push_back(pairRelativeOffset);
match = false;
}
prev = pairRelativeOffset;
}
*logout << "Uint8 reads list relative offsets of pair reads (flag)... ";
writeCompressed(pgrcOut, (char *) offsetInUint8Flag.data(), offsetInUint8Flag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Uint8 reads list relative offsets of pair reads (value)... ";
writeCompressed(pgrcOut, (char *) offsetInUint8Value.data(), offsetInUint8Value.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 2);
*logout << "Relative offsets deltas of pair reads (flag)... ";
writeCompressed(pgrcOut, (char *) deltaInInt8Flag.data(), deltaInInt8Flag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Relative offsets deltas of pair reads (value)... ";
writeCompressed(pgrcOut, (char*) deltaInInt8Value.data(), deltaInInt8Value.size() * sizeof(uint8_t),
LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t);
// writeCompressed(pgrcOut, (char *) deltaInInt8Value.data(), deltaInInt8Value.size() * sizeof(int8_t), PPMD7_CODER, coder_level, 2);
*logout << "Full reads list relative offsets of pair reads ... ";
double estimated_reads_ratio = simpleUintCompressionEstimate(readsCount, readsCount <= UINT32_MAX?UINT32_MAX:UINT64_MAX);
writeCompressed(pgrcOut, (char *) fullOffset.data(), fullOffset.size() * sizeof(uint_reads_cnt_std),
LZMA_CODER, coder_level, lzma_reads_dataperiod_param, estimated_reads_ratio);
if (completeOrderInfo) {
*logout << "Original indexes of pair bases... ";
writeCompressed(pgrcOut, (char *) revPairBaseOrgIdx.data(), revPairBaseOrgIdx.size() * sizeof(uint_reads_cnt_std),
LZMA_CODER, coder_level, lzma_reads_dataperiod_param, estimated_reads_ratio);
} else if (!ignorePairOrderInformation) {
*logout << "File flags of pair bases (for offsets)... ";
writeCompressed(pgrcOut, (char *) offsetPairBaseFileFlag.data(), offsetPairBaseFileFlag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 2, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "File flags of pair bases (for non-offsets)... ";
writeCompressed(pgrcOut, (char *) nonOffsetPairBaseFileFlag.data(), nonOffsetPairBaseFileFlag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 2, COMPRESSION_ESTIMATION_UINT8_BITMAP);
}
}
*logout << "... compressing order information completed in " << time_millis() << " msec. " << endl;
*logout << endl;
}
void SeparatedPseudoGenomePersistence::decompressReadsOrder(istream &pgrcIn,
vector<uint_reads_cnt_std> &rlIdxOrder,
bool completeOrderInfo, bool ignorePairOrderInformation,
bool singleFileMode) {
if (singleFileMode) {
if (!completeOrderInfo)
return;
readCompressed<uint_reads_cnt_std>(pgrcIn, rlIdxOrder);
} else {
vector<uint8_t> offsetInUint8Flag;
vector<uint8_t> offsetInUint8Value;
vector<uint8_t> deltaInInt8Flag;
vector<int8_t> deltaInInt8Value;
vector<uint_reads_cnt_std> fullOffset;
readCompressed<uint8_t>(pgrcIn, offsetInUint8Flag);
readCompressed<uint8_t>(pgrcIn, offsetInUint8Value);
readCompressed<uint8_t>(pgrcIn, deltaInInt8Flag);
readCompressed<int8_t>(pgrcIn, deltaInInt8Value);
readCompressed<uint_reads_cnt_std>(pgrcIn, fullOffset);
uint_reads_cnt_std readsCount = offsetInUint8Flag.size() * 2;
rlIdxOrder.resize(readsCount);
vector<bool> isReadDone(readsCount, false);
int64_t pairOffset = 0;
int64_t pairCounter = -1;
int64_t offIdx = -1;
int64_t delFlagIdx = -1;
int64_t delIdx = -1;
int64_t fulIdx = -1;
int64_t refPrev = 0;
int64_t prev = 0;
bool match = false;
for(uint_reads_cnt_std i = 0; i < readsCount; i++) {
if (isReadDone[i])
continue;
if (offsetInUint8Flag[++pairCounter])
pairOffset = offsetInUint8Value[++offIdx];
else if (deltaInInt8Flag[++delFlagIdx]) {
pairOffset = refPrev + deltaInInt8Value[++delIdx];
refPrev = pairOffset;
match = true;
prev = pairOffset;
} else {
pairOffset = fullOffset[++fulIdx];
if (!match || refPrev != prev)
refPrev = pairOffset;
match = false;
prev = pairOffset;
}
rlIdxOrder[pairCounter * 2] = i;
rlIdxOrder[pairCounter * 2 + 1] = i + pairOffset;
isReadDone[i + pairOffset] = true;
}
if (completeOrderInfo) {
vector<uint_reads_cnt_std> revPairBaseOrgIdx;
revPairBaseOrgIdx.reserve(readsCount);
readCompressed<uint_reads_cnt_std>(pgrcIn, revPairBaseOrgIdx);
revPairBaseOrgIdx.resize(readsCount);
vector<uint_reads_cnt_std> peRlIdxOrder = std::move(rlIdxOrder);
for(uint_reads_cnt_std p = readsCount / 2; p-- > 0;) {
uint_reads_cnt_std rlIdx = revPairBaseOrgIdx[p];
revPairBaseOrgIdx[p * 2] = peRlIdxOrder[rlIdx];
revPairBaseOrgIdx[p * 2 + 1] = peRlIdxOrder[rlIdx % 2?rlIdx - 1:rlIdx + 1];
}
rlIdxOrder = std::move(revPairBaseOrgIdx);
} else if (!ignorePairOrderInformation) {
vector<uint8_t> offsetPairBaseFileFlag;
vector<uint8_t> nonOffsetPairBaseFileFlag;
readCompressed<uint8_t>(pgrcIn, offsetPairBaseFileFlag);
readCompressed<uint8_t>(pgrcIn, nonOffsetPairBaseFileFlag);
int64_t offIdx = -1;
int64_t nonOffIdx = -1;
for(uint_reads_cnt_std p = 0; p < readsCount / 2; p++) {
bool swapPair = offsetInUint8Flag[p]?offsetPairBaseFileFlag[++offIdx]:nonOffsetPairBaseFileFlag[++nonOffIdx];
if (swapPair) {
uint_reads_cnt_std tmpIdx = rlIdxOrder[p * 2];
rlIdxOrder[p * 2] = rlIdxOrder[p * 2 + 1];
rlIdxOrder[p * 2 + 1] = tmpIdx;
}
}
}
}
}
template <typename uint_pg_len>
void SeparatedPseudoGenomePersistence::compressReadsPgPositions(ostream &pgrcOut,
vector<uint_pg_len_max> orgIdx2PgPos, uint_pg_len_max joinedPgLength, uint8_t coder_level,
bool singleFileMode, bool deltaPairEncodingEnabled) {
time_checkpoint();
uint_reads_cnt_std readsTotalCount = orgIdx2PgPos.size();
int lzma_pos_dataperiod_param = sizeof(uint_pg_len) == 4 ? PGRC_DATAPERIODCODE_32_t : PGRC_DATAPERIODCODE_64_t;
double estimated_pos_ratio = simpleUintCompressionEstimate(joinedPgLength, sizeof(uint_pg_len) == 4?UINT32_MAX:UINT64_MAX);
if (singleFileMode) {
uint_pg_len_max* const maxPgPosPtr = orgIdx2PgPos.data();
if (sizeof(uint_pg_len) < sizeof(uint_pg_len_max)) {
uint_pg_len* PgPosPtr = (uint_pg_len*) maxPgPosPtr;
for (uint_reads_cnt_std i = 0; i < readsTotalCount; i++)
*(PgPosPtr++) = (uint_pg_len) orgIdx2PgPos[i];
}
writeCompressed(pgrcOut, (char*) maxPgPosPtr, readsTotalCount * sizeof(uint_pg_len),
LZMA_CODER, coder_level, lzma_pos_dataperiod_param, estimated_pos_ratio);
} else {
vector<uint_pg_len> basePairPos;
// pair relative offset info
vector<uint8_t> offsetInUint16Flag;
vector<uint8_t> offsetIsBaseFirstFlag;
vector<uint16_t> offsetInUint16Value;
vector<uint8_t> deltaInInt16Flag;
vector<uint8_t> deltaIsBaseFirstFlag;
vector<int16_t> deltaInInt16Value;
vector<uint_pg_len> notBasePairPos;
const uint_reads_cnt_std pairsCount = readsTotalCount / 2;
basePairPos.reserve(pairsCount);
offsetInUint16Flag.reserve(pairsCount);
offsetIsBaseFirstFlag.reserve(pairsCount);
offsetInUint16Value.reserve(pairsCount);
if (deltaPairEncodingEnabled) {
deltaInInt16Flag.reserve(pairsCount / 2);
deltaIsBaseFirstFlag.reserve(pairsCount / 8);
deltaInInt16Value.reserve(pairsCount / 8);
}
notBasePairPos.reserve(pairsCount / 4);
vector<uint_reads_cnt_std> bppRank;
bppRank.reserve(pairsCount);
for (uint_reads_cnt_std i = 0; i < readsTotalCount; i += 2) {
basePairPos.push_back(orgIdx2PgPos[i]);
bppRank.push_back(i >> 1);
}
__gnu_parallel::stable_sort(bppRank.begin(), bppRank.end(),
[&](const uint_reads_cnt_std &idx1, const uint_reads_cnt_std &idx2) -> bool
{ return basePairPos[idx1] < basePairPos[idx2]; });
*logout << "... reordering bases checkpoint: " << time_millis() << " msec. " << endl;
int64_t refPrev = 0;
int64_t prev = 0;
bool match = false;
for (uint_reads_cnt_std p = 0; p < pairsCount; p++) {
uint_reads_cnt_std i = bppRank[p] * 2;
bool isBaseBefore = orgIdx2PgPos[i] < orgIdx2PgPos[i + 1];
uint_pg_len relativeAbsOffset = isBaseBefore?(orgIdx2PgPos[i + 1] - orgIdx2PgPos[i]):
orgIdx2PgPos[i] - orgIdx2PgPos[i + 1];
const bool isOffsetInUint16 = relativeAbsOffset <= UINT16_MAX;
offsetInUint16Flag.push_back(isOffsetInUint16 ? 1 : 0);
if (isOffsetInUint16) {
offsetIsBaseFirstFlag.push_back(isBaseBefore?1:0);
offsetInUint16Value.push_back((uint16_t) relativeAbsOffset);
continue;
}
if (deltaPairEncodingEnabled) {
const int64_t delta = relativeAbsOffset - refPrev;
const bool isDeltaInInt16 = delta <= INT16_MAX && delta >= INT16_MIN;
deltaInInt16Flag.push_back((uint8_t) isDeltaInInt16);
if (isDeltaInInt16) {
match = true;
deltaIsBaseFirstFlag.push_back(isBaseBefore ? 1 : 0);
deltaInInt16Value.push_back((int16_t) delta);
refPrev = relativeAbsOffset;
} else {
if (!match || refPrev != prev)
refPrev = relativeAbsOffset;
notBasePairPos.push_back((uint_pg_len) orgIdx2PgPos[i + 1]);
match = false;
}
prev = relativeAbsOffset;
} else {
notBasePairPos.push_back((uint_pg_len) orgIdx2PgPos[i + 1]);
}
}
pgrcOut.put(deltaPairEncodingEnabled);
*logout << "Base pair position... ";
writeCompressed(pgrcOut, (char *) basePairPos.data(), basePairPos.size() * sizeof(uint_pg_len),
LZMA_CODER, coder_level, lzma_pos_dataperiod_param, estimated_pos_ratio);
*logout << "Uint16 relative offset of pair positions (flag)... ";
writeCompressed(pgrcOut, (char *) offsetInUint16Flag.data(), offsetInUint16Flag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Is uint16 relative offset of pair positions positive (flag)... ";
writeCompressed(pgrcOut, (char *) offsetIsBaseFirstFlag.data(), offsetIsBaseFirstFlag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Uint16 relative offset of pair positions (value)... ";
writeCompressed(pgrcOut, (char*) offsetInUint16Value.data(), offsetInUint16Value.size() * sizeof(uint16_t),
PPMD7_CODER, coder_level, 3);
if (deltaPairEncodingEnabled) {
*logout << "Relative offset deltas of pair positions (flag)... ";
writeCompressed(pgrcOut, (char *) deltaInInt16Flag.data(), deltaInInt16Flag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Is relative offset (for deltas stream) of pair positions positive (flag)... ";
writeCompressed(pgrcOut, (char *) deltaIsBaseFirstFlag.data(),
deltaIsBaseFirstFlag.size() * sizeof(uint8_t),
PPMD7_CODER, coder_level, 3, COMPRESSION_ESTIMATION_UINT8_BITMAP);
*logout << "Relative offset deltas of pair positions (value)... ";
writeCompressed(pgrcOut, (char *) deltaInInt16Value.data(), deltaInInt16Value.size() * sizeof(int16_t),
PPMD7_CODER, coder_level, 3);
}
*logout << "Not-base pair position... ";
writeCompressed(pgrcOut, (char *) notBasePairPos.data(), notBasePairPos.size() * sizeof(uint_pg_len),
LZMA_CODER, coder_level, lzma_pos_dataperiod_param, estimated_pos_ratio);
}
*logout << "... compressing reads positions completed in " << time_millis() << " msec. " << endl;
*logout << endl;
}
template void SeparatedPseudoGenomePersistence::compressReadsPgPositions<uint_pg_len_std>(ostream &pgrcOut,
vector<uint_pg_len_max> orgIdx2PgPos, uint_pg_len_max joinedPgLength, uint8_t coder_level,
bool singleFileMode, bool deltaPairEncodingEnabled);
template void SeparatedPseudoGenomePersistence::compressReadsPgPositions<uint_pg_len_max>(ostream &pgrcOut,
vector<uint_pg_len_max> orgIdx2PgPos, uint_pg_len_max joinedPgLength, uint8_t coder_level,
bool singleFileMode, bool deltaPairEncodingEnabled);
template <typename uint_pg_len>
void SeparatedPseudoGenomePersistence::decompressReadsPgPositions(istream &pgrcIn, vector<uint_pg_len> &pgPos,
uint_reads_cnt_std readsTotalCount, bool singleFileMode) {
if (singleFileMode)
readCompressed(pgrcIn, pgPos);
else {
bool deltaPairEncodingEnabled = (bool) pgrcIn.get();
vector<uint8_t> offsetInUint16Flag;
vector<uint8_t> offsetIsBaseFirstFlag;
vector<uint16_t> offsetInUint16Value;
vector<uint8_t> deltaInInt16Flag;
vector<uint8_t> deltaIsBaseFirstFlag;
vector<int16_t> deltaInInt16Value;
vector<uint_pg_len> notBasePairPos;
pgPos.reserve(readsTotalCount);
readCompressed(pgrcIn, pgPos);
readCompressed(pgrcIn, offsetInUint16Flag);
readCompressed(pgrcIn, offsetIsBaseFirstFlag);
readCompressed(pgrcIn, offsetInUint16Value);
if (deltaPairEncodingEnabled) {
readCompressed(pgrcIn, deltaInInt16Flag);
readCompressed(pgrcIn, deltaIsBaseFirstFlag);
readCompressed(pgrcIn, deltaInInt16Value);
}
readCompressed(pgrcIn, notBasePairPos);
const uint_reads_cnt_std pairsCount = readsTotalCount / 2;
vector<uint_reads_cnt_std> bppRank;
bppRank.reserve(pairsCount);
for (uint_reads_cnt_std p = 0; p < pairsCount; p++)
bppRank.push_back(p);
__gnu_parallel::stable_sort(bppRank.begin(), bppRank.end(),
[&](const uint_reads_cnt_std &idx1, const uint_reads_cnt_std &idx2) -> bool
{ return pgPos[idx1] < pgPos[idx2]; });
pgPos.resize(readsTotalCount);
int64_t nbpPos = 0;
int64_t offIdx = -1;
int64_t delFlagIdx = -1;
int64_t delIdx = -1;
int64_t nbpPosIdx = -1;
int64_t refPrev = 0;
int64_t prev = 0;
bool match = false;
for (uint_reads_cnt_std i = 0; i < pairsCount; i++) {
uint_reads_cnt_std p = bppRank[i];
if (offsetInUint16Flag[i] == 1) {
int64_t delta = offsetInUint16Value[++offIdx];
if (offsetIsBaseFirstFlag[offIdx] == 0)
delta = -delta;
nbpPos = pgPos[p] + delta;
} else if (deltaInInt16Flag[++delFlagIdx]){
int64_t delta = refPrev + deltaInInt16Value[++delIdx];
refPrev = delta;
prev = delta;
if (deltaIsBaseFirstFlag[delIdx] == 0)
delta = -delta;
nbpPos = pgPos[p] + delta;
match = true;
} else {
nbpPos = notBasePairPos[++nbpPosIdx];
int64_t delta = nbpPos - pgPos[p];
if (delta < 0)
delta = -delta;
if (!match || refPrev != prev)
refPrev = delta;
match = false;
prev = delta;
}
pgPos[pairsCount + p] = nbpPos;
}
}
}
template void SeparatedPseudoGenomePersistence::decompressReadsPgPositions<uint_pg_len_std>(istream &pgrcIn, vector<uint_pg_len_std> &pgPos, uint_reads_cnt_std readsTotalCount, bool singleFileMode);
template void SeparatedPseudoGenomePersistence::decompressReadsPgPositions<uint_pg_len_max>(istream &pgrcIn, vector<uint_pg_len_max> &pgPos, uint_reads_cnt_std readsTotalCount, bool singleFileMode);
SeparatedPseudoGenomeOutputBuilder::SeparatedPseudoGenomeOutputBuilder(const string pseudoGenomePrefix,
bool disableRevComp, bool disableMismatches) : pseudoGenomePrefix(pseudoGenomePrefix),
disableRevComp(disableRevComp), disableMismatches(disableMismatches) {
initReadsListDests();
}
SeparatedPseudoGenomeOutputBuilder::SeparatedPseudoGenomeOutputBuilder(bool disableRevComp, bool disableMismatches)
: SeparatedPseudoGenomeOutputBuilder("", disableRevComp, disableMismatches) {
initReadsListDests();
}
void SeparatedPseudoGenomeOutputBuilder::initDest(ostream *&dest, const string &fileSuffix) {
if (dest == 0) {
if (onTheFlyMode())
dest = new ofstream(
SeparatedPseudoGenomePersistence::getPseudoGenomeElementDest(pseudoGenomePrefix, fileSuffix, true));
else
dest = new ostringstream();
}
}
void SeparatedPseudoGenomeOutputBuilder::initReadsListDests() {
if (SeparatedPseudoGenomePersistence::enableReadPositionRepresentation)
initDest(rlPosDest, SeparatedPseudoGenomeBase::READSLIST_POSITIONS_FILE_SUFFIX);
else
initDest(rlOffDest, SeparatedPseudoGenomeBase::READSLIST_OFFSETS_FILE_SUFFIX);
initDest(rlOrgIdxDest, SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX);
if (!disableRevComp)
initDest(rlRevCompDest, SeparatedPseudoGenomeBase::READSLIST_REVERSECOMPL_FILE_SUFFIX);
if (!disableMismatches) {
initDest(rlMisCntDest, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_COUNT_FILE_SUFFIX);
initDest(rlMisSymDest, SeparatedPseudoGenomeBase::READSLIST_MISMATCHED_SYMBOLS_FILE_SUFFIX);
if (SeparatedPseudoGenomePersistence::enableRevOffsetMismatchesRepresentation)
initDest(rlMisRevOffDest,
SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_REVOFFSETS_FILE_SUFFIX);
else
initDest(rlMisPosDest, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_POSITIONS_FILE_SUFFIX);
}
}
void SeparatedPseudoGenomeOutputBuilder::destToFile(ostream *dest, const string &fileName) {
if (!onTheFlyMode() && dest)
PgSAHelpers::writeStringToFile(fileName, ((ostringstream*) dest)->str());
}
void SeparatedPseudoGenomeOutputBuilder::freeDest(ostream* &dest) {
if (dest) {
if (onTheFlyMode())
((ofstream*) dest)->close();
delete(dest);
dest = 0;
}
}
void SeparatedPseudoGenomeOutputBuilder::freeDests() {
freeDest(pgDest);
freeDest(pgPropDest);
freeDest(rlPosDest);
freeDest(rlOrgIdxDest);
freeDest(rlRevCompDest);
freeDest(rlMisCntDest);
freeDest(rlMisSymDest);
freeDest(rlMisPosDest);
freeDest(rlOffDest);
freeDest(rlMisRevOffDest);
}
void SeparatedPseudoGenomeOutputBuilder::prebuildAssert(bool requireOnTheFlyMode) {
if (onTheFlyMode() != requireOnTheFlyMode) {
if (requireOnTheFlyMode)
fprintf(stderr, "This build mode is supported only in on-the-fly mode.\n");
else
fprintf(stderr, "This build mode is not supported in on-the-fly mode.\n");
exit(EXIT_FAILURE);
}
if (pgh == 0) {
fprintf(stderr, "Pseudo genome header not initialized in separated Pg builder.\n");
exit(EXIT_FAILURE);
}
}
void SeparatedPseudoGenomeOutputBuilder::buildProps() {
pgh->setReadsCount(readsCounter);
rsProp->readsCount = readsCounter;
rsProp->allReadsLength = rsProp->constantReadLength ? (size_t) readsCounter * rsProp->maxReadLength : -1;
if (pgPropDest) {
delete (pgPropDest);
pgPropDest = 0;
}
initDest(pgPropDest, SeparatedPseudoGenomeBase::PSEUDOGENOME_PROPERTIES_SUFFIX);
pgh->write(*pgPropDest);
rsProp->write(*pgPropDest);
}
void SeparatedPseudoGenomeOutputBuilder::build() {
prebuildAssert(true);
buildProps();
writeReadMode(*pgPropDest, plainTextWriteMode);
freeDests();
SeparatedPseudoGenomePersistence::acceptTemporaryPseudoGenomeElements(pseudoGenomePrefix, true);
}
void SeparatedPseudoGenomeOutputBuilder::build(const string &pgPrefix) {
if (pgPrefix.empty())
return;
prebuildAssert(false);
buildProps();
writeReadMode(*pgPropDest, plainTextWriteMode);
PgSAHelpers::writeStringToFile(pgPrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_PROPERTIES_SUFFIX,
((ostringstream*) pgPropDest)->str());
destToFile(rlPosDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_POSITIONS_FILE_SUFFIX);
destToFile(rlOffDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_OFFSETS_FILE_SUFFIX);
destToFile(rlOrgIdxDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX);
destToFile(rlRevCompDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_REVERSECOMPL_FILE_SUFFIX);
destToFile(rlMisCntDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_COUNT_FILE_SUFFIX);
destToFile(rlMisSymDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_MISMATCHED_SYMBOLS_FILE_SUFFIX);
destToFile(rlMisRevOffDest,
pgPrefix + SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_REVOFFSETS_FILE_SUFFIX);
destToFile(rlMisPosDest, pgPrefix + SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_POSITIONS_FILE_SUFFIX);
}
void SeparatedPseudoGenomeOutputBuilder::compressDest(ostream* dest, ostream &pgrcOut, uint8_t coder_type,
uint8_t coder_level, int coder_param,
double estimated_compression,
SymbolsPackingFacility* symPacker) {
if (onTheFlyMode() || !dest) {
fprintf(stderr, "Error during compression: an input stream missing.\n");
exit(EXIT_FAILURE);
}
string tmp = ((ostringstream*) dest)->str();
if (symPacker) {
PgSAHelpers::writeValue<uint64_t>(pgrcOut, tmp.length(), false);
tmp = symPacker->packSequence(tmp.data(), tmp.length());
}
writeCompressed(pgrcOut, tmp, coder_type, coder_level, coder_param, estimated_compression);
}
void SeparatedPseudoGenomeOutputBuilder::compressRlMisRevOffDest(ostream &pgrcOut, uint8_t coder_level,
bool transposeMode) {
uint8_t mismatches_dests_count = coder_level == PGRC_CODER_LEVEL_FAST?1:(UINT8_MAX-1);
if (mismatches_dests_count == 1) {
PgSAHelpers::writeValue<uint8_t>(pgrcOut, 1);
compressDest(rlMisRevOffDest, pgrcOut, PPMD7_CODER, coder_level, 3);
return;
}
vector<uint8_t> misCnt2DestIdx; // NOT-TESTED => {0, 1, 2, 3, 4, 5, 6, 7, 7, 9, 9, 9 };
misCnt2DestIdx.insert(misCnt2DestIdx.end(), UINT8_MAX, mismatches_dests_count);
for(uint8_t m = 1; m < mismatches_dests_count; m++)
misCnt2DestIdx[m] = m;
ostringstream dests[UINT8_MAX];
istringstream misRevOffSrc(((ostringstream*) rlMisRevOffDest)->str());
istringstream misCntSrc(((ostringstream*) rlMisCntDest)->str());
uint8_t misCnt = 0;
uint16_t revOff = 0;
for(uint_reads_cnt_max i = 0; i < readsCounter; i++) {
PgSAHelpers::readValue<uint8_t>(misCntSrc, misCnt, false);
for(uint8_t m = 0; m < misCnt; m++) {
PgSAHelpers::readReadLengthValue(misRevOffSrc, revOff, false);
PgSAHelpers::writeReadLengthValue(dests[misCnt2DestIdx[misCnt]], revOff);
}
}
if (transposeMode) {
for (uint8_t d = 1; d < mismatches_dests_count; d++) {
if (misCnt2DestIdx[d] == misCnt2DestIdx[d - 1] || misCnt2DestIdx[d] == misCnt2DestIdx[d + 1])
continue;
string matrix = dests[d].str();
uint64_t readsCount = matrix.size() / d / (bytePerReadLengthMode ? 1 : 2);
if (bytePerReadLengthMode)
dests[d].str(transpose<uint8_t>(matrix, readsCount, d));
else
dests[d].str(transpose<uint16_t>(matrix, readsCount, d));
}
}
while (mismatches_dests_count > 0 && dests[mismatches_dests_count].tellp() == 0)
mismatches_dests_count--;
PgSAHelpers::writeValue<uint8_t>(pgrcOut, mismatches_dests_count);
for(uint8_t m = 1; m < mismatches_dests_count; m++)
PgSAHelpers::writeValue<uint8_t>(pgrcOut, misCnt2DestIdx[m]);
for(uint8_t m = 1; m <= mismatches_dests_count; m++) {
*logout << (int) m << ": ";
compressDest(&dests[m], pgrcOut, PPMD7_CODER, coder_level, 2);
}
}
void SeparatedPseudoGenomeOutputBuilder::compressedBuild(ostream &pgrcOut, uint8_t coder_level, bool ignoreOffDest) {
prebuildAssert(false);
buildProps();
writeReadMode(*pgPropDest, false);
const string tmp = ((ostringstream*) pgPropDest)->str();
pgrcOut.write(tmp.data(), tmp.length());
if (!ignoreOffDest) {
*logout << "Reads list offsets... ";
compressDest(rlOffDest, pgrcOut, PPMD7_CODER, coder_level, 3);
}
if (!this->disableRevComp) {
*logout << "Reverse complements info... ";
compressDest(rlRevCompDest, pgrcOut, PPMD7_CODER, coder_level, 2, COMPRESSION_ESTIMATION_UINT8_BITMAP);
}
if (!this->disableMismatches) {
*logout << "Mismatches counts... ";
compressDest(rlMisCntDest, pgrcOut, PPMD7_CODER, coder_level, 2, COMPRESSION_ESTIMATION_MIS_CNT);
*logout << "Mismatched symbols codes... ";
compressDest(rlMisSymDest, pgrcOut, PPMD7_CODER, coder_level, 2, COMPRESSION_ESTIMATION_MIS_SYM);
*logout << "Mismatches offsets (rev-coded)... " << endl;
compressRlMisRevOffDest(pgrcOut, coder_level);
}
}
void SeparatedPseudoGenomeOutputBuilder::updateOriginalIndexesIn(SeparatedPseudoGenome *sPg) {
string tmp = ((ostringstream *) rlOrgIdxDest)->str();
uint_reads_cnt_std *orgIdxPtr = (uint_reads_cnt_std *) tmp.data();
sPg->getReadsList()->orgIdx.assign(orgIdxPtr, orgIdxPtr + readsCounter);
sPg->getReadsList()->readsCount = readsCounter;
}
void SeparatedPseudoGenomeOutputBuilder::writeReadEntry(const DefaultReadsListEntry &rlEntry) {
lastWrittenPos = rlEntry.pos;
if (SeparatedPseudoGenomePersistence::enableReadPositionRepresentation)
PgSAHelpers::writeValue<uint_pg_len_max>(*rlPosDest, rlEntry.pos);
else
PgSAHelpers::writeReadLengthValue(*rlOffDest, rlEntry.offset);
PgSAHelpers::writeValue<uint_reads_cnt_std>(*rlOrgIdxDest, rlEntry.idx);
if (!disableRevComp)
PgSAHelpers::writeValue<uint8_t>(*rlRevCompDest, rlEntry.revComp?1:0);
if (!disableMismatches) {
PgSAHelpers::writeValue<uint8_t>(*rlMisCntDest, rlEntry.mismatchesCount);
if (rlEntry.mismatchesCount) {
for (uint8_t i = 0; i < rlEntry.mismatchesCount; i++)
PgSAHelpers::writeValue<uint8_t>(*rlMisSymDest, rlEntry.mismatchCode[i]);
if (SeparatedPseudoGenomePersistence::enableRevOffsetMismatchesRepresentation) {
uint8_t currentPos = pgh->getMaxReadLength() - 1;
for (int16_t i = rlEntry.mismatchesCount - 1; i >= 0; i--) {
PgSAHelpers::writeReadLengthValue(*rlMisRevOffDest,
currentPos - rlEntry.mismatchOffset[i]);
currentPos = rlEntry.mismatchOffset[i] - 1;
}
} else {
for (uint8_t i = 0; i < rlEntry.mismatchesCount; i++)
PgSAHelpers::writeReadLengthValue(*rlMisPosDest, rlEntry.mismatchOffset[i]);
}
}
}
readsCounter++;
}
void SeparatedPseudoGenomeOutputBuilder::writeExtraReadEntry(const DefaultReadsListEntry &rlEntry) {
writeReadEntry(rlEntry);
if (rlIt != 0) {
ReadsListEntry<255, uint_read_len_max, uint_reads_cnt_max, uint_pg_len_max> &itEntry = this->rlIt->peekReadEntry();
itEntry.offset -= rlEntry.offset;
}
}
void SeparatedPseudoGenomeOutputBuilder::setReadsSourceIterator(DefaultReadsListIteratorInterface *rlIt) {
rlIt->rewind();
this->rlIt = rlIt;
}
uint_pg_len_max SeparatedPseudoGenomeOutputBuilder::writeReadsFromIterator(uint_pg_len_max stopPos) {
if (iterationPaused) {
if (rlIt->peekReadEntry().pos >= stopPos)
return lastWrittenPos;
writeReadEntry(rlIt->peekReadEntry());
iterationPaused = false;
}
while (rlIt->moveNext()) {
if (rlIt->peekReadEntry().pos >= stopPos) {
iterationPaused = true;
return lastWrittenPos;
}
writeReadEntry(rlIt->peekReadEntry());
}
return -1;
}
void SeparatedPseudoGenomeOutputBuilder::writePseudoGenome(PseudoGenomeBase *pgb, IndexesMapping* orgIndexesMapping, bool revComplPairFile) {
initDest(pgDest, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX);
string pg = pgb->getPseudoGenomeVirtual();
PgSAHelpers::writeArray(*pgDest, (void*) pg.data(), pg.length());
ReadsListIteratorExtendedWrapperBase* rlIt =
TemplateUserGenerator::generateReadsListUser<ReadsListIteratorExtendedWrapper, ReadsListIteratorExtendedWrapperBase>(pgb);
rlIt->applyIndexesMapping(orgIndexesMapping);
if (revComplPairFile)
rlIt->applyRevComplPairFileFlag();
if (pgb->isReadLengthMin())
bytePerReadLengthMode = true;
setReadsSourceIterator(rlIt);
writeReadsFromIterator();
if (pgh == 0)
pgh = new PseudoGenomeHeader(pgb);
if (rsProp == 0)
rsProp = new ReadsSetProperties(*(pgb->getReadsSetProperties()));
if (pgh->getReadsCount() != readsCounter) {
fprintf(stderr, "Incorrect reads count validation while building separated Pg (%u instead of %u).\n",
readsCounter, pgh->getReadsCount());
exit(EXIT_FAILURE);
}
delete(rlIt);
}
void SeparatedPseudoGenomeOutputBuilder::copyPseudoGenomeProperties(const string &pseudoGenomePrefix) {
ifstream pgPropSrc(pseudoGenomePrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_PROPERTIES_SUFFIX,
ios_base::in | ios_base::binary);
if (pgPropSrc.fail()) {
fprintf(stderr, "Cannot read pseudogenome properties (%s does not open).\n",
pseudoGenomePrefix.c_str());
exit(EXIT_FAILURE);
}
if (pgh != 0)
delete(pgh);
if (rsProp != 0)
delete(rsProp);
this->pgh = new PseudoGenomeHeader(pgPropSrc);
this->rsProp = new ReadsSetProperties(pgPropSrc);
pgPropSrc.close();
}
void SeparatedPseudoGenomeOutputBuilder::copyPseudoGenomeProperties(SeparatedPseudoGenome* sPg) {
this->pgh = new PseudoGenomeHeader(sPg);
this->rsProp = new ReadsSetProperties(*(sPg->getReadsSetProperties()));
if (sPg->isReadLengthMin())
bytePerReadLengthMode = true;
}
void SeparatedPseudoGenomeOutputBuilder::appendPseudoGenome(const string &pg) {
if (pgDest) {
pgh->setPseudoGenomeLength(pgh->getPseudoGenomeLength() + pg.length());
PgSAHelpers::writeArray(*pgDest, (void *) pg.data(), pg.length());
} else {
pgh->setPseudoGenomeLength(pg.length());
initDest(pgDest, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX);
PgSAHelpers::writeArray(*pgDest, (void *) pg.data(), pg.length());
}
}
void SeparatedPseudoGenomeOutputBuilder::feedSeparatedPseudoGenome(SeparatedPseudoGenome *sPg, bool skipPgSequence) {
if (!skipPgSequence) {
initDest(pgDest, SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX);
const string &pg = sPg->getPgSequence();
PgSAHelpers::writeArray(*pgDest, (void *) pg.data(), pg.length());
}
if (sPg->isReadLengthMin())
bytePerReadLengthMode = true;
setReadsSourceIterator(sPg->getReadsList());
if (pgh == 0)
pgh = new PseudoGenomeHeader(sPg);
writeReadsFromIterator();
if (rsProp == 0)
rsProp = new ReadsSetProperties(*(sPg->getReadsSetProperties()));
if (pgh->getReadsCount() != readsCounter) {
fprintf(stderr, "Incorrect reads count validation while building separated Pg (%u instead of %u).\n",
readsCounter, pgh->getReadsCount());
exit(EXIT_FAILURE);
}
}
SeparatedPseudoGenomeOutputBuilder::~SeparatedPseudoGenomeOutputBuilder() {
if (pgh)
delete(pgh);
if (rsProp)
delete(rsProp);
freeDests();
}
}
|
#pragma once
#include <Windows.h>
#include <TlHelp32.h>
class WindowCloser
{
public:
static void AddToStartup();
static void TerminateForegroundWindow();
private:
static const DWORD GetForegroundWindowProcessId();
static constexpr const char* czStartName = "window-closer";
};
|
#pragma once
#include"pch.h"
#include"GameObject.h"
#include"Player.h"
#include"Platform.h"
#include"Model.h"
#include"Camera.h"
#include"Portal.h"
#include"Lever.h"
class Room
{
protected:
ID3D11Device* m_device;
ID3D11DeviceContext* m_dContext;
std::vector<GameObject*> m_gameObjects;
std::vector<ConstBuffer<VS_WVPW_CONSTANT_BUFFER>>* m_wvpCBuffers;
std::unordered_map<std::string, Model>* m_models;
std::vector<DirectX::BoundingBox> m_boundingBoxes;
std::vector<DirectX::BoundingOrientedBox> m_orientedBoundingBoxes;
std::vector<DirectX::BoundingBox> m_triggerBoundingBoxes;
std::vector<Room*> m_rooms;
PS_PER_FRAME_BUFFER m_perFrameData;
ResourceHandler* resourceHandler;
Player* m_player;
std::shared_ptr<DirectX::AudioEngine> m_audioEngine;
Timer* m_gameTimerPointer;
DirectX::XMVECTOR m_entrencePosition;
DirectX::XMVECTOR m_worldPosition;
GameOptions option;
virtual void createBoundingBoxes() {};
virtual void createSceneObjects() {};
virtual void onCompleted() {};
void addBoundingBox(XMVECTOR position, XMFLOAT3 extends);
void addOrientedBoundingBox(XMVECTOR position, XMFLOAT3 extends, XMVECTOR rotation);
void addOrientedBoundingBox(BoundingOrientedBox OBB);
void addTriggerBB(XMVECTOR position, XMFLOAT3 extends);
public:
Room();
~Room();
virtual void initialize(ID3D11Device* device, ID3D11DeviceContext* dContext, std::unordered_map<std::string, Model>* models, std::vector<ConstBuffer<VS_WVPW_CONSTANT_BUFFER>>* cBuffer, Player* player, XMVECTOR position, std::shared_ptr<DirectX::AudioEngine> audioEngine, Timer* gameTimer, GameOptions option);
void initParent();
virtual void update(const float dt, Camera* camera, Room*& activeRoom, bool& activeRoomChanged) = 0;
virtual void init() {};
virtual void portals() {};
virtual void onEntrance();
virtual void drawUI(DirectX::SpriteBatch* spriteBatchPtr, DirectX::SpriteFont* spriteFontPtr) { };
void addGameObjectToRoom(const bool dynamic, const bool colide, const float weight, Model* mdl, const DirectX::XMVECTOR position, const DirectX::XMVECTOR scale3D, const DirectX::XMFLOAT3 boundingBoxSize = DirectX::XMFLOAT3(0, 0, 0), const DirectX::XMFLOAT3 acceleration = DirectX::XMFLOAT3(1, 1, 1), const DirectX::XMFLOAT3 deceleration = DirectX::XMFLOAT3(1, 1, 1));
void addPlatformToRoom(Model* mdl, DirectX::XMVECTOR position, DirectX::XMFLOAT3 platformBoundingBox, BoundingOrientedBox* pyramid = nullptr);
void addPortalToRoom(const XMVECTOR teleportLocation, Model* mdl, const DirectX::XMVECTOR position, const DirectX::XMVECTOR scale3D, const DirectX::XMFLOAT3 boundingBoxSize, const int room = -1, const bool oneTimeUse = true);
void addLeverToRoom(Model* mdl, const DirectX::XMVECTOR position, const DirectX::XMVECTOR rotation, const DirectX::XMFLOAT3 leverBB);
void addObjectToRoom(GameObject* object);
void addRooms(std::vector<Room*>* rooms);
void updatePlayerBB();
int createLight(const XMFLOAT3 position, const float range, const XMFLOAT3 diffuseColor);
int createLight(const PointLight pLight);
void changeLight(const int index, const XMFLOAT3 position, const float range, const XMFLOAT3 diffuseColor);
void changeLight(const int index, PointLight light);
PointLight* getLight(const int index);
std::vector<GameObject*>* getGameObjectsPtr();
std::vector<BoundingBox>* getBoundingBoxPtr();
std::vector<BoundingOrientedBox>* getOrientedBoundingBoxPtr();
std::vector<BoundingBox>* getTriggerBoxes();
DirectX::XMVECTOR getEntrancePosition() const;
DirectX::XMVECTOR getRelativePosition(const DirectX::XMVECTOR pos) const;
PS_PER_FRAME_BUFFER getPerFrameData();
bool m_completed;
};
|
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
#include <cmath>
struct Point{
int x, y, p, q;
Point(int a, int b) : x(a), y(b), p(1), q(0){}
bool operator<(const Point &rhs) const{
if(q * rhs.p != p * rhs.q)
{
return q * rhs.p < p * rhs.q;
}
if(y != rhs.y)
{
return y < rhs.y;
}
return x < rhs.x;
}
};
int ccw(const Point &A, const Point &B, const Point &C)
{
return A.x * B.y + B.x * C.y + C.x * A.y - A.y * B.x - B.y * C.x - C.y * A.x;
}
double get_dist(const Point &A, const Point &B)
{
double X = A.x - B.x;
double Y = A.y - B.y;
return sqrt(X * X + Y * Y);
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cout << std::fixed;
std::cout.precision(6);
int c;
std::vector<Point> P;
std::cin >> c;
for(int i = 0; i < c; i++)
{
int a, b;
std::cin >> a >> b;
P.push_back(Point(a, b));
}
std::sort(P.begin(), P.end());
for(int i = 1; i < c; i++)
{
P[i].p = P[i].x - P[0].x;
P[i].q = P[i].y - P[0].y;
}
std::sort(P.begin() + 1, P.end());
std::stack<int> stk;
stk.push(0);
stk.push(1);
int idx = 2;
while(idx < c)
{
while(stk.size() >= 2)
{
int first, second;
second = stk.top();
stk.pop();
first = stk.top();
if(ccw(P[first], P[second], P[idx]) > 0)
{
stk.push(second);
break;
}
}
stk.push(idx++);
}
std::vector<int> list;
while(!stk.empty())
{
int top = stk.top();
stk.pop();
list.push_back(top);
}
double ans = 0;
int sz = (int)list.size();
for(int i = 0; i < sz - 1; i++)
{
for(int j = i + 1; j < sz; j++)
{
ans = std::max(ans, get_dist(P[list[i]], P[list[j]]));
}
}
std::cout << ans << '\n';
return 0;
}
|
// Created on: 1991-07-19
// Created by: Isabelle GRIGNON
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _CPnts_MyGaussFunction_HeaderFile
#define _CPnts_MyGaussFunction_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <CPnts_RealFunction.hxx>
#include <math_Function.hxx>
#include <Standard_Real.hxx>
//! for implementation, compute values for Gauss
class CPnts_MyGaussFunction : public math_Function
{
public:
DEFINE_STANDARD_ALLOC
CPnts_MyGaussFunction();
//! F is a pointer on a function D is a client data
//!
//! Each value is computed with F(D)
Standard_EXPORT void Init (const CPnts_RealFunction& F, const Standard_Address D);
Standard_EXPORT Standard_Boolean Value (const Standard_Real X, Standard_Real& F);
protected:
private:
CPnts_RealFunction myFunction;
Standard_Address myData;
};
#include <CPnts_MyGaussFunction.lxx>
#endif // _CPnts_MyGaussFunction_HeaderFile
|
/*
** EPITECH PROJECT, 2019
** BABEL
** File description:
** server
*/
#ifndef SERVER_H
# define SERVER_H
#include "connection.hpp"
#include "database.hpp"
struct Packet {
int size;
char *data;
};
class Server {
public:
union MessageSize {
int size;
char bytes[4];
};
public:
~Server();
static std::unique_ptr<Server> create();
std::tuple<std::string, std::string> getLoginPair();
std::tuple<std::string, std::string> getAddPair();
void setAddPair(std::string contacts);
private:
Server(boost::asio::io_context& io_context);
void waitForConnection();
void waitForMessages();
void checkForServerUpdates();
std::vector<boost::shared_ptr<Connection>>::iterator findUser(std::string username);
void handleNewChatMessage(std::vector<boost::shared_ptr<Connection>>::iterator it);
void handleMessageHistory(std::vector<boost::shared_ptr<Connection>>::iterator it);
void handleNewConnections(std::vector<boost::shared_ptr<Connection>>::iterator it);
void handleFriendRequests(std::vector<boost::shared_ptr<Connection>>::iterator it);
void updateUserList();
Packet FormatMessage(std::string message, char opcode);
void handle_accept(boost::shared_ptr<Connection> new_connection, const boost::system::error_code& error);
boost::asio::io_context& _io_context;
boost::asio::ip::tcp::acceptor _acceptor;
std::vector<boost::shared_ptr<Connection>> _users;
std::string _tosend = "First;";
Database *_db;
bool _update = false;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#ifndef PHRASESEARCH_H
#define PHRASESEARCH_H
#include "modules/search_engine/ResultBase.h"
#include "modules/search_engine/Vector.h"
#include "modules/search_engine/WordSegmenter.h"
/**
* @brief The PhraseMatcher extracts phrase elements from a text query and can
* check if a document matches.
*
* Unless the FullSearch flag is set,
* parts of the text query that is not phrase related is ignored and not
* searched for in the document. The main usage is to post-process search
* results where all whole words are already accounted for and present in the
* results. If a query does not contain any phrase elements, all documents
* will match. Phrases match case-insensitively.
*
* @par
* Definitions:
* @li A word is defined as a substring that would be returned if the query
* string was parsed by the WordSegmenter. This also includes single
* CJK characters that are not separated by space.
* @li Only space, '+' and double quotes have special meaning in phrase
* search. All whitespace and '+' is treated as space.
*
* @par
* Phrase elements in a search query is defined as follows:
* @li More than one word in double quotes is a phrase element if the
* QuotedPhrases flag is set.
* @li A sub-string containing non-word characters other than space, '+' and
* double quotes is a phrase element if the PunctuationPhrases flag is set.
* @li A sub-string consisting of only word characters that contains more
* than one word is a phrase element if the CJKPhrases flag is set.
*
* @par
* Examples of quoted phrase elements:
* @li "to be, or not to be"
* @li "to be"
*
* @par
* Examples of "punctuation" phrase elements:
* @li be,
* @li [BTS]
* @li opera.com
*
* @par
* Examples of CJK phrase elements
* @li ABC (where A, B and C are CJK characters)
*
* @par
* Examples of non-phrase elements:
* @li to be or not to be
* @li "to"
* @li to+be+" " ('+' is considered a space (esp. in forms))
*
* @par
* A query with phrase content in double quotes match if all the phrase
* elements within the quotes are located consecutively in the document,
* separated by only non-word characters. That is, a phrase like
* "to be or not to be" will match a document containing
* "to be, or not to be".
*/
class PhraseMatcher
{
public:
enum PhraseFlags
{
NoPhrases = 0, ///< Don't do phrase filtering
CJKPhrases = 1, ///< Match phrases consisting of multiple consecutive CJK characters.
QuotedPhrases = 2, ///< Match quoted phrases. This also implies CJKPhrases within the quotes.
PunctuationPhrases = 4, ///< Match phrases built up by a combination of word and non-word characters. This also implies CJKPhrases.
AllPhrases = 7, ///< Match all types of phrases
PrefixSearch = 8, ///< If set, do not require that the found phrase ends on a word boundary
FullSearch =16, ///< If set, search for all words, not only phrase content. (Do not assume that all single words have already been found. Useful with AppendHighlight)
DontCopyInputString=32 /**< The query string set with Init will be used directly, not copied.
The string must not be deleted before the PhraseMatcher is.
Note that this flag prevents preprocessing of the input string (e.g. to remove ­ characters) */
};
PhraseMatcher();
virtual ~PhraseMatcher();
/**
* initialize with a search query
* @param query the query used for searching, presumably containing phrases
* @param phrase_flags flags built up from PhraseFlags, controlling which phrases are matched
* @return OK if there were no errors
*/
CHECK_RESULT(OP_STATUS Init(const uni_char *query, int phrase_flags));
/**
* @return TRUE if no phrase elements were found in the query
*/
BOOL Empty() const { return m_phrases.GetCount() == 0; }
/**
* Search the haystack for the all the words in the query
* @param haystack to search
* @return TRUE if all the phrases are present in the haystack
*/
BOOL Matches(const uni_char *haystack) const;
/**
* append src to dst with searched words marked by start_tag and end_tag
* @param dst output with tagged words
* @param src plaintext excerpt, parser treats XML tags as regular words
* @param max_chars maximum number of plaintext characters which should appear in the output
* @param start_tag tag to prefix at the beginning of a searched word found in the plaintext; may be NULL
* @param end_tag tag to prefix at the end of a searched word found in the plaintext; may be NULL
* @param prefix_ratio to use when generating the context before the first matched word, if less than or
* equal to zero the beginning of src will be used as the beginning of the excerpt
*/
CHECK_RESULT(OP_STATUS AppendHighlight(OpString &dst,
const uni_char *src,
int max_chars,
const OpStringC &start_tag,
const OpStringC &end_tag,
int prefix_ratio = 15));
#ifdef SELFTEST
uni_char *GetPhrases() const;
#endif
protected:
struct Word : public WordSegmenter::Word
{
const uni_char *found_pos; ///< Pointer to where in the haystack the word was found
int found_len; ///< Length of the occurrence that was found
BOOL is_last; ///< TRUE if this was the last, possibly unfinished word and we are doing prefix search
Word() : WordSegmenter::Word(), found_pos(NULL), found_len(0), is_last(FALSE) {}
};
static BOOL IsDoubleQuote(UnicodePoint c);
BOOL TreatAsSpace(UnicodePoint c) const;
static BOOL FindPhrase(TVector<Word> *phrase, const uni_char *haystack);
static BOOL FindWord(Word &word, const uni_char *s, const uni_char *haystack, BOOL first_word);
static int CopyText(uni_char *&dst_ptr, const uni_char *from, const uni_char *end);
static int CopyResult(uni_char *&dst_ptr, Word &result, const OpStringC &start_tag, const OpStringC &end_tag);
static const uni_char *FindEnd(const uni_char *start, int length);
static const uni_char *FindStart(const uni_char *text, const uni_char *start, int length, int prefix_ratio);
const uni_char *m_query;
TVector<TVector<Word> *> m_phrases;
int m_phrase_flags;
};
/**
* @brief Used by PhraseFilter to get the document corresponding to a search
* result to be able to look for the actual phrase.
*/
template <typename T> class DocumentSource
{
public:
virtual ~DocumentSource() {}
/**
* Get the document associated with a search result.
*
* Since phrase filtering in worst case can take a long time, it might be
* necessary to abort the search (e.g. in search-as-you-type, if another letter
* has been written to the search query). To effect an abort, the DocumentSource
* may return NULL on all subsequent calls. Since NULL documents do not match,
* no further results will be added, and the filtering will be quickly finished.
*
* If several "records" are concatenated into one document, but phrases should
* not match across record boundaries (e.g. message subject + message body), the
* records may be separated using the form-feed character ('\f').
*
* @param item A search result, potentially matching
* @return the document associated with item, or NULL to abort the search
*/
virtual const uni_char *GetDocument(const T &item) = 0;
};
/**
* @brief A DocumentSource that automatically deletes the acquired documents.
*/
template <typename T> class AutoDeleteDocumentSource : public DocumentSource<T>
{
public:
AutoDeleteDocumentSource() : m_doc(NULL) {}
virtual ~AutoDeleteDocumentSource()
{
OP_DELETEA(m_doc);
}
virtual const uni_char *GetDocument(const T &item)
{
OP_DELETEA(m_doc);
m_doc = AcquireDocument(item);
return m_doc;
}
protected:
/**
* Get the document associated with a search result
* @param item A search result
* @return a document associated with item. Will be freed by the
* destructor of this class using OP_DELETEA().
*/
virtual uni_char *AcquireDocument(const T &item) = 0;
uni_char *m_doc;
};
/**
* @brief PhraseFilter is a SearchFilter to be used with FilterIterator.
*
* It uses a PhraseMatcher to match documents retrieved from a DocumentSource.
*/
template <typename T> class PhraseFilter : public SearchFilter<T>
{
public:
/**
* Construct a PhraseFilter
* @param query the query used for searching, presumably containing phrases
* @param doc_source The document source used to match phrases
* @param phrase_flags flags built up from PhraseMatcher::PhraseFlags, controlling what kind of phrase search is performed
*/
PhraseFilter(const uni_char *query, DocumentSource<T> &doc_source, int phrase_flags)
: m_doc_source(doc_source)
{
m_status = OpStatus::OK;
m_matcher = OP_NEW(PhraseMatcher, ());
if (m_matcher == NULL)
{
m_status = OpStatus::ERR_NO_MEMORY;
}
else if (OpStatus::IsError(m_status = m_matcher->Init(query, phrase_flags)) || m_matcher->Empty())
{
OP_DELETE(m_matcher);
m_matcher = NULL;
}
m_first_time = TRUE;
}
virtual ~PhraseFilter()
{
OP_DELETE(m_matcher);
}
/**
* @return TRUE if no phrases were found in the query
*/
virtual BOOL Empty() const { return m_matcher == NULL; }
/**
* @param item A search result
* @return TRUE if the document associated with the search result matches the phrase
*/
virtual BOOL Matches(const T &item) const
{
if (!m_first_time)
m_status = OpStatus::OK;
m_first_time = FALSE;
return m_matcher == NULL || m_matcher->Matches(m_doc_source.GetDocument(item));
}
CHECK_RESULT(virtual OP_STATUS Error(void) const) { return m_status; }
protected:
mutable OP_STATUS m_status;
mutable BOOL m_first_time;
PhraseMatcher *m_matcher;
DocumentSource<T> &m_doc_source;
};
#endif // PHRASESEARCH_H
|
#include <stdio.h>
#include <conio.h>
void main () {
clrscr();
int A[10][10],B[10][10];
int r,c,r2,c2;
printf("\n\n\t\tMATRIX A ");
printf("\n\n\tEnter the values for matrix A ");
printf("\n\n\tEnter number of Rows: ");
scanf("%d",&r);
printf("\n\n\tEnter number of Columns: ");
scanf("%d",&c);
for (int i=0; i<r; i++)
for(int j=0; j<c; j++)
scanf("%d",&A[i][j]);
printf("\n\n\tMATRIX B ");
printf("\n\n\tEnter the values for matrix B ");
printf("\n\n\tEnter number of Rows: ");
scanf("%d",&r2);
printf("\n\n\tEnter number of Columns: ");
scanf("%d",&c2);
for (int k=0; k<r2; k++)
for(int l=0; l<c2; l++)
scanf("%d",&B[k][l]);
printf("\n\n\tThe values of Matrix A is:\n");
for (i=0; i<r; i++) {
for(j=0; j<c; j++)
printf(" %d ",A[i][j]);
printf("\n");
}
printf("\n\n\tThe values of Matrix B is:\n");
for (k=0; k<r2; k++) {
for(l=0; l<c2; l++)
printf(" %d ",B[k][l]);
printf("\n");
}
getche();
}
|
#include "notification.h"
Notification::Notification(QObject *parent) :
QObject(parent)
{
Configuration conf;
ShowNotifications = conf.getValue("ShowNotifications").toBool();
}
void Notification::send(const QString &message)
{
if(!ShowNotifications) {
qDebug() << "Notification: " << message;
return;
}
QString service = "org.freedesktop.Notifications";
QString path = "/org/freedesktop/Notifications";
QString interface = "org.freedesktop.Notifications";
QString method = "Notify";
QList<QVariant> arguments;
arguments.append(QVariant(QString("Kfilebox")));
arguments.append(QVariant(quint32(0)));
arguments.append(QVariant(QString("kfilebox")));
arguments.append(QVariant("Kfilebox"));
arguments.append(QVariant(message));
arguments.append(QVariant(QStringList()));
arguments.append(QVariant(QVariantMap()));
arguments.append(QVariant((int)0));
QDBusMessage msg = QDBusMessage::createMethodCall(service, path, interface, method);
msg.setArguments(arguments);
QDBusConnection::sessionBus().call(msg);
}
|
#ifndef QuickCommandConverter_H
#define QuickCommandConverter_H
#include "platforms/mac/embrowser/EmBrowserQuick.h"
/** A class for converting betwwen internal command numbers and standard toolbox command IDs.
* In some circumstances, the system needs to enable some of our menu items depending on what it thinks they might do,
* the best example is the save dialog: It will want to control the enabled state of undo, cut, copy, paste, clear
* and select all. To do this is, the system has a very complicated set of rules for finding these items,
* based on command key equiv, position in toolbar, title and other things.
* To help it out, we actually use the standard system command numbers in the menu, where it makes sense (edit commands,
* new, open, close, print, quit, preferences), and then convert it back to the
* internal identifier, when we need to detemine enabled state or the item has been selected.
*/
class QuickCommandConverter
{
enum { arraySize = 16 };
public:
QuickCommandConverter();
UInt32 AddCommandPair(EmQuickMenuCommand inQuickCommand, UInt32 inHICommandID);
EmQuickMenuCommand GetQuickCommandFromHICommand(UInt32 hiMenuEquv);
private:
int mCount;
EmQuickMenuCommand mQuickCommands[arraySize];
UInt32 mHICommandIDs[arraySize];
};
extern QuickCommandConverter *gQuickCommandConverter;
#endif // HICommandConverter_H
|
#include "main_window.h"
#include "qtomato.h"
#include "new_task_dialog.h"
#include "task_widget.h"
#include "task_data_widget.h"
#include "time_dialog.h"
#include "timer.h"
#include <QTabWidget>
#include <QMenuBar>
#include <iostream>
TomatoMainWindow::TomatoMainWindow( QWidget* parent ) : QMainWindow( parent )
{
tomato = new QTomato;
timer = new TomatoTimer;
mainWidget = new QTabWidget;
setCentralWidget( mainWidget );
taskWidget = new TaskWidget;
mainWidget->addTab( taskWidget, tr("main page") );
newTaskDialog = new NewTaskDialog;
taskDataWidget = new TaskDataWidget;
workingDialog = new TimeDialog;
workingDialog->setWindowTitle( "working" );
workingDialog->setModal( true );
restingDialog = new TimeDialog;
restingDialog->setWindowTitle( "resting" );
restingDialog->setModal( true );
QFont font;
font.setPointSize( 30 );
restingDialog->setFont( font );
createMenuBar();
connect( taskWidget, SIGNAL(start()),
this, SLOT(start()) );
connectUpdateData();
connectDataStream();
connectTimer();
connect( taskWidget, SIGNAL(workTimeChanged(int)),
this, SLOT(changeWorkTime(int)) );
connect( taskWidget, SIGNAL(restTimeChanged(int)),
this, SLOT(changeRestTime(int)) );
load();
}
TomatoMainWindow::~TomatoMainWindow( void )
{
delete addTask;
delete fileMenu;
delete newTaskDialog;
delete showData;
delete dataMenu;
delete taskDataWidget;
delete taskWidget;
delete tomato;
delete workingDialog;
delete restingDialog;
delete mainWidget;
}
void TomatoMainWindow::load( void )
{
tomato->load();
taskWidget->load();
newTaskDialog->load();
}
void TomatoMainWindow::createMenuBar( void )
{
fileMenu = new QMenu( tr("file") );
addTask = new QAction( tr("new task"), this ) ;
fileMenu->addAction( addTask );
menuBar()->addMenu( fileMenu );
connect( addTask, SIGNAL(triggered()),
newTaskDialog, SLOT(show()) );
dataMenu = new QMenu( tr("data") );
showData = new QAction( tr("show data"), this );
dataMenu->addAction(showData);
menuBar()->addMenu(dataMenu);
connect( showData, SIGNAL(triggered()),
taskDataWidget, SLOT(show()) );
}
void TomatoMainWindow::connectDataStream( void )
{
connect( tomato, SIGNAL(updateTask(const std::vector<QTask>&)),
taskWidget, SLOT(updateTask(const std::vector<QTask>&)) );
connect( tomato, SIGNAL(updateTaskData(const std::vector<QTaskData>&)),
taskDataWidget, SLOT(updateTaskData(const std::vector<QTaskData>)) );
}
void TomatoMainWindow::connectUpdateData( void )
{
connect( newTaskDialog, SIGNAL(addTask(QTask)),
tomato, SLOT(addTask(QTask)) );
connect( taskWidget, SIGNAL(chooseTask(int, bool)),
tomato, SLOT(chooseTask(int, bool)) );
connect( taskWidget, SIGNAL(finishTask(int, bool)),
tomato, SLOT(finishTask(int, bool)) );
connect( tomato, SIGNAL(updateTask(QTask)),
taskWidget, SLOT(updateTask(QTask)) );
}
void TomatoMainWindow::connectTimer( void )
{
connect( timer, SIGNAL(finishWork()),
this, SLOT(finishWork()) );
connect( timer, SIGNAL(finishRest()),
this, SLOT(finishRest()) );
connect( timer, SIGNAL(displayTime(int)),
workingDialog, SLOT(changeTime(int)) );
connect( timer, SIGNAL(displayTime(int)),
restingDialog, SLOT(changeTime(int)) );
}
void TomatoMainWindow::start( void )
{
tomato->start( workTime, restTime );
timer->start();
workingDialog->show();
}
void TomatoMainWindow::finishRest( void )
{
tomato->end();
restingDialog->hide();
}
void TomatoMainWindow::finishWork( void )
{
workingDialog->hide();
restingDialog->showFullScreen();
}
void TomatoMainWindow::changeRestTime( int minutes )
{
this->restTime = minutes;
timer->setTime( workTime, restTime );
}
void TomatoMainWindow::changeWorkTime( int minutes )
{
this->workTime = minutes;
timer->setTime( workTime, restTime );
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 1999-2004
*/
#ifndef ES_ARRAY_OBJECT_H
#define ES_ARRAY_OBJECT_H
#include "modules/ecmascript/carakan/src/object/es_object.h"
#include "modules/ecmascript/carakan/src/object/es_indexed.h"
class ES_Array
//: public ES_Object
{
public:
static ES_Object *Make(ES_Context *context, ES_Global_Object *global_object, unsigned capacity = 0, unsigned length = 0);
static ES_Object *MakePrototypeObject(ES_Context *context, ES_Global_Object *global_object, ES_Class *&instance);
static void SetLength(ES_Context *context, ES_Object *array, const ES_Value_Internal &length);
};
#endif // ES_ARRAY_OBJECT_H
|
/*
* This file is part of OctoMap - An Efficient Probabilistic 3D Mapping
* Framework Based on Octrees
* http://octomap.github.io
*
* Copyright (c) 2009-2014, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved. License for the viewer octovis: GNU GPL v2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#ifndef VIEWERSETTINGSPANEL_H
#define VIEWERSETTINGSPANEL_H
#include <math.h>
#include <QWidget>
#include "ui_ViewerSettingsPanel.h"
#define _TREE_MAX_DEPTH 16
class ViewerSettingsPanel : public QWidget
{
Q_OBJECT
public:
ViewerSettingsPanel(QWidget *parent = 0);
~ViewerSettingsPanel();
public slots:
void setNumberOfScans(unsigned scans);
void setCurrentScan(unsigned scan);
void setResolution(double resolution);
void setTreeDepth(int depth);
private slots:
void on_firstScanButton_clicked();
void on_lastScanButton_clicked();
void on_nextScanButton_clicked();
void on_fastFwdScanButton_clicked();
signals:
void treeDepthChanged(int depth);
void addNextScans(unsigned scans);
void gotoFirstScan();
private:
void scanProgressChanged();
void leafSizeChanged();
Ui::ViewerSettingsPanelClass ui;
unsigned m_currentScan;
unsigned m_numberScans;
unsigned m_treeDepth;
double m_resolution;
};
#endif // VIEWERSETTINGSPANEL_H
|
/*
Temporal difference (TD) learning methods
SARSA(Lambda)
With replacing traces
Action selection : e-greedy policy = f(Q values)
Compilation instructions:
gcc -o sarsa_lambda -lm -g sarsa_lambda.c
then run ./sarsa_lambda
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define min(x, y) ((x <= y) ? x : y)
#define max(x, y) ((x >= y) ? x : y)
#define Alpha 0.1
#define Epsilon 0.01
/* size of the maze */
#define ROW 6
#define COL 7
#define A 4
#define S 16 /* number of states */
/* Goal */
#define G_i 3
#define G_j 5
#define EPISODES 150 /* in hundreds */
#define MaxSteps 1000 /* maximum number of tries per episode */
/* environment : 1=obstacle 0=no obstacle */
int ENV[ 7][ 6] = {{1,1,1,1,1,1},
{1,0,0,1,0,1},
{1,0,0,0,0,1},
{1,0,1,1,0,1},
{1,1,1,1,0,1},
{1,1,1,0,0,1},
{1,1,1,1,1,1}};
/* predeclarations */
int select_action(float Q[S][A], int s);
void InitQfunc(float Q[S][A]);
int InitState(int *x, int *y, float e[S][A]);
int GetState(int x, int y);
int reward(int x, int y, int a);
int NextState(int *x,int *y,int a);
void UpdateQfunc(int s, int a, int r, float Q[S][A], int next_s, int next_a, float e[S][A],float Gamma,float Lambda,float GtotheL);
void end();
void main(int argc, char *argv[])
{
float Q[S][A]; /* Q state-action values */
float e[S][A]; /* eligibility traces */
float Gamma, Lambda, GtotheL;
int a_t;
int s;
int x,y;
int next_s, next_a;
int r;
int sum_r,avg_r;
int i,j,cnt;
int sum_steps,sum_failures;
Gamma = 0.9; /* discount factor */
Lambda = 0.9; /* lambda parameter in SARSA(lambda) */
GtotheL = 0.9095; /* Gamma to the Lambda */
srand48(123456789);
InitQfunc(Q);
sum_steps = 0;
sum_failures = 0;
for(i=0;i<(EPISODES);i++) {
avg_r = 0.0;
for(j=0;j<100;j++) {
s=InitState(&x,&y,e);
cnt=0;
sum_r=0;
/* repeat for a certain maximum number of steps or until goal is reached */
while(((x != G_i) || (y != G_j)) && (cnt < MaxSteps)) {
a_t = select_action(Q,s); /* select an action */
next_s = NextState(&x,&y,a_t); /* apply action */
r = reward(x,y,a_t); /* receive external reinforcement */
next_a = select_action(Q,next_s); /* select next action */
/* update Q values */
UpdateQfunc(s,a_t,r,Q,next_s,next_a,e,Gamma,Lambda,GtotheL);
/* update current state */
s = next_s;
cnt++;
sum_r +=r;
}
avg_r +=sum_r;
}
/* print the average of sum of gained reward */
printf("\n%f",avg_r/100.0);
}
end(Q);
}
int InitState(int *x,int *y,float e[S][A])
{
int i,j,s;
*x = lrand48()%2 + 1;
*y = lrand48()%3 + 1;
s = GetState(*x,*y);
for(i=0;i<S;i++)
for(j=0;j<A;j++)
e[i][j] = 0.0;
return(s);
}
int select_action(float Q[S][A],int s)
{
int i;
int action;
int a_qmax;
a_qmax =0;
/* find the action with maximum Q value, given a certain state s */
for(i=1;i<A;i++)
if(Q[s][i] > Q[s][a_qmax])
a_qmax = i;
action = a_qmax;
/* chose the action with maximum Q value with probability 1-epsilon %
else, chose a random action */
if(drand48() < Epsilon)
action=lrand48()%A;
return(action);
}
void InitQfunc(float Q[S][A])
{
int s,a;
for(s=0;s<S;s++)
for(a=0;a<A;a++)
Q[s][a] = 0.0;
}
int reward(int x, int y, int a)
{
if((x == G_i) && (y == G_j))
return(0);
else return(-1);
}
int GetState(int x, int y)
{
int s = 0;
if(ENV[y-1][x]) s++;
if(ENV[y][x-1]) s +=2;
if(ENV[y][x+1]) s +=4;
if(ENV[y+1][x]) s +=8;
return(s);
}
int NextState(int *x, int *y, int a)
{
int i,j;
int s;
switch(a) {
case 0: if(!ENV[*y-1][*x])
*y -= 1;
break;
case 1: if(!ENV[*y][*x+1])
*x += 1;
break;
case 2: if(!ENV[*y+1][*x])
*y += 1;
break;
case 3: if(!ENV[*y][*x-1])
*x -= 1;
break;
}
s = GetState(*x,*y);
return(s);
}
void UpdateQfunc(int s, int a, int r, float Q[S][A], int next_s, int next_a, float e[S][A],float Gamma,float Lambda,float GtotheL)
{
int i,j;
float TDerr;
/* compute TD error */
if(next_s != -1)
TDerr = (float)r+Gamma*Q[next_s][next_a] - Q[s][a];
else TDerr = (float)r - Q[s][a];
/* replacing traces: */
e[s][a] = 1;
for(i=0;i<S;i++)
for(j=0;j<A;j++) {
/* update Q values */
Q[i][j] += Alpha*TDerr*e[i][j];
e[i][j] = (float)(GtotheL*e[i][j]);
}
}
void end(float Q[S][A])
{
int i,j;
int a_qmax;
printf("\nLearned policy:\n");
for(i=0;i<S;i++) {
a_qmax = 0;
for(j=1;j<A;j++)
if(Q[i][j] > Q[i][a_qmax])
a_qmax = j;
printf("\nA[%d] = %d",i,a_qmax);
}
}
|
#include <iostream>
#include <vector>
#include <fstream>
class Database
{
private:
/* data */
protected:
//protected
public:
Database(/* args */)
{
//constructor
}
~Database()
{
//destructor
}
// 2D string vector
std::vector<std::vector<std::string>> mainList;
std::string name;
void write(std::vector<std::vector<std::string>> mainList);
std::vector<std::vector<std::string>> read();
};
|
// Copyright (c) 2012-2017 The Cryptonote developers
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <cstdint>
#include "CryptoNoteProtocol/ICryptoNoteProtocolObserver.h"
#include "CryptoNoteProtocol/ICryptoNoteProtocolQuery.h"
class ICryptoNoteProtocolQueryStub: public cn::ICryptoNoteProtocolQuery {
public:
ICryptoNoteProtocolQueryStub() : peers(0), observedHeight(0), synchronized(false) {}
virtual bool addObserver(cn::ICryptoNoteProtocolObserver* observer) override;
virtual bool removeObserver(cn::ICryptoNoteProtocolObserver* observer) override;
virtual uint32_t getObservedHeight() const override;
virtual size_t getPeerCount() const override;
virtual bool isSynchronized() const override;
void setPeerCount(uint32_t count);
void setObservedHeight(uint32_t height);
void setSynchronizedStatus(bool status);
private:
size_t peers;
uint32_t observedHeight;
bool synchronized;
};
|
#pragma once
#include "../framework.h"
#include "../defines.h"
#include "gl_strings.h"
#include "gl_command.h"
#include <string>
#include <queue>
#include <vector>
namespace glmock
{
//
// Implementation of the validation exception - used by the default behaviour for when errors occure in the
// mock framework.
class ValidationException : public IValidationException
{
public:
ValidationException(CommandError* errors, unsigned int count);
~ValidationException();
private:
CommandError* mErrors;
unsigned int mCount;
};
class GLFramework : public IFramework
{
private:
static GLFramework& Get();
//
// @return The next command in the prediction queue; NULL if no commands are available.
static GLCommand* TryGet();
public:
GLFramework(IErrorCallback* calback);
~GLFramework();
//
// Add an error for when a bad parameter was supplied to a function
static void AddBadParameter(const char* function, const char* paramName, std::string expected, std::string actual);
//
// Add an error if a bad/invalid function was called.
static void AddBadFunctionCalled(const char* expected, const char* actual);
//
// Add an error if a bad/invalid function was called.
static void AddUnspecifiedFunctionCalled(const char* expected);
// IFramework
public:
virtual void glGetIntegerv(GLenum pname, GLint* params);
virtual void glDeleteTextures(GLsizei n, const GLuint* textures);
virtual void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width,
GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
virtual void glBindTexture(GLenum target, GLuint texture);
virtual void glBlendFunc(GLenum sfactor, GLenum dfactor);
virtual IReturns<GLenum>* glGetError();
virtual void glGenTextures(GLsizei n, GLuint* textures);
virtual void glFlush();
virtual void glUseProgram(GLuint program);
public:
//
// Retrieves the element at the top of the queue
template<class T>
static T* CastAndGet(const char* expected) {
GLCommand* cmd = TryGet();
if(cmd == 0) {
AddUnspecifiedFunctionCalled(expected);
return 0;
}
T* casted = dynamic_cast<T*>(cmd);
if(casted == 0) {
AddBadFunctionCalled(expected, cmd->Name);
if(cmd != 0)
delete cmd;
}
return casted;
}
private:
std::queue<GLCommand*> mCommands;
IErrorCallback* mErrorCallback;
};
extern std::string IntToString(GLint val);
extern std::string FloatToString(GLfloat val);
extern std::string DoubleToString(GLdouble val);
}
|
//
// Created by 周华 on 2021/5/4.
//
#include "Ray.h"
|
#include "utils/process_utils.hpp"
#include "utils/time_utils.hpp"
#include "config/options_ptts.hpp"
#include "config/utils.hpp"
#include "config/player_ptts.hpp"
#include "player/cplayer_mgr.hpp"
#include "log.hpp"
#include <iostream>
#include <boost/program_options.hpp>
#include <string>
using namespace std;
using namespace nora;
namespace bpo = boost::program_options;
namespace pc = proto::config;
int main(int argc, char *argv[]) {
// main thread
string server;
string host;
unsigned short port;
int login_count = 0;
int login_frequency = 100;
int behavior_tree_root = 10000;
try {
bpo::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("server,s", bpo::value<string>(&server)->default_value("10.1.1.90:10217"), "set login server ip, e.g. '10.1.1.90:10217'")
("count,c", bpo::value<int>(), "set player login count")
("frequency,f", bpo::value<int>(), "set per second player login frequency")
("behavior_tree_root,r", bpo::value<int>(), "set player behavior tree root")
;
bpo::variables_map vm;
bpo::store(bpo::parse_command_line(argc, argv, desc), vm);
bpo::notify(vm);
if(vm.count("help")) {
cout << desc << endl;
return 1;
}
if(vm.count("server")) {
server = vm["server"].as<string>();
}
if (vm.count("count")) {
login_count = vm["count"].as<int>();
}
if (vm.count("frequency")) {
login_frequency = vm["frequency"].as<int>();
}
if (vm.count("behavior_tree_root")) {
behavior_tree_root = vm["behavior_tree_root"].as<int>();
}
host = split_string(server, ':')[0];
stringstream stream;
stream << split_string(server, ':')[1];
stream >> port;
} catch (const exception& e) {
cerr << "error: " << e.what() << endl;
return 1;
}
srand(time(0));
deamonize(argv);
write_pid_file("robot_pid");
// open robot thread
auto st = make_shared<service_thread>("robot");
clock::instance().start(st);
PTTS_LOAD(options);
auto ptt = PTTS_GET_COPY(options, 1u);
init_log("robot", ptt.level());
config::load_config();
config::load_dirty_word();
config::check_config();
PTTS_SET_FUNCS(robot);
PTTS_LOAD(robot);
PTTS_MVP(robot);
PTTS_MVP(options);
auto cpm = make_shared<scene::cplayer_mgr>(st, login_count, login_frequency, behavior_tree_root);
st->async_call(
[host, port, cpm] {
cpm->start(host, port);
});
st->run();
return 0;
}
|
#include "stdafx.h"
#include "mainGame.h"
//=============================================================
// ## 초기화 ## init()
//=============================================================
HRESULT mainGame::init()
{
gameNode::init();
//이곳에서 초기화를 한다
//백그라운드 이미지 초기화
IMAGEMANAGER->addImage("백그라운드", "image/backGround.bmp", 600, 4288);
IMAGEMANAGER->addImage("메인화면", "image/inGameStart.bmp", WINSIZEX, WINSIZEY);
IMAGEMANAGER->addImage("스타트버튼", "image/inGameStartButton.bmp", 305, 57, true, RGB(255, 0, 255));
IMAGEMANAGER->addFrameImage("로딩", "image/loading.bmp", 3000, 800, 5, 1);
_main = IMAGEMANAGER->findImage("메인화면");
_startButton = IMAGEMANAGER->findImage("스타트버튼");
_loading = IMAGEMANAGER->findImage("로딩");
_count = 0;
_index = 0;
//루프용 변수 초기화
_loopX = _loopY = 0;
time = 0;
_gameStart = false;
_load = false;
//플레이어 클래스 초기화
_player = new player;
_player->init();
/*_enemy = new enemy;
_enemy->init();*/
_loadLoop = false;
alpha = 0;
timecheck = false;
return S_OK;
}
//=============================================================
// ## 해제 ## release()
//=============================================================
void mainGame::release()
{
gameNode::release();
//이미지 클래스를 나갈때까진 사용할 일 없다
//동적할당 new를 사용했다면 이곳에서 SAFE_DELETE() 사용한다
//플레이어 클래스 해제
_player->release();
SAFE_DELETE(_player);
/*_enemy->release();
SAFE_DELETE(_enemy);*/
}
//=============================================================
// ## 업데이트 ## update()
//=============================================================
void mainGame::update()
{
gameNode::update();
//이곳에서 계산식, 키보드, 마우스등등 업데이트를 한다
//간단하게 이곳에서 코딩한다고 생각하면 된다
//충돌처리
time++;
if (INPUT->GetKeyDown('1')) {
_gameStart = true;
_load = true;
time = 0;
}
if (!_gameStart) {
//time = 0;
if (time % 60 == 0)
{
if (!timecheck) {
alpha = 255;
timecheck = true;
}
else {
alpha = 0;
timecheck = false;
}
}
}
else {
if (_load) {
loadAnim();
}
else {
_loopY--;
//플레이어 클래스 업데이트
_player->update();
//_enemy->update();
}
}
}
//=============================================================
// ## 렌더 ## render()
//=============================================================
void mainGame::render()
{
//흰색 빈 비트맵 (이것은 렌더에 그냥 두기)
PatBlt(getMemDC(), 0, 0, WINSIZEX, WINSIZEY, BLACKNESS);
//=============================================================
//이곳에서 WM_PAINT에서 했던것을 처리하면 된다
//백그라운드 렌더
//IMAGEMANAGER->render("백그라운드", getMemDC());
//백그라운드 루프렌더
if (_gameStart && !_load) {
RECT rc = RectMake(0, 0, WINSIZEX, 4288);
IMAGEMANAGER->loopRender("백그라운드", getMemDC(), &rc, _loopX, _loopY);
//플레이어 렌더
_player->render();
//_enemy->render();
}
if (!_gameStart && !_load) {
_main->render(getMemDC(), 0, 0);
//_startButton->render(getMemDC(), WINSIZEX / 2 - 150, WINSIZEY - 200);
_startButton->alphaRender(getMemDC(), WINSIZEX / 2 - 150, WINSIZEY - 200, alpha);
}
if (_load)
{
_loading->frameRender(getMemDC(), 0, 0);
}
//=============================================================
//백버퍼의 내용을 화면DC에 그린다 (이것도 렌더에 그냥 두기)
this->getBackBuffer()->render(getHDC());
}
void mainGame::loadAnim()
{
_count++;
_loading->setFrameY(0);
if (!_loadLoop)
{
if (_count % 20 == 0)
{
if (_index < 4)
{
_index++;
}
_loading->setFrameX(_index);
if (_index == 4)
{
_loadLoop = true;
}
}
}
else {
if (time % 30 == 0)
{
if (timecheck)
{
_index = 4;
timecheck = false;
}
else {
_index = 3;
timecheck = true;
}
}
_loading->setFrameX(_index);
if (time % 300 == 0) _load = false;
}
}
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000005
int gcd(int a,int b){
if(!a)return 1;if(!b)return a;
if(a<0) a=-a; for(int t;b;t=a%b,a=b,b=t);
return a;
}
bool vis[maxn];
int main(){
int n;
while(cin>>n){
memset(vis,false,sizeof(vis));
int t=(int)sqrt(n);
// cout<<t<<" t\n";
int ans=0;
for(int i=1;i<=t;i++){
int s=(int)sqrt(n-i*i);
// cout<<s<<" s\n";
for(int j=i+1;j<=s;j++){
int x=2*i*j;
int y=j*j-i*i;
int z=i*i+j*j;
// cout<<x<<' '<<y<<' '<<z<<"\n";
if(i%2!=j%2&&gcd(i,j)==1){
ans++;
vis[x]=vis[y]=vis[z]=true;
}
for(int k=2;k*z<=n;k++){
vis[k*x]=vis[k*y]=vis[k*z]=true;
}
}
}
int ans1=0;
for(int i=1;i<=n;i++){
if(!vis[i])
ans1++;
}
cout<<ans<<" "<<ans1<<"\n";
}
return 0;
}
|
/*
This demo showcases some components of cvui being used to control
the application of the Canny edge algorithm to a loaded image.
Code licensed under the MIT license
*/
#include <opencv2/opencv.hpp>
#define CVUI_IMPLEMENTATION
#include "cvui.h"
#define WINDOW_NAME "CVUI Canny Edge"
#define WINDOW_NAME "CVUI Test"
int main(int argc, const char *argv[])
{
cv::Mat frame = cv::Mat(300, 600, CV_8UC3);
bool checked = false;
bool checked2 = true;
int count = 0;
double countFloat = 0.0;
double trackbarValue = 0.0;
// Init a OpenCV window and tell cvui to use it.
// If cv::namedWindow() is not used, mouse events will
// not be captured by cvui.
cv::namedWindow(WINDOW_NAME);
cvui::init(WINDOW_NAME);
while (true) {
// Fill the frame with a nice color
frame = cv::Scalar(49, 52, 49);
// Show some pieces of text.
cvui::text(frame, 50, 30, "Hey there!");
// You can also specify the size of the text and its color
// using hex 0xRRGGBB CSS-like style.
cvui::text(frame, 200, 30, "Use hex 0xRRGGBB colors easily", 0.4, 0xff0000);
// Sometimes you want to show text that is not that simple, e.g. strings + numbers.
// You can use cvui::printf for that. It accepts a variable number of parameter, pretty
// much like printf does.
cvui::printf(frame, 200, 50, 0.4, 0x00ff00, "Use printf formatting: %d + %.2f = %f", 2, 3.2, 5.2);
// Buttons will return true if they were clicked, which makes
// handling clicks a breeze.
if (cvui::button(frame, 50, 60, "Button")) {
std::cout << "Button clicked" << std::endl;
}
// If you do not specify the button width/height, the size will be
// automatically adjusted to properly house the label.
cvui::button(frame, 200, 70, "Button with large label");
// You can tell the width and height you want
cvui::button(frame, 410, 70, 15, 15, "x");
// Window components are useful to create HUDs and similars. At the
// moment, there is no implementation to constraint content within a
// a window.
cvui::window(frame, 50, 120, 120, 100, "Window");
// The counter component can be used to alter int variables. Use
// the 4th parameter of the function to point it to the variable
// to be changed.
cvui::counter(frame, 200, 120, &count);
// Counter can be used with doubles too. You can also specify
// the counter's step (how much it should change
// its value after each button press), as well as the format
// used to print the value.
cvui::counter(frame, 320, 120, &countFloat, 0.1, "%.1f");
// The trackbar component can be used to create scales.
// It works with all numerical types (including chars).
cvui::trackbar(frame, 420, 110, 150, &trackbarValue, 0., 50.);
// Checkboxes also accept a pointer to a variable that controls
// the state of the checkbox (checked or not). cvui::checkbox() will
// automatically update the value of the boolean after all
// interactions, but you can also change it by yourself. Just
// do "checked = true" somewhere and the checkbox will change
// its appearance.
cvui::checkbox(frame, 200, 160, "Checkbox", &checked);
cvui::checkbox(frame, 200, 190, "A checked checkbox", &checked2);
// Display the lib version at the bottom of the screen
cvui::printf(frame, frame.cols - 80, frame.rows - 20, 0.4, 0xCECECE, "cvui v.%s", cvui::VERSION);
// This function must be called *AFTER* all UI components. It does
// all the behind the scenes magic to handle mouse clicks, etc.
cvui::update();
// Show everything on the screen
cv::imshow(WINDOW_NAME, frame);
// Check if ESC key was pressed
if (cv::waitKey(20) == 27) {
break;
}
}
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'CHelpInfo.ui'
**
** Created by: Qt User Interface Compiler version 5.3.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CHELPINFO_H
#define UI_CHELPINFO_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_CHelpInfo
{
public:
QGridLayout *gridLayout;
QFrame *frame;
QGridLayout *gridLayout_2;
QLabel *label;
QToolButton *tbtn_add;
QSpacerItem *horizontalSpacer;
QToolButton *tbtn_delete;
QTableWidget *tableWidget;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer_2;
QPushButton *btn_Save;
QPushButton *btn_SaveXml;
void setupUi(QWidget *CHelpInfo)
{
if (CHelpInfo->objectName().isEmpty())
CHelpInfo->setObjectName(QStringLiteral("CHelpInfo"));
CHelpInfo->resize(512, 363);
gridLayout = new QGridLayout(CHelpInfo);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
gridLayout->setVerticalSpacing(2);
frame = new QFrame(CHelpInfo);
frame->setObjectName(QStringLiteral("frame"));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
gridLayout_2 = new QGridLayout(frame);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
gridLayout_2->setContentsMargins(0, 3, 0, 0);
label = new QLabel(frame);
label->setObjectName(QStringLiteral("label"));
gridLayout_2->addWidget(label, 0, 0, 1, 1);
tbtn_add = new QToolButton(frame);
tbtn_add->setObjectName(QStringLiteral("tbtn_add"));
QIcon icon;
icon.addFile(QStringLiteral(":/Resources/plus.png"), QSize(), QIcon::Normal, QIcon::Off);
tbtn_add->setIcon(icon);
gridLayout_2->addWidget(tbtn_add, 0, 2, 1, 1);
horizontalSpacer = new QSpacerItem(317, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
gridLayout_2->addItem(horizontalSpacer, 0, 1, 1, 1);
tbtn_delete = new QToolButton(frame);
tbtn_delete->setObjectName(QStringLiteral("tbtn_delete"));
QIcon icon1;
icon1.addFile(QStringLiteral(":/Resources/minus.png"), QSize(), QIcon::Normal, QIcon::Off);
tbtn_delete->setIcon(icon1);
gridLayout_2->addWidget(tbtn_delete, 0, 3, 1, 1);
gridLayout->addWidget(frame, 0, 0, 1, 1);
tableWidget = new QTableWidget(CHelpInfo);
if (tableWidget->columnCount() < 2)
tableWidget->setColumnCount(2);
QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem);
QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1);
tableWidget->setObjectName(QStringLiteral("tableWidget"));
QFont font;
font.setPointSize(9);
tableWidget->setFont(font);
tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
tableWidget->setAlternatingRowColors(true);
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
tableWidget->setTextElideMode(Qt::ElideRight);
tableWidget->horizontalHeader()->setStretchLastSection(true);
tableWidget->verticalHeader()->setVisible(false);
gridLayout->addWidget(tableWidget, 1, 0, 1, 1);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer_2);
btn_Save = new QPushButton(CHelpInfo);
btn_Save->setObjectName(QStringLiteral("btn_Save"));
horizontalLayout->addWidget(btn_Save);
btn_SaveXml = new QPushButton(CHelpInfo);
btn_SaveXml->setObjectName(QStringLiteral("btn_SaveXml"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(btn_SaveXml->sizePolicy().hasHeightForWidth());
btn_SaveXml->setSizePolicy(sizePolicy);
horizontalLayout->addWidget(btn_SaveXml);
gridLayout->addLayout(horizontalLayout, 2, 0, 1, 1);
retranslateUi(CHelpInfo);
QMetaObject::connectSlotsByName(CHelpInfo);
} // setupUi
void retranslateUi(QWidget *CHelpInfo)
{
CHelpInfo->setWindowTitle(QApplication::translate("CHelpInfo", "CHelpInfo", 0));
label->setText(QApplication::translate("CHelpInfo", "\345\256\242\346\210\267\347\253\257\347\273\264\346\212\244\344\277\241\346\201\257\347\274\226\350\276\221", 0));
#ifndef QT_NO_TOOLTIP
tbtn_add->setToolTip(QApplication::translate("CHelpInfo", "\346\267\273\345\212\240\350\275\257\344\273\266", 0));
#endif // QT_NO_TOOLTIP
tbtn_add->setText(QString());
#ifndef QT_NO_TOOLTIP
tbtn_delete->setToolTip(QApplication::translate("CHelpInfo", "\345\210\240\351\231\244", 0));
#endif // QT_NO_TOOLTIP
tbtn_delete->setText(QString());
QTableWidgetItem *___qtablewidgetitem = tableWidget->horizontalHeaderItem(0);
___qtablewidgetitem->setText(QApplication::translate("CHelpInfo", "\346\240\207\351\242\230", 0));
QTableWidgetItem *___qtablewidgetitem1 = tableWidget->horizontalHeaderItem(1);
___qtablewidgetitem1->setText(QApplication::translate("CHelpInfo", "\345\206\205\345\256\271", 0));
btn_Save->setText(QApplication::translate("CHelpInfo", "\344\277\235\345\255\230", 0));
btn_SaveXml->setText(QApplication::translate("CHelpInfo", "\347\224\237\346\210\220 XML", 0));
} // retranslateUi
};
namespace Ui {
class CHelpInfo: public Ui_CHelpInfo {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CHELPINFO_H
|
#include "Game.h"
Game::Game(void)
{
try
{
//RENDERING SETUP
// Seed for generating random numbers with rand()
srand((unsigned int)time(0));
// Setup window
window = new Window(window_width_g, window_height_g, window_title_g);
// Set up z-buffer for rendering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Enable Alpha blending
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
glDepthMask(GL_TRUE); // allow writes to depth buffer
// Set up renderer
renderer = new Renderer("spriteShader.vert", "fireParticleShader.vert", "explosionParticleShader.vert", "fragmentShader.frag", "textShader.vert", "textShader.frag");
setupMenu();
}
catch (exception &e)
{
// print exception and sleep so error can be read
PrintException(e);
this_thread::sleep_for(chrono::milliseconds(100000));
}
}
Game::~Game(void)
{
delete window;
delete renderer;
}
void Game::setupMenu(void)
{
state = 0;
currency = 0;
waves = 0;
powerup = 0;
pickup = false;
towers.clear();
enemies.clear();
projectiles.clear();
wizards.clear();
powerups.clear();
explosions.clear();
roundInfo = queue<array<int, 4>>();
background = "Title_Screen";
}
void Game::setupLevel(string level) {
ifstream levelFile("assets/level_" + level + ".txt");
string line;
//set background image (the maze)
getline(levelFile, line);
background = strdup(line.c_str());
cout << background << "setup" << endl;
//set currency
getline(levelFile, line);
currency = stoi(line);
//set start and end node positions
getline(levelFile, line);
maze = new Maze(40, 30, "assets/" + line);
//load rounds into round variable
//in the file the rouns are stored in lines of x,y,z where x == num zombies, y == num skeletons, z == num necromancers, w == num waves
//loop over the remaining lines and store in the info into round info
while (getline(levelFile, line))
{
roundInfo.push({ stoi(line), stoi(line.substr(line.find(",") + 1)), stoi(line.substr(line.find(",", line.find(",") + 1) + 1)), stoi(line.substr(line.find(",", line.find(",", line.find(",") + 1) + 1) + 1))});
}
//reset base health
baseHealth = 10;
}
void Game::input(double dTime) {
//menu state
if (state == 0) {
//pressing 1, 2, or 3 will begin levels one to three
if (glfwGetKey(Window::getWindow(), GLFW_KEY_1) == GLFW_PRESS)
{
setupLevel("1");
level = "1";
state = 1;
}
else if (glfwGetKey(Window::getWindow(), GLFW_KEY_2) == GLFW_PRESS)
{
setupLevel("2");
level = "2";
state = 1;
}else if (glfwGetKey(Window::getWindow(), GLFW_KEY_3) == GLFW_PRESS)
{
setupLevel("3");
level = "3";
state = 1;
}
//escape or closing the window will exit the game
else if (glfwGetKey(Window::getWindow(), GLFW_KEY_ESCAPE) == GLFW_PRESS || glfwWindowShouldClose(window->getWindow())) {state = 2;}
}
//game state
else if (state == 1)
{
//pressing q returns to the menu, quitting the window closes the game
if (glfwGetKey(Window::getWindow(), GLFW_KEY_Q) == GLFW_PRESS) {
state = 0;
setupMenu();
}
else if (glfwWindowShouldClose(window->getWindow())) { state = 2; }
//if mouse is down and was up last tick, allow the player to place a tower
if (glfwGetMouseButton(Window::getWindow(), GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS && mouseWasUp)
{
// get the cursor location on the screen
double mouseX, mouseY;
glfwGetCursorPos(Window::getWindow(), &mouseX, &mouseY);
Node *position = maze->getNodeFromCoords(mouseX / (window_width_g / 2) - 1, 1 - mouseY / (window_height_g / 2));//get the node at that position
if (!position->isOccupied())
{
// Placing a Lightning Tower and buying the tower
if (glfwGetKey(Window::getWindow(), GLFW_KEY_L) == GLFW_PRESS && currency >= LIGHTNINGTOWERPRICE)
{
towers.push_back(new LightningTower(glm::vec3(mouseX / (window_width_g / 2) - 1, 1 - mouseY / (window_height_g / 2), 0)));
currency -= LIGHTNINGTOWERPRICE;
position->setTowerHere(true);
}
// Placing a Fire Tower and buying the tower
else if (glfwGetKey(Window::getWindow(), GLFW_KEY_F) == GLFW_PRESS && currency >= FIRETOWERPRICE)
{
towers.push_back(new FireTower(glm::vec3(mouseX / (window_width_g / 2) - 1, 1 - mouseY / (window_height_g / 2), 0)));
currency -= FIRETOWERPRICE;
position->setTowerHere(true);
}
// Placing an Ice Tower and buying the tower
else if (glfwGetKey(Window::getWindow(), GLFW_KEY_I) == GLFW_PRESS && currency >= ICETOWERPRICE)
{
towers.push_back(new IceTower(glm::vec3(mouseX / (window_width_g / 2) - 1, 1 - mouseY / (window_height_g / 2), 0)));
currency -= ICETOWERPRICE;
position->setTowerHere(true);
}
}
// if the mouse is in range of the powerup
// erase the power up
// increase the power up value
// set the pickup to true
for (int i = powerups.size() - 1; i >= 0; i--)
{
if ((mouseX / (window_width_g / 2) - 1) > powerups[i]->getPosition().x - powerups[i]->getScale().x /2
&& (mouseX / (window_width_g / 2) - 1) < powerups[i]->getPosition().x + powerups[i]->getScale().x / 2
&& (1 - mouseY / (window_height_g / 2)) > powerups[i]->getPosition().y - powerups[i]->getScale().y / 2
&& (1 - mouseY / (window_height_g / 2)) < powerups[i]->getPosition().y + powerups[i]->getScale().y / 2)
{
powerup++;
powerups.erase(powerups.begin() + i);
}
}
}
//wizard can be spawned by pressing w when and costs 3 powerup points, it is spawned with a path from one end on the maze to one start
if (glfwGetKey(Window::getWindow(), GLFW_KEY_W) == GLFW_PRESS && keyWasUp_w && powerup >= 3)
{
powerup -= 3;
stack<Node*> path = maze->getWizardPath();
wizards.push_back(new Wizard(path.top()->getPosition(), path));
}
//set keyWasUp to true if key is up this tick
keyWasUp_w = glfwGetKey(Window::getWindow(), GLFW_KEY_W) == GLFW_RELEASE;
//set mouseWasUp to true if mouse is up this tick
mouseWasUp = glfwGetMouseButton(Window::getWindow(), GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE;
}
}
void Game::update(double dTime) {
if (state == 1) {
//if round is over (all enemies are dead) repopulate enemies based on roundInfo
if (enemies.size() == 0) {
if (roundInfo.size() == 0) { setupMenu(); }//if no more rounds, level is complete, go back to menu
else {
// get the enemy path for the creeps and start position
stack<Node*> enemyPath = maze->getEnemyPath();
glm::vec3 startPosition = enemyPath.top()->getPosition();
//create zombies, skeletons, and necromancers and place them at the start node, with the enemy path
//each enemy gets a stagger to make them wait a bit before moving out of the spawn
float stagger = 0.0f;
for (int i = 0; i < roundInfo.front()[0]; i++) {
enemies.push_back(new Zombie(stagger, enemyPath, startPosition));
stagger += 0.5f;
cout << stagger;
}
for (int i = 0; i < roundInfo.front()[1]; i++) {
enemies.push_back(new Skeleton(stagger, enemyPath, startPosition));
stagger += 0.5f;
}
for (int i = 0; i < roundInfo.front()[2]; i++) {
enemies.push_back(new Necromancer(stagger, enemyPath, startPosition));
stagger += 0.5f;
}
// show the current round on screen
waves = roundInfo.front()[3];
roundInfo.pop();//pop round
}
}
//update towers, projectiles, enemies and wizards
for (int i = 0; i < explosions.size(); i++) { explosions[i]->update(dTime); }
for (int i = 0; i < towers.size(); i++) { towers[i]->update(dTime, enemies, &projectiles); }
for (int i = 0; i < projectiles.size(); i++) { projectiles[i]->update(dTime); }
for (int i = 0; i < enemies.size(); i++) { enemies[i]->update(dTime, &powerups, &projectiles, ¤cy, &baseHealth); }
for (int i = 0; i < wizards.size(); i++) { wizards[i]->update(dTime, enemies); }
for (int i = 0; i < powerups.size(); i++) { powerups[i]->update(dTime); }
if (powerup >= 4)
{
pickup = false;
}
//delete non existant towers
for (int i = towers.size() - 1; i >= 0; i--) {
if (!towers[i]->exists()) {
towers.erase(towers.begin() + i);
}
}
//delete non existant projectiles
for (int i = projectiles.size() - 1; i >= 0; i--) {
if (!projectiles[i]->exists()) {
projectiles.erase(projectiles.begin() + i);
}
}
//delete non existant enemies, add their loot to the currency
for (int i = enemies.size() - 1; i >= 0; i--) {
if (!enemies[i]->exists()) {
//if enemy died, create an explosion
if (enemies[i]->getHealth() <= 0) { explosions.push_back(new Explosion(enemies[i]->getPosition())); }
enemies.erase(enemies.begin() + i);
}
}
// delete non existant wizards
for (int i = wizards.size() - 1; i >= 0; i--){
if (!wizards[i]->exists()){
//wizard explodes when it despawns
explosions.push_back(new Explosion(wizards[i]->getPosition()));
wizards.erase(wizards.begin() + i);
}
}
// delete non existant powerups
for (int i = powerups.size() - 1; i >= 0; i--) {
if (!powerups[i]->exists()) {
powerups.erase(powerups.begin() + i);
}
}
// delete non existant explosions
for (int i = explosions.size() - 1; i >= 0; i--) {
if (!explosions[i]->exists()) {
explosions.erase(explosions.begin() + i);
}
}
//if no more base health game ends and returns to menu
if (baseHealth <= 0) { setupMenu(); }
}
}
void Game::render(void) {
// Clear background
window->clear(viewport_background_color_g);
// Update other events like input handling
glfwPollEvents();
//draw game objects
for (int i = 0; i < explosions.size(); i++) { explosions[i]->render(renderer); }
for (int i = 0; i < towers.size(); i++) { towers[i]->render(renderer); }
for (int i = 0; i < projectiles.size(); i++) { projectiles[i]->render(renderer); }
for (int i = 0; i < enemies.size(); i++) { enemies[i]->render(renderer); }
for (int i = 0; i < powerups.size(); i++) { powerups[i]->render(renderer); }
for (int i = 0; i < wizards.size(); i++) { wizards[i]->render(renderer); }
// render currency text
if (state == 1)
{
if (level == "1")
{
renderer->renderText(glm::vec3(-0.68, 0.93, 0), 0.04f, string("Currency " + to_string(currency)));
renderer->renderText(glm::vec3(0.4, 0.93, 0), 0.04f, string("Base health " + to_string(baseHealth)));
renderer->renderText(glm::vec3(-0.15, 0.8, 0), 0.05f, string("Wave " + to_string(waves)));
renderer->renderText(glm::vec3(-0.95, -0.95, 0), 0.06f, string("Pickups " + to_string(powerup)));
}
else if (level == "2")
{
renderer->renderText(glm::vec3(-0.95, 0.93, 0), 0.04f, string("Currency " + to_string(currency)));
renderer->renderText(glm::vec3(0.12, 0.93, 0), 0.04f, string("Base health " + to_string(baseHealth)));
renderer->renderText(glm::vec3(-0.95, -0.95, 0), 0.05f, string("Wave " + to_string(waves)));
renderer->renderText(glm::vec3(0.18, -0.95, 0), 0.06f, string("Pickups " + to_string(powerup)));
}
else if (level == "3")
{
renderer->renderText(glm::vec3(-0.53, 0.93, 0), 0.04f, string("Currency " + to_string(currency)));
renderer->renderText(glm::vec3(0.1, 0.93, 0), 0.04f, string("Base health " + to_string(baseHealth)));
renderer->renderText(glm::vec3(-0.15, 0.8, 0), 0.05f, string("Wave " + to_string(waves)));
renderer->renderText(glm::vec3(-0.95, -0.95, 0), 0.06f, string("Pickups " + to_string(powerup)));
}
}
//draw background image with a scale transformation
renderer->drawSprite(background, glm::scale(glm::mat4(1), glm::vec3(2, 2, 1)));
// Push buffer drawn in the background onto the display
glfwSwapBuffers(window->getWindow());
}
|
#include <stack>
#include <iostream>
using namespace std;
stack<int> st;
int main(){
int n;
cin >> n;
int p = 1;
int q = 1;
st.push(2);
while(n-- > 2){
q = st.top();
st.push(q + p);
p = q;
}
/*while(st.size() > 0){
cout << st.top() << endl;
st.pop();
}*/
cout << st.top() << endl;
return 0;
}
|
#include "roles.h"
roles::roles()
{
}
roles::roles(float width, float height)
{
}
roles::~roles()
{
}
void roles::draw(sf::RenderWindow &window)
{
for (int i = 0; i < MAX_NUMBER_OF_ITEMS; i++)
{
window.draw(menu[i]);
}
}
void roles::printRoles()
{
sf::Font font;
if (!font.loadFromFile("fff.ttf"))
{
std::cout << " i cannot find." << std::endl;
}
else
{
std::cout << "it works" << std::endl;
}
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("click.wav"))
{
std::cout << "error" << std::endl;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.setVolume(10);
sf::Text text;
sf::Text row1;
// TITLE
text.setFont(font);
text.setString("Roles");
text.setCharacterSize(50);
text.setColor(sf::Color::Red);
text.setStyle(sf::Text::Bold | sf::Text::Underlined);
text.setPosition(75, 0);
//TITLE
//ROW1
row1.setFont(font);
row1.setString("Thomas:Movement/UI\nMicah:Camera/Game Logic\nTrent:tilemap/ game logic\nBrian:Menu\n\n\n\nPress A to go back\nto main menu\n");
row1.setCharacterSize(40);
row1.setColor(sf::Color::Red);
row1.setStyle(sf::Text::Bold);
row1.setPosition(0, 150);
//ROW1
sf::RenderWindow window(sf::VideoMode(600, 600), "Roles");
roles roles(window.getSize().x, window.getSize().y);
sf::Texture texture;
sf::Sprite background;
sf::Texture text1;
sf::Sprite rules2;
if (!texture.loadFromFile("farm.jpg"))
{
std::cout << " i cannot find. " << std::endl;
}
else
{
std::cout << "It works" << std::endl;
}
background.setTexture(texture);
background.setPosition(-700, 0);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::EventType::Closed)
{
window.close();
}
switch (event.type)
{
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Return:
switch (roles.GetPressedItem())
{
case 0:
std::cout << "Press the 'A' key to return to main menu" << std::endl;
break;
case sf::Event::TextEntered:
if (event.text.unicode < 128)
{
//why the fuck does 'A'||'a' key close the window
//i guess i will use this as an intended implementation
//std::cout << (char)event.text.unicode;
printf("%49[^\n]", event.text.unicode);
if (event.text.unicode=='a')
{
sound.play();
}
}
}
break;
case sf::Event::Closed:
window.close();
break;
}
}
window.clear();
window.draw(background);
//draw
//window.draw(text);
window.draw(row1);
//draw
//rules2.setcha
roles.draw(window);
window.draw(rules2);
window.display();
}
}
}
|
#include <math.h>
class Vector3
{
public:
float x;
float y;
float z;
public:
Vector3():
x(0), y(0), z(0) {}
Vector3(const float x, const float y, const float z):
x(x), y(y), z(z) {}
void invert()
{
x = -x;
y = -y;
z = -z;
}
void operator*=(const float value)
{
x *= value;
y *= value;
z *= value;
}
Vector3 operator*(const float value) const
{
return Vector3(x*value, y*value, z*value);
}
void operator+=(const Vector3 &vector)
{
x += vector.x;
y += vector.y;
z += vector.z;
}
Vector3 operator+(const Vector3 &vector) const
{
return Vector3(x+vector.x, y+vector.y, z+vector.z);
}
void operator-=(const Vector3 &vector)
{
x -= vector.x;
y -= vector.y;
z -= vector.z;
}
Vector3 operator-(const Vector3 &vector) const
{
return Vector3(x-vector.x, y-vector.y, z-vector.z);
}
void addScaledVector(const Vector3 &vector, float scale)
{
x += vector.x * scale;
y += vector.y * scale;
z += vector.z * scale;
}
float magnitude() const
{
return sqrtf(x*x+y*y+z*z);
}
float squareMagnitude() const
{
return x*x+y*y+z*z;
}
void normalize()
{
float mag = magnitude();
if (mag > 0)
{
(*this) *= ((float)1)/mag;
}
}
Vector3 componentProduct(const Vector3 &vector) const
{
return Vector3(x*vector.x, y*vector.y, z*vector.z);
}
void componentProductUpdate(const Vector3 &vector)
{
x *= vector.x;
y *= vector.y;
z *= vector.z;
}
float dotProduct(const Vector3 &vector) const
{
return x*vector.x + y*vector.y + z*vector.z;
}
Vector3 crossProduct(const Vector3 &vector) const
{
return Vector3(y*vector.z-z*vector.y,
z*vector.x-x*vector.z,
x*vector.y-y*vector.x);
}
};
|
//
// Created by tudom on 2019-12-30.
//
#include <string>
#include <charconv>
#include <array>
#include "../include.hpp"
//&!off
#include LIBNM_INCLUDE_HEADER_N(exception/CorruptedELFObject.hpp)
//&!on
LIBNM_API
const char* libnm::corrupted_elf_object::what() const noexcept {
return "The ELF object is found to have become corrupted. Further information unavailable.";
}
template<class T>
LIBNM_LOCAL
constexpr auto g10d(T i) {
auto d = 10;
while (i % d != i) {
d *= 10;
}
return d / 10;
}
template<class T>
LIBNM_LOCAL
constexpr auto sl(T i) -> T {
if (i >= 10) {
return 1 +
sl(i % g10d(i));
}
return 1;
}
template<class T>
LIBNM_LOCAL
inline constexpr T pow(T const& x, std::size_t n) {
return n > 0 ? x * pow(x, n - 1)
: 1;
}
LIBNM_API
const char* libnm::unexplainable_elf_bit_format::what() const noexcept {
static std::string str;
str = "Byte signifying 32/64-bitness expected to be `1` or `2` but was `" + _byte + "`.";
return str.c_str();
}
LIBNM_API
libnm::unexplainable_elf_bit_format::unexplainable_elf_bit_format(uint8_t byte) {
std::array<char, sl(pow(2, sizeof(byte)))> tmpString{};
if (auto[end, ec] = std::to_chars(tmpString.data(), tmpString.data() + tmpString.size(), byte);
ec == std::errc()) {
_byte = {tmpString.data(), static_cast<std::size_t>(end - tmpString.data())};
} else {
_byte = "<?>";
}
}
LIBNM_API
const char* libnm::no_sections::what() const noexcept {
return "Elf object contains no sections.";
}
LIBNM_API
const char* libnm::inconsistent_section_header_table::what() const noexcept {
return "String Index Table's position is greater than the amount of section headers.";
}
LIBNM_API
const char* libnm::inconsistent_section_header_size::what() const noexcept {
return "Section-header's size is declared different from which the system expects.";
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_PEERFINDER_MANAGER_H_INCLUDED
#define RIPPLE_PEERFINDER_MANAGER_H_INCLUDED
namespace ripple {
namespace PeerFinder {
/** Maintains a set of IP addresses used for getting into the network. */
class Manager
: public Stoppable
, public PropertyStream::Source
{
protected:
explicit Manager (Stoppable& parent);
public:
/** Create a new Manager. */
static Manager* New (
Stoppable& parent,
SiteFiles::Manager& siteFiles,
Callback& callback,
Journal journal);
/** Destroy the object.
Any pending source fetch operations are aborted.
There may be some listener calls made before the
destructor returns.
*/
virtual ~Manager () { }
/** Set the configuration for the manager.
The new settings will be applied asynchronously.
Thread safety:
Can be called from any threads at any time.
*/
virtual void setConfig (Config const& config) = 0;
/** Add a set of strings for peers that should always be connected.
This is useful for maintaining a private cluster of peers.
If a string is not parseable as a numeric IP address it will
be passed to a DNS resolver to perform a lookup.
*/
virtual void addFixedPeers (
std::vector <std::string> const& strings) = 0;
/** Add a set of strings as fallback IPAddress sources.
@param name A label used for diagnostics.
*/
virtual void addFallbackStrings (std::string const& name,
std::vector <std::string> const& strings) = 0;
/** Add a URL as a fallback location to obtain IPAddress sources.
@param name A label used for diagnostics.
*/
virtual void addFallbackURL (std::string const& name,
std::string const& url) = 0;
/** Called when an (outgoing) connection attempt to a particular address
is about to begin.
*/
virtual void onPeerConnectAttemptBegins (IPAddress const& address) = 0;
/** Called when an (outgoing) connection attempt to a particular address
completes, whether it succeeds or fails.
*/
virtual void onPeerConnectAttemptCompletes (IPAddress const& address,
bool success) = 0;
/** Called when a new peer connection is established but before get
we exchange hello messages.
*/
virtual void onPeerConnected (IPAddress const& address,
bool inbound) = 0;
/** Called when a new peer connection is established after we exchange
hello messages.
Internally, we add the peer to our tracking table, validate that
we can connect to it, and begin advertising it to others after
we are sure that its connection is stable.
*/
virtual void onPeerHandshake (PeerID const& id,
IPAddress const& address,
bool inbound) = 0;
/** Called when an existing peer connection drops for whatever reason.
Internally, we mark the peer as no longer connected, calculate
stability metrics, and consider whether we should try to reconnect
to it or drop it from our list.
*/
virtual void onPeerDisconnected (PeerID const& id) = 0;
/** Called when mtENDPOINTS is received. */
virtual void onPeerEndpoints (PeerID const& id,
std::vector <Endpoint> const& endpoints) = 0;
/** Called when a legacy IP/port address is received (from mtPEER). */
virtual void onPeerLegacyEndpoint (IPAddress const& ep) = 0;
};
}
}
#endif
|
/*
* File: json_to_semantics_parser.hpp
* Author: azamat
*
* Created on June 10, 2015, 1:19 PM
*/
#ifndef JSON_TO_SEMANTICS_PARSER_HPP
#define JSON_TO_SEMANTICS_PARSER_HPP
#include <graphviz/gvc.h>
#include <graphviz/graph.h>
#include <Variant/Variant.h>
#include <Variant/Schema.h>
#include <Variant/SchemaLoader.h>
#include <kdl_extensions/geometric_semantics_kdl.hpp>
#include <iostream>
#include <Eigen/Core>
#include <kdl/frames_io.hpp>
#include <kdl_extensions/chain_geometric_primitives.hpp>
using libvariant::Variant;
using std::map;
using std::string;
using namespace std;
template <typename PoseT>
bool jsonToPose(Variant const& inputData, PoseT& geometricPrimitive)
{
std::string geomtype = inputData.At("@geomtype").AsString();
grs::Point refPoint, tarPoint;
grs::Body refBody, tarBody;
grs::OrientationFrame refFrame, tarFrame, coordFrame;
KDL::Frame homogenTransform;
Variant const semantics = inputData.At("semantics");
for (Variant::ConstMapIterator i=semantics.MapBegin(); i != semantics.MapEnd(); ++i)
{
if(i->first == "target")
{
std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
tarPoint = grs::Point(pointname);
std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
tarFrame = grs::OrientationFrame(framename);
std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
tarBody = grs::Body(bodyname);
}
if(i->first == "reference")
{
std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
refPoint = grs::Point(pointname);
std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
refFrame = grs::OrientationFrame(framename);
std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
refBody = grs::Body(bodyname);
}
if(i->first == "coordinateFrame")
{
std::string name = i->second.At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
coordFrame = grs::OrientationFrame(name);
}
}
Variant const coordinates = inputData.At("coordinates");
for (Variant::ConstMapIterator i=coordinates.MapBegin(); i != coordinates.MapEnd(); ++i)
{
if(i->first == "rows")
{
Eigen::Matrix<double, 4, 4 > Matrix4d;
unsigned int matrixrow(0);
for (Variant::ConstListIterator k = i->second.ListBegin(); k != i->second.ListEnd(); ++k)
{
unsigned int matrixcolumn(0);
for (Variant::ConstListIterator j = k->ListBegin(); j != k->ListEnd(); ++j)
{
Matrix4d(matrixrow,matrixcolumn) = j->AsDouble();
matrixcolumn++;
}
matrixrow++;
}
for(unsigned int i=0; i<3; i++)
{
homogenTransform.p.data[i] = Matrix4d(i,3);
}
unsigned int k(0);
for(unsigned int i=0; i<3; i++)
{
for(unsigned int j=0; j<3; j++)
{
homogenTransform.M.data[k] = Matrix4d(i,j);
k++;
}
}
}
}
geometricPrimitive = grs::Pose<KDL::Frame>(grs::PoseCoordinatesSemantics(tarPoint, tarFrame,tarBody, refPoint, refFrame,refBody,coordFrame),homogenTransform);
return true;
}
template <typename PoseT>
bool jsonToSegment(Variant const& inputData, kdle::Segment<PoseT>& kinematicsPrimitive)
{
PoseT rootFrame, tipFrame, jointFrame;
kdle::Link< PoseT > link;
std::vector< kdle::AttachmentFrame<PoseT> > frameList1;
std::cout << inputData.At("@kinematicstype").AsString() << std::endl;
Variant const jointsemantics = inputData.At("link").At("@kinematics");
for (Variant::ConstMapIterator i=jointsemantics.MapBegin(); i != jointsemantics.MapEnd(); ++i)
{
if(i->first == "rootFrame")
{
jsonToPose(i->second.At("@geometry"), rootFrame);
std::cout << "rootFrame= " << rootFrame << std::endl;
}
if(i->first == "tipFrame")
{
jsonToPose(i->second.At("@geometry"), tipFrame);
std::cout << "tipFrame= " << tipFrame << std::endl;
}
}
link = kdle::Link<PoseT> (inputData.At("link").At("@kinematics").At("name").AsString(), rootFrame, tipFrame);
Variant const attachmentframes = inputData.At("framelist");
for (Variant::ConstListIterator k=attachmentframes.ListBegin(); k != attachmentframes.ListEnd(); ++k)
{
jsonToPose (k->At("frame").At("@geometry"), jointFrame);
std::cout <<"Joint pose= " << jointFrame << std::endl;
frameList1.push_back( kdle::createAttachmentFrame(jointFrame, kdle::FrameType::JOINT));
}
kinematicsPrimitive = kdle::Segment<PoseT>(inputData.At("name").AsString(),link,frameList1);
return true;
}
template <typename PoseT>
bool jsonToJoint(Variant const& inputData, std::map<std::string, PoseT>& segmentList, kdle::Joint<PoseT>& kinematicsPrimitive)
{
std::cout << inputData.At("@kinematicstype").AsString() << std::endl;
Variant const jointsemantics = inputData.At("@jointtype");
for (Variant::ConstMapIterator i=jointsemantics.MapBegin(); i != jointsemantics.MapEnd(); ++i)
{
if(i->first == "@constraint")
{
}
if(i->first == "target")
{
std::string jointname= i->second.At("frameid").At("name").AsString();
std::string jointid= i->second.At("frameid").At("id").AsString();
std::cout << "targetframename= " << jointname << std::endl;
}
if(i->first == "reference")
{
std::string jointname= i->second.At("frameid").At("name").AsString();
std::string jointid= i->second.At("frameid").At("id").AsString();
std::cout << "referenceframename= " << jointname << std::endl;
}
}
kinematicsPrimitive = kdle::Joint<PoseT>();
return true;
}
template <typename PoseT>
bool jsonToCppModel(Variant const& inputData, kdle::KinematicChain<PoseT>& achain)
{
if(inputData.IsList())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "TOP: IT IS A LIST" << std::endl;
printf("Number of Kinematic structures: %d \n",inputData.Size());
#endif
std::vector< kdle::Segment<PoseT> > segments;
std::map<std::string, PoseT> segmentList;
for (Variant::ConstListIterator j = inputData.ListBegin(); j != inputData.ListEnd(); ++j)
{
if (j->IsMap())
{
for (Variant::ConstMapIterator i=j->MapBegin(); i != j->MapEnd(); ++i)
{
if( i->first == "@kinematics")
{
if(i->second.At("@kinematicstype").AsString() =="Segment")
{
kdle::Segment<grs::Pose<KDL::Frame> > segment;
jsonToSegment(i->second, segment);
segments.push_back(segment);
}
else if(i->second.At("@kinematicstype").AsString() =="Joint")
{
kdle::Joint<PoseT> joint;
jsonToJoint(i->second, segmentList, joint);
}
}
}
}
}
}
return true;
}
void walkJSONTree(Variant const& inputData, Agnode_t* node, Agedge_t* edgeVector, Agraph_t *g, int& nodecounter)
{
if (inputData.IsMap())
{
Agnode_t* parentnode;
parentnode = node;
nodecounter++;
#ifdef VERBOSE_CHECK_KDLE
std::cout << "PLOT: TOP: IT IS A MAP" << std::endl;
printf("Size: %d \n",inputData.Size());
std::cout << std::endl;
#endif
for (Variant::ConstMapIterator i=inputData.MapBegin(); i != inputData.MapEnd(); ++i)
{
if(i->second.IsMap())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "BOTTOM: IT IS A MAP" << std::endl;
printf("Key: %s \n", i->first.c_str());
printf("Type: %d \n", i->second.GetType());
std::cout << "Value: " << std::endl<< std::endl;
#endif
nodecounter++;
std::string tag("node");
std::ostringstream convert;
convert << nodecounter;
tag.append("-");
tag.append(convert.str());
tag.append(":");
tag.append(i->first);
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "green", "");
agsafeset(currentnode, "shape", "oval", "");
edgeVector = agedge(g, parentnode , currentnode);
walkJSONTree(i->second, currentnode, edgeVector, g, nodecounter);
}
else if(i->second.IsList())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "BOTTOM: IT IS A LIST" << std::endl;
printf("Key: %s \n", i->first.c_str());
printf("Type: %d \n", i->second.GetType());
std::cout << "Value: " << std::endl<< std::endl;
#endif
nodecounter++;
std::string tag("node");
std::ostringstream convert;
convert << nodecounter;
tag.append("-");
tag.append(convert.str());
tag.append(":");
tag.append(i->first);
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "blue", "");
agsafeset(currentnode, "shape", "oval", "");
edgeVector= agedge(g, parentnode , currentnode);
walkJSONTree(i->second, currentnode, edgeVector, g, nodecounter);
}
else if(i->second.IsString())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "BOTTOM: IT IS A STRING" << std::endl;
printf("Key: %s \n", i->first.c_str());
printf("Type: %d \n", i->second.GetType());
std::cout << "Value: " << std::endl<< std::endl;
#endif
nodecounter++;
std::string tag("node");
std::ostringstream convert;
convert << nodecounter;
tag.append("-");
tag.append(convert.str());
tag.append(":");
tag.append(i->first);
tag.append(":");
tag.append(i->second.AsString());
//fill in edge vector by iterating over joints in the tree
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "red", "");
agsafeset(currentnode, "shape", "oval", "");
edgeVector= agedge(g, parentnode , currentnode);
// agsafeset(edgeVector.back(), "label", const_cast<char*>(i->second.AsString().c_str()), "");
}
else if(i->second.IsFloat())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "BOTTOM: IT IS A FLOAT" << std::endl;
printf("Key: %s \n", i->first.c_str());
printf("Type: %d \n", i->second.GetType());
std::cout << "Value: " << std::endl<< std::endl;
#endif
nodecounter++;
std::string tag("node");
std::ostringstream convert;
convert << nodecounter;
tag.append("-");
tag.append(convert.str());
tag.append(":");
tag.append(i->first);
tag.append(":");
tag.append(i->second.AsString());
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "red", "");
agsafeset(currentnode, "shape", "box", "");
edgeVector= agedge(g, parentnode , currentnode);
}
}
}
else if(inputData.IsList())
{
nodecounter++;
Agnode_t* parentnode;
parentnode = node;
#ifdef VERBOSE_CHECK_KDLE
std::cout << "PLOT: TOP: IT IS A LIST" << std::endl;
printf("Size: %d \n",inputData.Size());
#endif
for (Variant::ConstListIterator j = inputData.ListBegin(); j != inputData.ListEnd(); ++j)
{
if (j->IsMap() || j->IsList())
{
//label the child node
nodecounter++;
std::string tag("node");
std::ostringstream convert;
convert << nodecounter;
tag.append("-");
tag.append(convert.str());
//connect the parent and the child nodes
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "green", "");
agsafeset(currentnode, "shape", "oval", "");
edgeVector= agedge(g, parentnode , currentnode);
//go to top of the function
walkJSONTree(*j, currentnode, edgeVector, g, nodecounter);
}
else if(j->IsFloat())
{
#ifdef VERBOSE_CHECK_KDLE
std::cout << "LIST BOTTOM: IT IS A FLOAT" << std::endl;
printf("Type: %d \n", j->GetType());
std::cout << "Value: " << j->AsNumber<float>() << std::endl<< std::endl;
#endif
nodecounter++;
std::string tag("node");
tag.append("-");
tag.append(static_cast<std::ostringstream&>(std::ostringstream() << nodecounter).str());
tag.append(":");
tag.append(static_cast<std::ostringstream&>(std::ostringstream() << j->AsNumber<float>()).str());
Agnode_t* currentnode = agnode( g, const_cast<char*>(tag.c_str()) );
agsafeset(currentnode, "color", "red", "");
agsafeset(currentnode, "shape", "box", "");
edgeVector= agedge(g, parentnode , currentnode);
}
//similar if clauses might be required for homogeneous arrays (i.e. the elements are of the same type)
}
}
return;
}
void drawTree(Variant const& inputData)
{
//graphviz stuff
/****************************************/
Agraph_t *g;
GVC_t *gvc;
/* set up a graphviz context */
gvc = gvContext();
/* Create a simple digraph */
g = agopen("robot-structure", AGDIGRAPH);
//create root node
Agnode_t* rootnode = agnode( g, "/" );
//create vector to hold edges
Agedge_t* edgeVector;
int counter = 0;
walkJSONTree(inputData, rootnode, edgeVector, g, counter);
/* Compute a layout using layout engine from command line args */
gvLayout(gvc, g, "dot");
/* Write the graph according to -T and -o options */
//gvRenderJobs(gvc, g);
gvRenderFilename(gvc, g, "pdf", "semantics-tree.pdf");
/* Free layout data */
gvFreeLayout(gvc, g);
/* Free graph structures */
agclose(g);
gvFreeContext(gvc);
/* close output file, free context, and return number of errors */
return;
}
template <typename PoseT>
bool createTree(std::string const& inputModelFile, std::string const& inputSchemaFile, kdle::KinematicChain< PoseT >& achain, bool const& plotOff=true)
{
Variant jsonData = libvariant::DeserializeJSONFile(inputModelFile.c_str());
libvariant::AdvSchemaLoader loader;
libvariant::SchemaResult result = libvariant::SchemaValidate(std::string("file://").append(inputSchemaFile).c_str(), jsonData, &loader);
if(!plotOff)
drawTree(jsonData);
if (!result.Error())
{
jsonToCppModel(jsonData, achain);
return true;
}
else
{
cout << result << endl;
return false;
}
}
////this function should be made a template which returns a kdle geometry (Pose, Twist)
////based on the value of @geomtype
//grs::Pose<KDL::Frame> jsonToPose(Variant const& inputData)
//{
// #ifdef VERBOSE_CHECK_KDLE
// std::string geomname = inputData.At("name").AsString();
// std::cout << geomname << std::endl;
// std::string geomid = inputData.At("id").AsString();
// std::cout << geomid << std::endl;
// std::string dsltype = inputData.At("@dsltype").AsString();
// std::cout << dsltype << std::endl;
// std::cout << geomtype << std::endl;
// #endif
// std::string geomtype = inputData.At("@geomtype").AsString();
//
// grs::Point refPoint, tarPoint;
// grs::Body refBody, tarBody;
// grs::OrientationFrame refFrame, tarFrame, coordFrame;
// KDL::Frame T;
//
// if(geomtype == "Position")
// {
// Variant const semantics = inputData.At("semantics");
// for (Variant::ConstMapIterator i=semantics.MapBegin(); i != semantics.MapEnd(); ++i)
// {
// if(i->first == "target")
// {
// //point name is concatenated from its own name and the geometry's name it belongs.
// std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarPoint = grs::Point(pointname);
// //body name is concatenated from its own name and the geometry's name it belongs.
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarBody = grs::Body(bodyname);
//
// }
// if(i->first == "reference")
// {
// std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refPoint = grs::Point(pointname);
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refBody = grs::Body(bodyname);
// }
// if(i->first == "coordinateFrame")
// {
// std::string name = i->second.At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// coordFrame = grs::OrientationFrame(name);
// }
// }
//
// grs::PositionCoordinatesSemantics positionCoordSemantics(tarPoint,tarBody,refPoint,refBody,coordFrame);
// #ifdef VERBOSE_CHECK_KDLE
// cout << " position =" << positionCoordSemantics << endl;
// #endif
//
// Variant const coordinates = inputData.At("coordinates");
// for (Variant::ConstMapIterator i=coordinates.MapBegin(); i != coordinates.MapEnd(); ++i)
// {
//
// }
// }
//
// if(geomtype == "Orientation")
// {
// Variant const semantics = inputData.At("semantics");
// for (Variant::ConstMapIterator i=semantics.MapBegin(); i != semantics.MapEnd(); ++i)
// {
// if(i->first == "target")
// {
// std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarFrame = grs::OrientationFrame(framename);
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarBody = grs::Body(bodyname);
//
// }
// if(i->first == "reference")
// {
// std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refFrame = grs::OrientationFrame(framename);
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refBody = grs::Body(bodyname);
// }
// if(i->first == "coordinateFrame")
// {
// std::string name = i->second.At("@semantic_primitive").At("name").AsString() + inputData.At("name").AsString().append(inputData.At("name").AsString());
// coordFrame = grs::OrientationFrame(name);
// }
// }
//
// grs::OrientationCoordinatesSemantics orientationCoordSemantics(tarFrame,tarBody,refFrame,refBody,coordFrame);
// #ifdef VERBOSE_CHECK_KDLE
// cout << "orientation =" << orientationCoordSemantics << endl;
// #endif
// Variant const coordinates = inputData.At("coordinates");
// for (Variant::ConstMapIterator i=coordinates.MapBegin(); i != coordinates.MapEnd(); ++i)
// {
//
// }
// }
//
// if(geomtype == "Pose")
// {
// Variant const semantics = inputData.At("semantics");
// for (Variant::ConstMapIterator i=semantics.MapBegin(); i != semantics.MapEnd(); ++i)
// {
// if(i->first == "target")
// {
// std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarPoint = grs::Point(pointname);
// std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarFrame = grs::OrientationFrame(framename);
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// tarBody = grs::Body(bodyname);
//
// }
// if(i->first == "reference")
// {
// std::string pointname = i->second.At("point").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refPoint = grs::Point(pointname);
// std::string framename = i->second.At("frame").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refFrame = grs::OrientationFrame(framename);
// std::string bodyname = i->second.At("body").At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// refBody = grs::Body(bodyname);
// }
// if(i->first == "coordinateFrame")
// {
// std::string name = i->second.At("@semantic_primitive").At("name").AsString().append(inputData.At("name").AsString());
// coordFrame = grs::OrientationFrame(name);
// }
// }
//
// Variant const coordinates = inputData.At("coordinates");
//
// for (Variant::ConstMapIterator i=coordinates.MapBegin(); i != coordinates.MapEnd(); ++i)
// {
// if(i->first == "rows")
// {
// Eigen::Matrix<double, 4, 4 > Matrix4d;
//
// unsigned int matrixrow(0);
// for (Variant::ConstListIterator k = i->second.ListBegin(); k != i->second.ListEnd(); ++k)
// {
// unsigned int matrixcolumn(0);
// for (Variant::ConstListIterator j = k->ListBegin(); j != k->ListEnd(); ++j)
// {
//
// Matrix4d(matrixrow,matrixcolumn) = j->AsDouble();
// matrixcolumn++;
// }
// matrixrow++;
// }
//
// for(unsigned int i=0; i<3; i++)
// {
// T.p.data[i] = Matrix4d(i,3);
// }
//
// unsigned int k(0);
// for(unsigned int i=0; i<3; i++)
// {
// for(unsigned int j=0; j<3; j++)
// {
// T.M.data[k] = Matrix4d(i,j);
// k++;
// }
//
// }
// }
// }
// }
//
//
// return grs::Pose<KDL::Frame>(grs::PoseCoordinatesSemantics(tarPoint, tarFrame,tarBody, refPoint, refFrame,refBody,coordFrame),T);
//}
//this function should be made a template which returns a kdle kinematics (Segment, Link)
//based on the value of @kinematicstype
//kdle::Segment<grs::Pose<KDL::Frame> >const& jsonToKinematics(Variant const& inputData)
//{
//
// grs::Pose<KDL::Frame> rootFrame, rootFrame2, tipFrame, jointFrame;
// grs::Pose<KDL::Vector, KDL::Rotation> rootFrame3;
// grs::Position<KDL::Vector> rootFrame4;
// kdle::Link< grs::Pose<KDL::Frame> > link;
// std::vector< kdle::AttachmentFrame<grs::Pose<KDL::Frame> > > frameList1;
//
// std::string kinematicstype = inputData.At("@kinematicstype").AsString();
// if(kinematicstype == "Segment")
// {
// std::cout << kinematicstype << std::endl;
//
// Variant const jointsemantics = inputData.At("link").At("@kinematics");
// for (Variant::ConstMapIterator i=jointsemantics.MapBegin(); i != jointsemantics.MapEnd(); ++i)
// {
// if(i->first == "rootFrame")
// {
// jsonToPose(i->second.At("@geometry"), rootFrame);
// std::cout << "rootFrame= " << rootFrame << std::endl;
//
// }
// if(i->first == "tipFrame")
// {
// jsonToPose(i->second.At("@geometry"), tipFrame);
// std::cout << "tipFrame= " << tipFrame << std::endl;
// }
// }
//
// link = kdle::Link< grs::Pose<KDL::Frame> > (inputData.At("link").At("@kinematics").At("name").AsString(), rootFrame, tipFrame);
//
// Variant const attachmentframes = inputData.At("framelist");
// for (Variant::ConstListIterator k=attachmentframes.ListBegin(); k != attachmentframes.ListEnd(); ++k)
// {
// jsonToPose (k->At("frame").At("@geometry"), jointFrame);
// std::cout <<"Joint pose= " << jointFrame << std::endl;
// frameList1.push_back( kdle::createAttachmentFrame(jointFrame, kdle::FrameType::JOINT));
// }
// }
// return kdle::Segment<grs::Pose<KDL::Frame> >(inputData.At("name").AsString(),link,frameList1);
//
// if(kinematicstype == "Joint")
// {
// std::cout << kinematicstype << std::endl;
// Variant const jointsemantics = inputData.At("@jointtype");
// for (Variant::ConstMapIterator i=jointsemantics.MapBegin(); i != jointsemantics.MapEnd(); ++i)
// {
// if(i->first == "@constraint")
// {
//
// }
// if(i->first == "target")
// {
// std::string jointname= i->second.At("frameid").At("name").AsString();
// std::string jointid= i->second.At("frameid").At("id").AsString();
// std::cout << "targetframename= " << jointname << std::endl;
//
// }
// if(i->first == "reference")
// {
// std::string jointname= i->second.At("frameid").At("name").AsString();
// std::string jointid= i->second.At("frameid").At("id").AsString();
// std::cout << "referenceframename= " << jointname << std::endl;
// }
// }
//
// }
//
// if(kinematicstype == "KinematicChain")
// {
// Variant const jointlist = inputData.At("jointlist");
// for (Variant::ConstListIterator i=jointlist.ListBegin(); i != jointlist.ListEnd(); ++i)
// {
// if(i->At("isRoot").AsBool() == true)
// {
// std::string jointname = i->At("@jointid").At("name").AsString();
// }
// else
// {
//
// }
// }
//
// }
//}
#endif /* JSON_TO_SEMANTICS_PARSER_HPP */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#if defined ENCODINGS_HAVE_TABLE_DRIVEN && (defined ENCODINGS_HAVE_CHINESE || defined ENCODINGS_HAVE_KOREAN)
#include "modules/encodings/tablemanager/optablemanager.h"
#include "modules/encodings/encoders/dbcs-encoder.h"
#include "modules/encodings/encoders/encoder-utility.h"
UTF16toDBCSConverter::UTF16toDBCSConverter(enum encoding outputencoding)
: m_maptable1(NULL), m_maptable2(NULL),
m_table1start(0), m_table1top(0), m_table2len(0),
m_my_encoding(outputencoding)
{
}
OP_STATUS UTF16toDBCSConverter::Construct()
{
if (OpStatus::IsError(this->OutputConverter::Construct())) return OpStatus::ERR;
long table1len;
const char *table1 = NULL, *table2 = NULL;
#ifdef ENCODINGS_HAVE_CHINESE
m_table1start = 0x4E00;
#endif
switch (m_my_encoding)
{
default:
#ifdef ENCODINGS_HAVE_CHINESE
case BIG5:
#ifdef USE_MOZTW_DATA
table1 = "big5-rev-table-1";
table2 = "big5-rev-table-2";
#endif
break;
case GBK:
table1 = "gbk-rev-table-1";
table2 = "gbk-rev-table-2";
break;
#endif
#ifdef ENCODINGS_HAVE_KOREAN
case EUCKR:
table1 = "ksc5601-rev-table-1";
table2 = "ksc5601-rev-table-2";
m_table1start = 0xAC00;
break;
#endif
}
m_maptable1 =
reinterpret_cast<const unsigned char *>(g_table_manager->Get(table1, table1len));
m_maptable2 =
reinterpret_cast<const unsigned char *>(g_table_manager->Get(table2, m_table2len));
// Determine which characters are supported by the tables
m_table1top = m_table1start + table1len / 2;
return m_maptable1 && m_maptable2 ? OpStatus::OK : OpStatus::ERR;
}
UTF16toDBCSConverter::~UTF16toDBCSConverter()
{
if (g_table_manager)
{
g_table_manager->Release(m_maptable1);
g_table_manager->Release(m_maptable2);
}
}
const char *UTF16toDBCSConverter::GetDestinationCharacterSet()
{
switch (m_my_encoding)
{
#ifdef ENCODINGS_HAVE_CHINESE
case BIG5: return "big5"; break;
case GBK: return "gbk"; break;
#endif
#ifdef ENCODINGS_HAVE_KOREAN
case EUCKR: return "euc-kr"; break;
#endif
}
OP_ASSERT(!"Unknown encoding");
return NULL;
}
int UTF16toDBCSConverter::Convert(const void* src, int len, void* dest,
int maxlen, int* read_p)
{
int read = 0;
int written = 0;
const UINT16 *input = reinterpret_cast<const UINT16 *>(src);
int utf16len = len / 2;
char *output = reinterpret_cast<char *>(dest);
while (read < utf16len && written < maxlen)
{
if (*input < 128)
{
// ASCII
*(output ++) = static_cast<char>(*input);
written ++;
}
else
{
char rowcell[2]; /* ARRAY OK 2009-01-27 johanh */
if (*input >= m_table1start && *input < m_table1top)
{
rowcell[1] = m_maptable1[(*input - m_table1start) * 2];
rowcell[0] = m_maptable1[(*input - m_table1start) * 2 + 1];
}
else
{
lookup_dbcs_table(m_maptable2, m_table2len, *input, rowcell);
}
if (rowcell[0] != 0 && rowcell[1] != 0)
{
if (written + 2 > maxlen)
{
// Don't split character
break;
}
output[0] = rowcell[0];
output[1] = rowcell[1];
written += 2;
output += 2;
}
else // Undefined code-point
{
#ifdef ENCODINGS_HAVE_ENTITY_ENCODING
if (!CannotRepresent(*input, read, &output, &written, maxlen))
break;
#else
*(output ++) = NOT_A_CHARACTER_ASCII;
written ++;
CannotRepresent(*input, read);
#endif
}
}
read ++; // Counting UTF-16 characters, not bytes
input ++;
}
*read_p = read * 2; // Counting bytes, not UTF-16 characters
m_num_converted += read;
return written;
}
#endif // ENCODINGS_HAVE_TABLE_DRIVEN && (ENCODINGS_HAVE_CHINESE || ENCODINGS_HAVE_KOREAN)
|
// Created on: 2006-05-25
// Created by: Alexander GRIGORIEV
// Copyright (c) 2006-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef VrmlData_Box_HeaderFile
#define VrmlData_Box_HeaderFile
#include <VrmlData_Geometry.hxx>
#include <gp_XYZ.hxx>
/**
* Inplementation of the Box node.
* This node is defined by Size vector, assumong that the box center is located
* in (0., 0., 0.) and that each corner is 0.5*|Size| distance from the center.
*/
class VrmlData_Box : public VrmlData_Geometry
{
public:
// ---------- PUBLIC METHODS ----------
/**
* Empty constructor
*/
inline VrmlData_Box ()
: mySize (2., 2., 2.)
{}
/**
* Constructor
*/
inline VrmlData_Box (const VrmlData_Scene& theScene,
const char * theName,
const Standard_Real sizeX = 2.,
const Standard_Real sizeY = 2.,
const Standard_Real sizeZ = 2.)
: VrmlData_Geometry (theScene, theName),
mySize (sizeX, sizeY, sizeZ)
{}
/**
* Query the Box size
*/
inline const gp_XYZ& Size () const { return mySize; }
/**
* Set the Box Size
*/
inline void SetSize (const gp_XYZ& theSize)
{ mySize = theSize; SetModified(); }
/**
* Query the primitive topology. This method returns a Null shape if there
* is an internal error during the primitive creation (zero radius, etc.)
*/
Standard_EXPORT virtual const Handle(TopoDS_TShape)&
TShape () Standard_OVERRIDE;
/**
* Create a copy of this node.
* If the parameter is null, a new copied node is created. Otherwise new node
* is not created, but rather the given one is modified.
*/
Standard_EXPORT virtual Handle(VrmlData_Node)
Clone (const Handle(VrmlData_Node)& theOther)const Standard_OVERRIDE;
/**
* Fill the Node internal data from the given input stream.
*/
Standard_EXPORT virtual VrmlData_ErrorStatus
Read (VrmlData_InBuffer& theBuffer) Standard_OVERRIDE;
/**
* Write the Node to output stream.
*/
Standard_EXPORT virtual VrmlData_ErrorStatus
Write (const char * thePrefix) const Standard_OVERRIDE;
private:
// ---------- PRIVATE FIELDS ----------
gp_XYZ mySize;
public:
// Declaration of CASCADE RTTI
DEFINE_STANDARD_RTTI_INLINE(VrmlData_Box,VrmlData_Geometry)
};
// Definition of HANDLE object using Standard_DefineHandle.hxx
DEFINE_STANDARD_HANDLE (VrmlData_Box, VrmlData_Geometry)
#endif
|
#pragma region("preprocessor")
#pragma region("imports")
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <iostream>
#include <shellapi.h>
#include <wrl.h>
#include <d3d12.h>
#include <dxgi1_6.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <vector>
#include <complex>
#include <cmath>
//#include "d3dx12.h"
#pragma endregion("imports")
#pragma region("linker directives")
#pragma comment(linker, "/DEFAULTLIB:D3d12.lib")
#pragma comment(linker, "/DEFAULTLIB:DXGI.lib")
#pragma comment(linker, "/DEFAULTLIB:D3DCompiler.lib")
#pragma endregion("linker directives")
#pragma region("preprocessor system checks")
#ifdef _DEBUG
#ifdef NDEBUG
#error debug flag conflict
#endif
#endif
#if !_HAS_CXX20
#error C++20 is required
#endif
#ifndef __has_cpp_attribute
#error critical macro __has_cpp_attribute not defined
#endif
#if !__has_include(<Windows.h>)
#error critital header Windows.h not found
#endif
#pragma endregion("preprocessor system checks")
#pragma region("macros")
#ifdef min
#pragma push_macro("min")
#undef min
#endif
#ifdef max
#pragma push_macro("max")
#undef max
#endif
#ifdef CreateWindow
#pragma push_macro("CreateWindow")
#undef CreateWindow
#endif
#ifdef _DEBUG
#define BDEBUG 1
#else
#define BDEBUG 0
#endif
#if __has_cpp_attribute(nodiscard) < 201603L
#define _NODISCARD [[nodiscard]]
#endif
#ifndef DECLSPEC_NOINLINE
#if _MSC_VER >= 1300
#define DECLSPEC_NOINLINE __declspec(noinline)
#else
#define DECLSPEC_NOINLINE
#endif
#endif
#ifndef _NORETURN
#define _NORETURN [[_Noreturn]]
#endif
#pragma endregion("macros")
#pragma region("function macros")
#ifdef _DEBUG
#define ASSERT_SUCCESS(x) assert(SUCCEEDED(x))
#else
#define ASSERT_SUCCESS(x) x
#endif
#define THROW_ON_FAIL(x) \
if (FAILED(x)){ \
std::cout << "[" << __LINE__ <<"]ERROR: " << std::hex << x << std::dec << std::endl; \
throw std::exception(); \
}
#pragma endregion("function macros")
#pragma endregion("preprocessor")
using Microsoft::WRL::ComPtr;
#pragma region("structures")
struct Vertex
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT4 color;
};
// this is the structure of our constant buffer.
struct ConstantBuffer {
DirectX::XMFLOAT4 colorMultiplier;
DirectX::XMFLOAT4 mousePos;
};
struct ConstantBuffer_Iterations {
int numIterations;
};
struct ConstantBuffer_Camera {
int camera_xpos;
int camera_ypos;
};
#pragma endregion("structures")
#pragma region("globals")
constexpr uint8_t g_NumFrames = 3;
constexpr bool showFPS = false;
constexpr wchar_t const* FENCE_NAME = L"_GlobalFence";
constexpr UINT sampleCount = 8;
constexpr UINT sampleQuality = 0;
uint32_t g_ClientWidth = 1280;
uint32_t g_ClientHeight = 720;
double temp = .2;
bool isWireframe = false;
static RECT g_WindowRect;
static ComPtr<ID3D12Device2> g_Device;
static ComPtr<ID3D12CommandQueue> g_CommandQueue;
static ComPtr<IDXGISwapChain4> g_SwapChain;
static ComPtr<ID3D12Resource> g_BackBuffers[g_NumFrames];
static ComPtr<ID3D12Resource> g_IntermediateBuffers[g_NumFrames];
static ComPtr<ID3D12GraphicsCommandList> g_CommandList;
static ComPtr<ID3D12CommandAllocator> g_CommandAllocators[g_NumFrames];
static ComPtr<ID3D12DescriptorHeap> g_RTVDescriptorHeap;
static ComPtr<ID3D12DescriptorHeap> m_DSVHeap;
static ComPtr<ID3D12Fence> g_Fence;
static ComPtr<ID3D12PipelineState> pipelineStateObject;
static ComPtr<ID3D12PipelineState> pipelineStateObject2;
static ComPtr<ID3D12PipelineState> pipelineStateObject_msaa;
static ComPtr<ID3D12RootSignature> rootSignature;
static ComPtr<ID3D12Resource> depthStencilBuffer;
static ComPtr<ID3D12DescriptorHeap> dsDescriptorHeap;
static ComPtr<ID3D12Resource> vertexBuffer;
static D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
static ComPtr<ID3D12Resource> vBufferUploadHeap;
static ComPtr<ID3D12Resource> indexBuffer;
static D3D12_INDEX_BUFFER_VIEW indexBufferView;
static ComPtr<ID3D12Resource> iBufferUploadHeap;
static D3D12_RECT scissorRect;
static D3D12_VIEWPORT viewport;
static D3D12_VIEWPORT viewport2;
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
static uint64_t g_FenceValue = 0;
static uint64_t g_FrameFenceValues[g_NumFrames] = {};
static bool g_VSync = true;
static bool g_TearingSupported = false;
static bool g_Fullscreen = false;
static uint64_t frameCounter = 0;
static double elapsedSeconds = 0.0;
static std::chrono::high_resolution_clock fpsClock;
ComPtr<ID3D12DescriptorHeap> mainDescriptorHeap[g_NumFrames]; // this heap will store the descripor to our constant buffer
ComPtr<ID3D12Resource> constantBufferUploadHeap[g_NumFrames]; // this is the memory on the gpu where our constant buffer will be placed.
ConstantBuffer cbColorMultiplierData; // this is the constant buffer data we will send to the gpu
// (which will be placed in the resource we created above)
ConstantBuffer_Iterations cbIterations;
ConstantBuffer_Camera cbCamera;
UINT8* cbColorMultiplierGPUAddress[g_NumFrames]; // this is a pointer to the memory location we get when we map our constant buffer
UINT8* cbIterationsGPUAddress[g_NumFrames]; // this is a pointer to the memory location we get when we map our constant buffer
UINT8* cbCameraGPUAddress[g_NumFrames];
#pragma endregion("globals")
LRESULT CALLBACK WndProc_preinit(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc_postinit(HWND, UINT, WPARAM, LPARAM);
int main(void)
{
bool useWarp = false;
{
int argc;
wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
for (size_t i = 0; i < argc; i++)
{
if (wcscmp(argv[i], L"-w") == 0 || wcscmp(argv[i], L"--width") == 0)
{
g_ClientWidth = wcstol(argv[++i], nullptr, 10);
}
if (wcscmp(argv[i], L"-h") == 0 || wcscmp(argv[i], L"--height") == 0)
{
g_ClientHeight = wcstol(argv[++i], nullptr, 10);
}
if (wcscmp(argv[i], L"-warp") == 0 || wcscmp(argv[i], L"--warp") == 0)
{
useWarp = true;
}
}
LocalFree(argv);
}
HINSTANCE hInstance;
GetModuleHandleExW(0, nullptr, &hInstance);
// TODO: what is this?
//SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
// Window class name. Used for registering / creating the window.
constexpr wchar_t const* windowClassName = L"DX12WindowClass";
ComPtr<IDXGIFactory4> factory4;
#ifdef _DEBUG
ComPtr<ID3D12Debug> debugInterface;
THROW_ON_FAIL(D3D12GetDebugInterface(__uuidof(ID3D12Debug), &debugInterface));
debugInterface->EnableDebugLayer();
#endif
{
BOOL allowTearing = FALSE;
constexpr UINT createFactoryFlags =
#ifdef _DEBUG
DXGI_CREATE_FACTORY_DEBUG
#else
0
#endif
;
//TODO: why create a IDXGIFactory4, then cast to IDXGIFactory5?
if (SUCCEEDED(CreateDXGIFactory2(createFactoryFlags, __uuidof(IDXGIFactory4), &factory4)))
{
ComPtr<IDXGIFactory5> factory5;
if (SUCCEEDED(factory4.As(&factory5)))
{
if (FAILED(factory5->CheckFeatureSupport(
DXGI_FEATURE_PRESENT_ALLOW_TEARING,
&allowTearing, sizeof(allowTearing))))
{
allowTearing = FALSE;
}
}
}
g_TearingSupported = (allowTearing == TRUE);
}
{
const WNDCLASSEXW windowClass = {
.cbSize = sizeof(WNDCLASSEXW),
.style = CS_HREDRAW | CS_VREDRAW,
.lpfnWndProc = &WndProc_preinit,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = hInstance,
.hIcon = LoadIconW(hInstance, IDI_APPLICATION),
.hCursor = LoadCursorW(hInstance, IDC_ARROW),
.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1),
.lpszMenuName = nullptr,
.lpszClassName = windowClassName,
.hIconSm = LoadIconW(hInstance, IDI_APPLICATION)
};
ASSERT_SUCCESS(RegisterClassExW(&windowClass));
}
HWND hWnd;
{
const int screenWidth = GetSystemMetrics(SM_CXSCREEN);
const int screenHeight = GetSystemMetrics(SM_CYSCREEN);
g_WindowRect = {
.left = 0,
.top = 0,
.right = static_cast<LONG>(g_ClientWidth),
.bottom = static_cast<LONG>(g_ClientHeight)
};
AdjustWindowRect(&g_WindowRect, WS_OVERLAPPEDWINDOW, FALSE);
const int windowWidth = g_WindowRect.right - g_WindowRect.left;
const int windowHeight = g_WindowRect.bottom - g_WindowRect.top;
// Center the window within the screen. Clamp to 0, 0 for the top-left corner.
hWnd = CreateWindowExW(
NULL,
windowClassName,
L"DirectX 12",
WS_OVERLAPPEDWINDOW,
std::max(0, (screenWidth - windowWidth) / 2),
std::max(0, (screenHeight - windowHeight) / 2),
windowWidth,
windowHeight,
NULL,
NULL,
hInstance,
nullptr
);
assert(hWnd && "Failed to create window");
ShowWindow(hWnd, SW_SHOW);
}
{
//TODO: no effect?
THROW_ON_FAIL(factory4->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER));
ComPtr<IDXGIFactory6> factory6;
THROW_ON_FAIL(factory4.As(&factory6));
ComPtr<IDXGIAdapter4> dxgiAdapter4;
if (useWarp)
{
THROW_ON_FAIL(factory4->EnumWarpAdapter(__uuidof(IDXGIAdapter4), &dxgiAdapter4));
THROW_ON_FAIL(D3D12CreateDevice(dxgiAdapter4.Get(), D3D_FEATURE_LEVEL_12_1, __uuidof(ID3D12Device2), &g_Device));
}
else
{
factory6->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, __uuidof(IDXGIAdapter4), &dxgiAdapter4);
THROW_ON_FAIL(D3D12CreateDevice(dxgiAdapter4.Get(), D3D_FEATURE_LEVEL_11_1, __uuidof(ID3D12Device2), &g_Device));
}
D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msLevels;
msLevels.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Replace with your render target format.
msLevels.SampleCount = sampleCount; // Replace with your sample count.
msLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
g_Device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msLevels, sizeof(msLevels));
std::cout << "quality levels " << msLevels.NumQualityLevels << std::endl;
// Enable debug messages in debug mode.
#ifdef _DEBUG
ComPtr<ID3D12InfoQueue> pInfoQueue;
if (SUCCEEDED(g_Device.As(&pInfoQueue)))
{
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
// Suppress whole categories of messages
//D3D12_MESSAGE_CATEGORY Categories[] = {};
// Suppress messages based on their severity level
D3D12_MESSAGE_SEVERITY Severities[] =
{
D3D12_MESSAGE_SEVERITY_INFO
};
// Suppress individual messages by their ID
D3D12_MESSAGE_ID DenyIds[] = {
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, // I'm really not sure how to avoid this message.
D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging.
D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, // This warning occurs when using capture frame while graphics debugging.
};
D3D12_INFO_QUEUE_FILTER NewFilter = {
.DenyList = {
.NumSeverities = _countof(Severities),
.pSeverityList = Severities,
.NumIDs = _countof(DenyIds),
.pIDList = DenyIds
}
};
THROW_ON_FAIL(pInfoQueue->PushStorageFilter(&NewFilter));
}
#endif
}
{
constexpr D3D12_COMMAND_QUEUE_DESC desc = {
.Type = D3D12_COMMAND_LIST_TYPE_DIRECT,
.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH,
.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE,
.NodeMask = 0
};
THROW_ON_FAIL(g_Device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), (&g_CommandQueue)));
}
{
const DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {
.Width = g_ClientWidth,
.Height = g_ClientHeight,
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.Stereo = FALSE,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = g_NumFrames,
.Scaling = DXGI_SCALING_STRETCH,
.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD,
.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED,
.Flags = (g_TearingSupported) ? (DWORD)DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : (DWORD)0
};
ComPtr<IDXGISwapChain1> swapChain1;//intermediate
THROW_ON_FAIL(factory4->CreateSwapChainForHwnd(
g_CommandQueue.Get(),
hWnd,
&swapChainDesc,
nullptr,
nullptr,
&swapChain1));
THROW_ON_FAIL(swapChain1.As(&g_SwapChain));
}
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {
.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
.NumDescriptors = g_NumFrames * 2 //Swap chain render targets + intermediate render targets
};
THROW_ON_FAIL(g_Device->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), &g_RTVDescriptorHeap));
}
{
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart();
ComPtr<ID3D12Resource> backBuffer;
const INT64 descriptorHandleIncrementSize = (INT64)g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
for (int i = 0; i < g_NumFrames; i++)
{
//TODO: create intermediate render target with higher sample count
D3D12_HEAP_PROPERTIES heapProperties =
{
.Type = D3D12_HEAP_TYPE_DEFAULT,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
.Alignment = 0,
.Width = g_ClientWidth,
.Height = g_ClientHeight,
.DepthOrArraySize = 1,
.MipLevels = 1,
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.SampleDesc = {
.Count = sampleCount,
.Quality = sampleQuality
},
.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET
};
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES,
&resourceDesc,
D3D12_RESOURCE_STATE_RENDER_TARGET,
nullptr,
__uuidof(ID3D12Resource),
&g_IntermediateBuffers[i]
);
g_IntermediateBuffers[i]->SetName(L"Intermediate Render Target");
g_Device->CreateRenderTargetView(g_IntermediateBuffers[i].Get(), nullptr, rtvHandle);
rtvHandle.ptr = (SIZE_T)((INT64)rtvHandle.ptr + descriptorHandleIncrementSize);
}
for (int i = 0; i < g_NumFrames; i++)
{
THROW_ON_FAIL(g_SwapChain->GetBuffer(i, __uuidof(ID3D12Resource), &backBuffer));
g_Device->CreateRenderTargetView(backBuffer.Get(), nullptr, rtvHandle);
g_BackBuffers[i] = backBuffer;
rtvHandle.ptr = (SIZE_T)((INT64)rtvHandle.ptr + descriptorHandleIncrementSize);
THROW_ON_FAIL(g_Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), &g_CommandAllocators[i]));
}
}
{
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {
.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
.NumDescriptors = 1,
.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE
};
THROW_ON_FAIL(g_Device->CreateDescriptorHeap(&dsvHeapDesc, __uuidof(ID3D12DescriptorHeap), &m_DSVHeap));
}
THROW_ON_FAIL(g_Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_CommandAllocators[g_SwapChain->GetCurrentBackBufferIndex()].Get(), nullptr, __uuidof(ID3D12GraphicsCommandList1), &g_CommandList));
THROW_ON_FAIL(g_Device->CreateFence(g_FenceValue, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &g_Fence));
HANDLE g_FenceEvent = CreateEventW(nullptr, FALSE, FALSE, FENCE_NAME);
assert(g_FenceEvent && "Failed to create fence event.");
{
D3D12_DESCRIPTOR_RANGE descriptorTableRanges[1] =
{ // only one range right now
{
.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV, // this is a range of constant buffer views (descriptors)
.NumDescriptors = 2, // we only have one constant buffer, so the range is only 1
.BaseShaderRegister = 0, // start index of the shader registers in the range
.RegisterSpace = 0, // space 0. can usually be zero
.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND // this appends the range to the end of the root signature descriptor tables
}
};
D3D12_ROOT_DESCRIPTOR_TABLE descriptorTable = {
.NumDescriptorRanges = _countof(descriptorTableRanges), // we only have one range
.pDescriptorRanges = &descriptorTableRanges[0] // the pointer to the beginning of our ranges array
};
// create a root parameter and fill it out
D3D12_ROOT_PARAMETER rootParameters[1] = { { // only one parameter right now
.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, // this is a descriptor table
.DescriptorTable = descriptorTable, // this is our descriptor table for this root parameter
.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL // our vertex shader will be the only shader accessing this parameter for now
}
};
D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc =
{
.NumParameters = _countof(rootParameters),
.pParameters = rootParameters,
.NumStaticSamplers = 0,
.pStaticSamplers = nullptr,
.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS // we can deny shader stages here for better performance
};
for (int i = 0; i < g_NumFrames; i++)
{
D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {
.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
.NumDescriptors = 1,
.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
};
THROW_ON_FAIL(g_Device->CreateDescriptorHeap(&heapDesc, __uuidof(ID3D12DescriptorHeap), &mainDescriptorHeap[i]));
}
// create the constant buffer resource heap
// We will update the constant buffer one or more times per frame, so we will use only an upload heap
// unlike previously we used an upload heap to upload the vertex and index data, and then copied over
// to a default heap. If you plan to use a resource for more than a couple frames, it is usually more
// efficient to copy to a default heap where it stays on the gpu. In this case, our constant buffer
// will be modified and uploaded at least once per frame, so we only use an upload heap
// create a resource heap, descriptor heap, and pointer to cbv for each frame
//todo: fix
for (int i = 0; i < g_NumFrames; i++)
{
D3D12_HEAP_PROPERTIES heapProperties =
{
.Type = D3D12_HEAP_TYPE_UPLOAD,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,
.Alignment = 0,
.Width = 1024 * 64,
.Height = 1,
.DepthOrArraySize = 1,
.MipLevels = 1,
.Format = DXGI_FORMAT_UNKNOWN,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
.Flags = D3D12_RESOURCE_FLAG_NONE,
};
g_Device->CreateCommittedResource(
&heapProperties, // this heap will be used to upload the constant buffer data
D3D12_HEAP_FLAG_NONE, // no flags
&resourceDesc, // size of the resource heap. Must be a multiple of 64KB for single-textures and constant buffers
D3D12_RESOURCE_STATE_GENERIC_READ, // will be data that is read from so we keep it in the generic read state
nullptr, // we do not have use an optimized clear value for constant buffers
__uuidof(ID3D12Resource), &constantBufferUploadHeap[i]);
constantBufferUploadHeap[i]->SetName(L"Constant Buffer Upload Resource Heap");
D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
cbvDesc.BufferLocation = constantBufferUploadHeap[i]->GetGPUVirtualAddress();
cbvDesc.SizeInBytes = (sizeof(ConstantBuffer) + sizeof(ConstantBuffer_Iterations) + sizeof(ConstantBuffer_Camera) + 255) & ~255; // CB size is required to be 256-byte aligned.
g_Device->CreateConstantBufferView(&cbvDesc, mainDescriptorHeap[i].Get()->GetCPUDescriptorHandleForHeapStart());
//memset(&cbColorMultiplierData, 0, sizeof(cbColorMultiplierData));
cbColorMultiplierData.colorMultiplier.x = 1;
cbColorMultiplierData.colorMultiplier.y = 1;
cbColorMultiplierData.colorMultiplier.z = 1;
cbIterations.numIterations = 1;
cbCamera.camera_xpos = 0;
cbCamera.camera_ypos = 0;
D3D12_RANGE readRange{ .Begin = 0, .End = 0 }; // We do not intend to read from this resource on the CPU. (End is less than or equal to begin)
constantBufferUploadHeap[i]->Map(0, &readRange, reinterpret_cast<void**>(&cbColorMultiplierGPUAddress[i]));
memcpy(cbColorMultiplierGPUAddress[i], &cbColorMultiplierData, sizeof(cbColorMultiplierData));
memcpy(cbColorMultiplierGPUAddress[i] + sizeof(cbColorMultiplierData), &cbIterations, sizeof(cbIterations));
memcpy(cbColorMultiplierGPUAddress[i] + sizeof(cbColorMultiplierData) + sizeof(cbIterations), &cbCamera, sizeof(cbCamera));
}
ComPtr<ID3DBlob> signature;
THROW_ON_FAIL(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, nullptr));
THROW_ON_FAIL(g_Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), __uuidof(ID3D12RootSignature), &rootSignature));
// create vertex and pixel shaders
// when debugging, we can compile the shader files at runtime.
// but for release versions, we can compile the hlsl shaders
// with fxc.exe to create .cso files, which contain the shader
// bytecode. We can load the .cso files at runtime to get the
// shader bytecode, which of course is faster than compiling
// them at runtime
// compile vertex shader
ComPtr<ID3DBlob> vertexShader; // d3d blob for holding vertex shader bytecode
ComPtr<ID3DBlob> errorBuff; // a buffer holding the error data if any
THROW_ON_FAIL(D3DCompileFromFile(L"VertexShader.hlsl",
nullptr,
nullptr,
"main",
"vs_5_0",
D3DCOMPILE_OPTIMIZATION_LEVEL3,
0,
&vertexShader,
&errorBuff));
// fill out a shader bytecode structure, which is basically just a pointer
// to the shader bytecode and the size of the shader bytecode
// compile pixel shader
ComPtr<ID3DBlob> pixelShader;
THROW_ON_FAIL(D3DCompileFromFile(L"PixelShader.hlsl",
nullptr,
nullptr,
"main",
"ps_5_0",
//D3DCOMPILE_DEBUG |
D3DCOMPILE_OPTIMIZATION_LEVEL3,
0,
&pixelShader,
&errorBuff));
D3D12_INPUT_ELEMENT_DESC inputLayout[] =
{
{
.SemanticName = "POSITION",
.SemanticIndex = 0,
.Format = DXGI_FORMAT_R32G32B32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 0,
.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
.InstanceDataStepRate = 0
},
{
.SemanticName = "COLOR",
.SemanticIndex = 0,
.Format = DXGI_FORMAT_R32G32B32_FLOAT,
.InputSlot = 0,
.AlignedByteOffset = 12,
.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
.InstanceDataStepRate = 0
}
};
psoDesc = {
.pRootSignature = rootSignature.Get(),
.VS = {
.pShaderBytecode = vertexShader->GetBufferPointer(),
.BytecodeLength = vertexShader->GetBufferSize()
},
.PS = {
.pShaderBytecode = pixelShader->GetBufferPointer(),
.BytecodeLength = pixelShader->GetBufferSize()
},
.BlendState = {
.AlphaToCoverageEnable = FALSE,
.IndependentBlendEnable = FALSE,
.RenderTarget = {
{
.BlendEnable = FALSE,
.LogicOpEnable = FALSE,
.SrcBlend = D3D12_BLEND_ONE,
.DestBlend = D3D12_BLEND_ZERO,
.BlendOp = D3D12_BLEND_OP_ADD,
.SrcBlendAlpha = D3D12_BLEND_ONE,
.DestBlendAlpha = D3D12_BLEND_ZERO,
.BlendOpAlpha = D3D12_BLEND_OP_ADD,
.LogicOp = D3D12_LOGIC_OP_NOOP,
.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL
}//TODO: X8
}
},
.SampleMask = 0xFFFFFFFF,
.RasterizerState = {
.FillMode = D3D12_FILL_MODE_WIREFRAME,
.CullMode = D3D12_CULL_MODE_NONE,
.FrontCounterClockwise = FALSE,
.DepthBias = D3D12_DEFAULT_DEPTH_BIAS,
.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP,
.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS,
.DepthClipEnable = TRUE,
.MultisampleEnable = FALSE,
.AntialiasedLineEnable = FALSE,
.ForcedSampleCount = 0,
.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF
},
.DepthStencilState = {
.DepthEnable = TRUE,
.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL,
.DepthFunc = D3D12_COMPARISON_FUNC_LESS,
.StencilEnable = FALSE,
.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK,
.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK,
.FrontFace = {
.StencilFailOp = D3D12_STENCIL_OP_KEEP,
.StencilDepthFailOp = D3D12_STENCIL_OP_KEEP,
.StencilPassOp = D3D12_STENCIL_OP_KEEP,
.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS
},
.BackFace = {
.StencilFailOp = D3D12_STENCIL_OP_KEEP,
.StencilDepthFailOp = D3D12_STENCIL_OP_KEEP,
.StencilPassOp = D3D12_STENCIL_OP_KEEP,
.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS
}
},
.InputLayout = {
.pInputElementDescs = inputLayout,
.NumElements = _countof(inputLayout),
},
.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
.NumRenderTargets = 1,
.RTVFormats = {DXGI_FORMAT_R8G8B8A8_UNORM},
.DSVFormat = DXGI_FORMAT_D32_FLOAT,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
};
THROW_ON_FAIL(g_Device->CreateGraphicsPipelineState(&psoDesc, __uuidof(ID3D12PipelineState), &pipelineStateObject));
psoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
THROW_ON_FAIL(g_Device->CreateGraphicsPipelineState(&psoDesc, __uuidof(ID3D12PipelineState), &pipelineStateObject2));
psoDesc.DepthStencilState = {};
psoDesc.SampleDesc.Count = sampleCount;
THROW_ON_FAIL(g_Device->CreateGraphicsPipelineState(&psoDesc, __uuidof(ID3D12PipelineState), &pipelineStateObject_msaa));
}
{
// create a depth stencil descriptor heap so we can get a pointer to the depth stencil buffer
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {
.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
.NumDescriptors = 1,
.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE
};
THROW_ON_FAIL(g_Device->CreateDescriptorHeap(&dsvHeapDesc, __uuidof(ID3D12DescriptorHeap), &dsDescriptorHeap));
}
{
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {
.Format = DXGI_FORMAT_D32_FLOAT,
.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D,
.Flags = D3D12_DSV_FLAG_NONE
};
D3D12_CLEAR_VALUE depthOptimizedClearValue = {
.Format = DXGI_FORMAT_D32_FLOAT,
.DepthStencil = {
.Depth = 1.0f,
.Stencil = 0
}
};
D3D12_HEAP_PROPERTIES heapProperties = {
.Type = D3D12_HEAP_TYPE_DEFAULT,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
.Alignment = 0,
.Width = g_ClientWidth,
.Height = g_ClientHeight,
.DepthOrArraySize = 1,
.MipLevels = 0,
.Format = DXGI_FORMAT_D32_FLOAT,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
};
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&depthOptimizedClearValue,
__uuidof(ID3D12Resource),
&depthStencilBuffer
);
dsDescriptorHeap->SetName(L"Depth/Stencil Resource Heap");
g_Device->CreateDepthStencilView(depthStencilBuffer.Get(), &depthStencilDesc, dsDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
}
Vertex vList[] = {
{.pos = {-1.f, -1.f, 0.9f}, .color = {1.0f, 1.0f, 1.0f, 1.0f}},
{.pos = {1.0f, -1.f, 0.6f}, .color = {0.0f, 0.0f, 1.0f, 1.0f}},
{.pos = {-1.f, 1.0f, 0.6f}, .color = {1.0f, 0.0f, 0.0f, 1.0f}},
{.pos = {1.0f, 1.0f, 0.9f}, .color = {0.0f, 1.0f, 0.0f, 1.0f}},
{.pos = {-1.0f, -1.f, 0.1f}, .color = {1.0f, 1.0f, 1.0f, 1.0f}},
{.pos = {1.0f, -1.f, 0.9f}, .color = {0.0f, 0.0f, 1.0f, 1.0f}},
{.pos = {-1.0f, 1.f, 0.9f}, .color = {1.0f, 0.0f, 0.0f, 1.0f}},
{.pos = {1.0f, 1.f, 0.1f}, .color = {0.0f, 1.0f, 0.0f, 1.0f}},
};
constexpr UINT64 vBufferSize = sizeof(vList);
{
D3D12_HEAP_PROPERTIES heapProperties =
{
.Type = D3D12_HEAP_TYPE_DEFAULT,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,
.Alignment = 0,
.Width = vBufferSize,
.Height = 1,
.DepthOrArraySize = 1,
.MipLevels = 1,
.Format = DXGI_FORMAT_UNKNOWN,
.SampleDesc =
{
.Count = 1,
.Quality = 0
},
.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
.Flags = D3D12_RESOURCE_FLAG_NONE
};
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
__uuidof(ID3D12Resource),
&vertexBuffer
);
vertexBuffer->SetName(L"Triangle 1 Vertex Buffer");
heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;//reuse properties struct for upload heap
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
__uuidof(ID3D12Resource),
&vBufferUploadHeap
);
vBufferUploadHeap->SetName(L"Triangle 1 Vertex Buffer Upload Heap");
//todo: fix use of reinterpret_cast
D3D12_SUBRESOURCE_DATA vertexData = {
.pData = reinterpret_cast<BYTE*>(vList),
.RowPitch = sizeof(vList),
.SlicePitch = sizeof(vList)
};
//TODO: this section is still filled with mystery, needs to be further investigated
{
struct TempData {
D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts;
UINT64 RowSizesInBytes;
UINT NumRows;
};
//TODO: use custom allocator from paged pool
TempData* myData = (TempData*)HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS, sizeof(TempData));
D3D12_RESOURCE_DESC Desc = vertexBuffer->GetDesc();
UINT64 RequiredSize;
g_Device->GetCopyableFootprints(&Desc, 0, 1, 0, &myData->layouts, &myData->NumRows, &myData->RowSizesInBytes, &RequiredSize);
std::cout << "myData->layouts.Offset " << myData->layouts.Offset << std::endl;
std::cout << "myData->layouts.Footprint.Format " << myData->layouts.Footprint.Format << std::endl;
std::cout << "myData->layouts.Footprint.Width " << myData->layouts.Footprint.Width << std::endl;
std::cout << "myData->layouts.Footprint.Height " << myData->layouts.Footprint.Height << std::endl;
std::cout << "myData->layouts.Footprint.Depth " << myData->layouts.Footprint.Depth << std::endl;
std::cout << "myData->layouts.Footprint.RowPitch " << myData->layouts.Footprint.RowPitch << std::endl;
std::cout << "myData->NumRows " << myData->NumRows << std::endl;
std::cout << "myData->RowSizesInBytes " << myData->RowSizesInBytes << std::endl;
std::cout << "RequiredSize " << RequiredSize << std::endl;
BYTE* pData = nullptr;
THROW_ON_FAIL(vBufferUploadHeap->Map(0, nullptr, reinterpret_cast<void**>(&pData)));
for (int x = 0; x < myData->layouts.Footprint.Depth; x++)
{
BYTE* pDestSlice = static_cast<BYTE*>(pData + myData->layouts.Offset) + ((SIZE_T)myData->layouts.Footprint.RowPitch * (SIZE_T)myData->NumRows) * x;
const BYTE* pSrcSlice = static_cast<const BYTE*>(vertexData.pData) + ((SIZE_T)myData->layouts.Footprint.RowPitch * (SIZE_T)myData->NumRows) * (LONG_PTR)x;//TODO: what is the LONG_PTR cast for?
for (int y = 0; y < myData->NumRows; y++)
{
memcpy(
pDestSlice + myData->layouts.Footprint.RowPitch * (UINT64)y,
pSrcSlice + vertexData.RowPitch * (LONG_PTR)y, //again, the mysterious cast
static_cast<SIZE_T>(myData->RowSizesInBytes));
}
}
vBufferUploadHeap->Unmap(0, nullptr);
g_CommandList->CopyBufferRegion(vertexBuffer.Get(), 0, vBufferUploadHeap.Get(), myData->layouts.Offset, myData->layouts.Footprint.Width);
HeapFree(GetProcessHeap(), 0, myData);
/*
* unknown functions used:
* g_Device->GetCopyableFootprints
* vBufferUploadHeap->Map
* vBufferUploadHeap->Unmap
*/
}
D3D12_RESOURCE_BARRIER barrier = {
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition{
.pResource = vertexBuffer.Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST,
.StateAfter = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,
},
};
g_CommandList->ResourceBarrier(1, &barrier);
}
DWORD iList[] = {
0, 1, 2, // first triangle
1, 2, 3, // second triangle
4, 5, 6,
5, 6, 7,
};
constexpr UINT64 iBufferSize = sizeof(iList);
{
D3D12_HEAP_PROPERTIES heapProperties =
{
.Type = D3D12_HEAP_TYPE_DEFAULT,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,
.Alignment = 0,
.Width = iBufferSize,
.Height = 1,
.DepthOrArraySize = 1,
.MipLevels = 1,
.Format = DXGI_FORMAT_UNKNOWN,
.SampleDesc =
{
.Count = 1,
.Quality = 0
},
.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
.Flags = D3D12_RESOURCE_FLAG_NONE
};
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
__uuidof(ID3D12Resource),
&indexBuffer
);
vertexBuffer->SetName(L"Triangle 1 Index Buffer");
heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;//reuse properties struct for upload heap
g_Device->CreateCommittedResource(
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
__uuidof(ID3D12Resource),
&iBufferUploadHeap
);
iBufferUploadHeap->SetName(L"Triangle 1 Index Buffer Upload Heap");
//TODO: fix use of reinterpret_cast
D3D12_SUBRESOURCE_DATA IndexData = {
.pData = reinterpret_cast<BYTE*>(iList),
.RowPitch = sizeof(iList),
.SlicePitch = sizeof(iList)
};
//TODO: this section is still filled with mystery, needs to be further investigated
{
struct TempData {
D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts;
UINT64 RowSizesInBytes;
UINT NumRows;
};
//TODO: use custom allocator from paged pool
TempData* myData = (TempData*)HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS, sizeof(TempData));
D3D12_RESOURCE_DESC Desc = indexBuffer->GetDesc();
UINT64 RequiredSize;
g_Device->GetCopyableFootprints(&Desc, 0, 1, 0, &myData->layouts, &myData->NumRows, &myData->RowSizesInBytes, &RequiredSize);
std::cout << "myData->layouts.Offset " << myData->layouts.Offset << std::endl;
std::cout << "myData->layouts.Footprint.Format " << myData->layouts.Footprint.Format << std::endl;
std::cout << "myData->layouts.Footprint.Width " << myData->layouts.Footprint.Width << std::endl;
std::cout << "myData->layouts.Footprint.Height " << myData->layouts.Footprint.Height << std::endl;
std::cout << "myData->layouts.Footprint.Depth " << myData->layouts.Footprint.Depth << std::endl;
std::cout << "myData->layouts.Footprint.RowPitch " << myData->layouts.Footprint.RowPitch << std::endl;
std::cout << "myData->NumRows " << myData->NumRows << std::endl;
std::cout << "myData->RowSizesInBytes " << myData->RowSizesInBytes << std::endl;
std::cout << "RequiredSize " << RequiredSize << std::endl;
BYTE* pData = nullptr;
THROW_ON_FAIL(iBufferUploadHeap->Map(0, nullptr, reinterpret_cast<void**>(&pData)));
for (int x = 0; x < myData->layouts.Footprint.Depth; x++)
{
BYTE* pDestSlice = static_cast<BYTE*>(pData + myData->layouts.Offset) + ((SIZE_T)myData->layouts.Footprint.RowPitch * (SIZE_T)myData->NumRows) * x;
const BYTE* pSrcSlice = static_cast<const BYTE*>(IndexData.pData) + ((SIZE_T)myData->layouts.Footprint.RowPitch * (SIZE_T)myData->NumRows) * (LONG_PTR)x;//TODO: what is the LONG_PTR cast for?
for (int y = 0; y < myData->NumRows; y++)
{
memcpy(
pDestSlice + myData->layouts.Footprint.RowPitch * (UINT64)y,
pSrcSlice + IndexData.RowPitch * (LONG_PTR)y, //again, the mysterious cast
static_cast<SIZE_T>(myData->RowSizesInBytes));
}
}
iBufferUploadHeap->Unmap(0, nullptr);
g_CommandList->CopyBufferRegion(indexBuffer.Get(), 0, iBufferUploadHeap.Get(), myData->layouts.Offset, myData->layouts.Footprint.Width);
HeapFree(GetProcessHeap(), 0, myData);
/*
* unknown functions used:
* g_Device->GetCopyableFootprints
* vBufferUploadHeap->Map
* vBufferUploadHeap->Unmap
*/
}
D3D12_RESOURCE_BARRIER barrier = {
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition{
.pResource = indexBuffer.Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST,
.StateAfter = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,
}
};
g_CommandList->ResourceBarrier(1, &barrier);
g_CommandList->Close();
ID3D12CommandList* ppCommandLists[] = { g_CommandList.Get() };
g_CommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
g_FenceValue++;
g_CommandQueue->Signal(g_Fence.Get(), g_FenceValue);
}
vertexBufferView = {
.BufferLocation = vertexBuffer->GetGPUVirtualAddress(),
.SizeInBytes = (UINT)vBufferSize,
.StrideInBytes = sizeof(Vertex)
};
indexBufferView = {
.BufferLocation = indexBuffer->GetGPUVirtualAddress(),
.SizeInBytes = (UINT)iBufferSize,
.Format = DXGI_FORMAT_R32_UINT
};
viewport = {
.TopLeftX = 0,
.TopLeftY = 0,
.Width = (FLOAT)g_ClientWidth,
.Height = (FLOAT)g_ClientHeight,
.MinDepth = 0.0F,
.MaxDepth = 1.0F
};
//viewport2 = {
// .TopLeftX = (FLOAT)g_ClientWidth / 2 - 100,
// .TopLeftY = (FLOAT)g_ClientHeight / 2 - 100,
// .Width = (FLOAT)200,
// .Height = (FLOAT)200,
// .MinDepth = 0.0F,
// .MaxDepth = 1.0F
//};
scissorRect = {
.left = 0,
.top = 0,
.right = (LONG)g_ClientWidth,
.bottom = (LONG)g_ClientHeight
};
SetWindowLongPtrW(hWnd, GWLP_WNDPROC, (LONG_PTR)&WndProc_postinit);
MSG msg{};
while (msg.message != WM_QUIT)
{
{
memcpy(cbColorMultiplierGPUAddress[g_SwapChain->GetCurrentBackBufferIndex()], &cbColorMultiplierData, sizeof(cbColorMultiplierData));
}
if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
g_FenceValue++;
THROW_ON_FAIL(g_CommandQueue->Signal(g_Fence.Get(), g_FenceValue));
if (g_Fence->GetCompletedValue() < g_FenceValue)
{
THROW_ON_FAIL(g_Fence->SetEventOnCompletion(g_FenceValue, g_FenceEvent));
WaitForSingleObject(g_FenceEvent, INFINITE);
}
CloseHandle(g_FenceEvent);
return 0;
}
static auto t0 = fpsClock.now();
auto deltaTime = t0 - t0;
LRESULT CALLBACK WndProc_preinit(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_DESTROY)
PostQuitMessage(0);
return DefWindowProcW(hwnd, message, wParam, lParam);
}
LRESULT CALLBACK WndProc_postinit(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
{
//keep track of fps
//TODO: this is probably broken
frameCounter++;
auto t1 = fpsClock.now();
deltaTime = t1 - t0;
t0 = t1;
if constexpr (showFPS)
{
elapsedSeconds += deltaTime.count() * 1e-9;
if (elapsedSeconds > .25)
{
system("cls");
std::cout << "FPS: " << (frameCounter / elapsedSeconds); //temporary, until I can write this to the screen
frameCounter = 0;
elapsedSeconds = 0.0;
}
}
}
{
const UINT currentBackBufferIndex = g_SwapChain->GetCurrentBackBufferIndex();
g_CommandAllocators[currentBackBufferIndex]->Reset();
//record and submit graphics commands
{
D3D12_RESOURCE_BARRIER barrier1
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_BackBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_PRESENT,
.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET
}
};
temp += 0.3 * deltaTime.count() * 1e-9;
const FLOAT clearColor1[] = { sin(temp), cos(temp), .5f, 1.0f };
const FLOAT clearColor2[] = { cos(temp), .5f, sin(temp), 1.0f };
D3D12_RESOURCE_BARRIER barrier2
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_BackBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET,
.StateAfter = D3D12_RESOURCE_STATE_PRESENT
}
};
D3D12_RESOURCE_BARRIER resolutionBarrier1
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_IntermediateBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET,
.StateAfter = D3D12_RESOURCE_STATE_RESOLVE_SOURCE
}
};
D3D12_RESOURCE_BARRIER resolutionBarrier2
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_IntermediateBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET
}
};
D3D12_RESOURCE_BARRIER resolutionDestBarrier1
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_BackBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET,
.StateAfter = D3D12_RESOURCE_STATE_RESOLVE_DEST
}
};
D3D12_RESOURCE_BARRIER resolutionDestBarrier2
{
.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
.Transition =
{
.pResource = g_BackBuffers[currentBackBufferIndex].Get(),
.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
.StateBefore = D3D12_RESOURCE_STATE_RESOLVE_DEST,
.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET
}
};
D3D12_CPU_DESCRIPTOR_HANDLE rtv1 = {
.ptr = (SIZE_T)(
(INT64)g_RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr +
(INT64)currentBackBufferIndex *
(INT64)g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)
)
};
D3D12_CPU_DESCRIPTOR_HANDLE rtv2 = {
.ptr = (SIZE_T)(
(INT64)g_RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr +
(INT64)g_NumFrames *
(INT64)g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) +
(INT64)currentBackBufferIndex *
(INT64)g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)
)
};
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = {
.ptr = (SIZE_T)dsDescriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr
};
//at long last, the actual graphics commands:
//g_CommandList->SetPipelineState(isWireframe ? pipelineStateObject2.Get() : pipelineStateObject.Get());
g_CommandList->Reset(g_CommandAllocators[currentBackBufferIndex].Get(), isWireframe ? pipelineStateObject.Get() : pipelineStateObject2.Get());
//cbIterations.numIterations = 1;
{
POINT p;
GetCursorPos(&p);
cbColorMultiplierData.mousePos.x = (p.x / (g_ClientWidth / 2.)) - 2;
cbColorMultiplierData.mousePos.y = (p.y / (g_ClientHeight / 2.)) - 2;
}
// copy our ConstantBuffer instance to the mapped constant buffer resource
memcpy(cbColorMultiplierGPUAddress[currentBackBufferIndex], &cbColorMultiplierData, sizeof(cbColorMultiplierData));
memcpy(cbColorMultiplierGPUAddress[currentBackBufferIndex] + sizeof(cbColorMultiplierData), &cbIterations, sizeof(cbIterations));
g_CommandList->SetPipelineState(pipelineStateObject_msaa.Get());
g_CommandList->ResourceBarrier(1, &barrier1);
g_CommandList->SetGraphicsRootSignature(rootSignature.Get());
g_CommandList->OMSetRenderTargets(1, &rtv1, FALSE, NULL);
g_CommandList->ClearRenderTargetView(rtv1, clearColor1, 0, nullptr);
//g_CommandList->ClearDepthStencilView(dsDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// set constant buffer descriptor heap
ID3D12DescriptorHeap* descriptorHeaps[] = { mainDescriptorHeap[currentBackBufferIndex].Get() };
g_CommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
// set the root descriptor table 0 to the constant buffer descriptor heap
g_CommandList->SetGraphicsRootDescriptorTable(0, mainDescriptorHeap[currentBackBufferIndex]->GetGPUDescriptorHandleForHeapStart());
g_CommandList->RSSetViewports(1, &viewport);
g_CommandList->RSSetScissorRects(1, &scissorRect);
g_CommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
g_CommandList->IASetVertexBuffers(0, 1, &vertexBufferView);
g_CommandList->IASetIndexBuffer(&indexBufferView);
g_CommandList->DrawIndexedInstanced(6, 1, 6, 0, 0);
g_CommandList->SetPipelineState(pipelineStateObject2.Get());
g_CommandList->OMSetRenderTargets(1, &rtv2, FALSE, NULL);
//TODO: convert intermediate buffer state to D3D12_RESOURCE_STATE_RESOLVE_SOURCE
g_CommandList->ResourceBarrier(1, &resolutionBarrier1);
g_CommandList->ResourceBarrier(1, &resolutionDestBarrier1);
g_CommandList->ResolveSubresource(g_BackBuffers[currentBackBufferIndex].Get(), 0, g_IntermediateBuffers[currentBackBufferIndex].Get(), 0, DXGI_FORMAT_R8G8B8A8_UNORM);
//g_CommandList->DrawIndexedInstanced(6, 1, 0, 0, 0);
g_CommandList->ResourceBarrier(1, &resolutionBarrier2);
g_CommandList->ResourceBarrier(1, &resolutionDestBarrier2);
g_CommandList->ResourceBarrier(1, &barrier2);
THROW_ON_FAIL(g_CommandList->Close());
ID3D12CommandList* const commandLists[] = { g_CommandList.Get() };
g_CommandQueue->ExecuteCommandLists(_countof(commandLists), commandLists);//submit the command list for execution
}
g_FenceValue++;
THROW_ON_FAIL(g_CommandQueue->Signal(g_Fence.Get(), g_FenceValue));
g_FrameFenceValues[currentBackBufferIndex] = g_FenceValue;
{
const UINT syncInterval = g_VSync ? 1 : 0;
const UINT presentFlags = g_TearingSupported && !g_VSync ? DXGI_PRESENT_ALLOW_TEARING : 0;
g_SwapChain->Present(syncInterval, presentFlags);
}
if (g_Fence->GetCompletedValue() < g_FrameFenceValues[currentBackBufferIndex])
{
HANDLE fenceEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, FENCE_NAME);
if (fenceEvent == NULL)
throw std::exception();
THROW_ON_FAIL(g_Fence->SetEventOnCompletion(g_FrameFenceValues[currentBackBufferIndex], fenceEvent));
WaitForSingleObject(fenceEvent, INFINITE);
}
}
break;
case WM_SYSKEYDOWN:
case WM_KEYDOWN:
{
bool alt = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
switch (wParam)
{
case 'Q'://zoom out
cbColorMultiplierData.colorMultiplier.z *= 1.1f;
break;
case 'E'://zoom in
cbColorMultiplierData.colorMultiplier.z *= .9;
break;
case 'Z':
isWireframe = !isWireframe;
break;
case 'A':
cbColorMultiplierData.colorMultiplier.x -= .1 * cbColorMultiplierData.colorMultiplier.z;
break;
case 'D':
cbColorMultiplierData.colorMultiplier.x += .1 * cbColorMultiplierData.colorMultiplier.z;
break;
case 'S':
cbColorMultiplierData.colorMultiplier.y -= .1 * cbColorMultiplierData.colorMultiplier.z;
break;
case 'W':
cbColorMultiplierData.colorMultiplier.y += .1 * cbColorMultiplierData.colorMultiplier.z;
break;
case 'I':
break;
case 'K':
break;
case 'J':
break;
case 'L':
break;
case 'V':
g_VSync = !g_VSync;
break;
case 'T':
cbIterations.numIterations += 1;
break;
case 'Y':
cbIterations.numIterations -= 1;
break;
case 'G':
cbIterations.numIterations += 100;
break;
case 'H':
cbIterations.numIterations -= 100;
break;
case VK_ESCAPE:
PostQuitMessage(0);
break;
case VK_RETURN:
case VK_F11:
if (alt)
{
if (g_Fullscreen = !g_Fullscreen)
{
// Store the current window dimensions so they can be restored
// when switching out of fullscreen state.
GetWindowRect(hwnd, &g_WindowRect);
// Set the window style to a borderless window so the client area fills
// the entire screen.
UINT windowStyle = WS_OVERLAPPEDWINDOW & ~(WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
SetWindowLongW(hwnd, GWL_STYLE, windowStyle);
// Query the name of the nearest display device for the window.
// This is required to set the fullscreen dimensions of the window
// when using a multi-monitor setup.
HMONITOR hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
MONITORINFOEXW monitorInfo{ {.cbSize = sizeof(MONITORINFOEXW)} };
GetMonitorInfoW(hMonitor, &monitorInfo);
SetWindowPos(hwnd, HWND_TOPMOST,
monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.top,
monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left,
monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(hwnd, SW_MAXIMIZE);
}
else
{
// Restore all the window decorators.
SetWindowLongW(hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
SetWindowPos(hwnd, HWND_NOTOPMOST,
g_WindowRect.left,
g_WindowRect.top,
g_WindowRect.right - g_WindowRect.left,
g_WindowRect.bottom - g_WindowRect.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(hwnd, SW_NORMAL);
}
}
break;
}
}
break;
// The default window procedure will play a system notification sound
// when pressing the Alt+Enter keyboard combination if this message is
// not handled.
case WM_SYSCHAR:
break;
case WM_SIZE:
{
RECT clientRect = {};
GetClientRect(hwnd, &clientRect);
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
if (g_ClientWidth != width || g_ClientHeight != height)
{
// Don't allow 0 size swap chain back buffers.
g_ClientWidth = std::max(1ui32, (uint32_t)width);
g_ClientHeight = std::max(1ui32, (uint32_t)height);
// Flush the GPU queue to make sure the swap chain's back buffers
// are not being referenced by an in-flight command list.
THROW_ON_FAIL(g_CommandQueue->Signal(g_Fence.Get(), ++g_FenceValue));
if (g_Fence->GetCompletedValue() < g_FenceValue)
{
HANDLE fenceEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, FENCE_NAME);
THROW_ON_FAIL(g_Fence->SetEventOnCompletion(g_FenceValue, fenceEvent));
WaitForSingleObject(fenceEvent, static_cast<DWORD>(std::chrono::milliseconds::max().count()));
}
for (int i = 0; i < g_NumFrames; i++)
{
// Any references to the back buffers must be released
// before the swap chain can be resized.
g_BackBuffers[i].Reset();
g_FrameFenceValues[i] = g_FrameFenceValues[g_SwapChain->GetCurrentBackBufferIndex()];
}
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
THROW_ON_FAIL(g_SwapChain->GetDesc(&swapChainDesc));
THROW_ON_FAIL(g_SwapChain->ResizeBuffers(g_NumFrames, g_ClientWidth, g_ClientHeight, swapChainDesc.BufferDesc.Format, swapChainDesc.Flags));
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle(g_RTVDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
const INT64 incrementSize = (INT64)g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
for (int i = 0; i < g_NumFrames; i++)
{
ComPtr<ID3D12Resource> backBuffer;
THROW_ON_FAIL(g_SwapChain->GetBuffer(i, __uuidof(ID3D12Resource), &backBuffer));
g_Device->CreateRenderTargetView(backBuffer.Get(), nullptr, rtvHandle);
g_BackBuffers[i] = backBuffer;
rtvHandle.ptr = (SIZE_T)((INT64)rtvHandle.ptr + incrementSize);
}
}
viewport = {
.TopLeftX = 0,
.TopLeftY = 0,
.Width = (FLOAT)g_ClientWidth,
.Height = (FLOAT)g_ClientHeight,
.MinDepth = 0.0F,
.MaxDepth = 1.0F
};
//std::cout << g_ClientWidth << ", " << g_ClientHeight << std::endl;
//viewport2 = {
// .TopLeftX = 0,
// .TopLeftY = 0,
// .Width = (FLOAT)g_ClientWidth,
// .Height = (FLOAT)g_ClientHeight,
// .MinDepth = 0.0F,
// .MaxDepth = 1.0F
//};
scissorRect = {
.left = 0,
.top = 0,
.right = (LONG)g_ClientWidth,
.bottom = (LONG)g_ClientHeight
};
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProcW(hwnd, message, wParam, lParam);
}
return 0;
}
#pragma pop_macro("max")
#pragma pop_macro("min")
#pragma pop_macro("CreateWindow")
|
// Copyright (C) 2016 John Biddiscombe
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/coroutines/detail/get_stack_pointer.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <algorithm>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <vector>
using info = std::tuple<std::size_t, std::ptrdiff_t, std::ptrdiff_t>;
using info_stack = std::stack<info>;
void stack_remaining(const char* txt, info_stack& stack)
{
#if defined(PIKA_HAVE_THREADS_GET_STACK_POINTER)
std::size_t stack_ptr = pika::threads::coroutines::detail::get_stack_ptr();
#else
std::size_t stack_ptr = 0x00000000;
#endif
std::ptrdiff_t stacksize = pika::this_thread::get_stack_size();
std::ptrdiff_t remaining_stack = pika::this_thread::get_available_stack_space();
//
std::cout << txt << " stacksize : 0x" << std::hex << stacksize << "\n";
std::cout << txt << " stack pointer : 0x" << std::hex << stack_ptr << "\n";
std::cout << txt << " stack remaining : 0x" << std::hex << remaining_stack << "\n\n";
stack.push(std::make_tuple(stack_ptr, stacksize, remaining_stack));
}
//
void stack_waste(int N, info_stack& stack)
{
// declare 1 MB of stack vars
char bytes[1 << 10] = {0};
// prevent the compiler optimizing it away
std::fill_n(&bytes[0], 32, 0);
std::stringstream dummy;
dummy << bytes[45] << std::ends;
//
std::stringstream temp;
temp << "stack_waste " << N;
stack_remaining(temp.str().c_str(), stack);
//
if (N > 0) stack_waste(N - 1, stack);
}
//
int pika_main()
{
info_stack my_stack_info;
// just for curiosity
stack_remaining("pika_main", my_stack_info);
// test stack vars
stack_waste(20, my_stack_info);
std::ptrdiff_t current_stack = 0;
while (!my_stack_info.empty())
{
info i = my_stack_info.top();
std::ptrdiff_t stack_now = std::get<2>(i);
std::cout << "stack remaining 0x" << std::hex << stack_now << "\n";
#if defined(PIKA_HAVE_THREADS_GET_STACK_POINTER)
# if defined(PIKA_DEBUG)
PIKA_TEST_LT(current_stack, stack_now);
# else
// In release builds some stack variables may get optimized away.
PIKA_TEST_LTE(current_stack, stack_now);
# endif
#endif
current_stack = stack_now;
my_stack_info.pop();
}
return pika::finalize();
}
int main(int argc, char* argv[])
{
//
// add command line option which controls the random number generator seed
using namespace pika::program_options;
options_description desc_commandline("Usage: " PIKA_APPLICATION_STRING " [options]");
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = desc_commandline;
init_args.cfg = cfg;
PIKA_TEST_EQ_MSG(
pika::init(pika_main, argc, argv, init_args), 0, "pika main exited with non-zero status");
return 0;
}
|
//
// SORT.hpp
// ADT
//
// Created by Jalor on 2020/9/7.
// Copyright © 2020 Jalor. All rights reserved.
//
#ifndef SORT_hpp
#define SORT_hpp
#include <iostream>
using namespace std;
template <typename DataType>
class Sort {
public:
Sort();//建立空的链表
void InsertSort(DataType data[],int n);
private:
int n;
};
//template <typename DataType>
//void Sort::InsertSort(DataType data[],int n){
// DataType i,j,tmp;
// for (i = 1; i < n; i ++) {
// if(data[i]<data[i-1]){
// tmp = data[i];
// data[i] = data[i-1];
// for (j = i-1; j>=0 && data[j]> tmp; j--) {
// data[j+1] = data[j];
// }
// data[j+1] = tmp;
// }
// }
//}
#endif /* SORT_hpp */
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x, y;
cin>>x>>y;
switch (x)
{
case 1:
cout<<"Total: R$ "<<fixed<<setprecision(2)<<y*4.00<<"\n";
break;
case 2:
cout<<"Total: R$ "<<fixed<<setprecision(2)<<y*4.50<<"\n";
break;
case 3:
cout<<"Total: R$ "<<fixed<<setprecision(2)<<y*5.00<<"\n";
break;
case 4:
cout<<"Total: R$ "<<fixed<<setprecision(2)<<y*2.00<<"\n";
break;
case 5:
cout<<"Total: R$ "<<fixed<<setprecision(2)<<y*1.5<<"\n";
break;
default:
break;
}
return 0;
}
|
#include <iostream>
void solution(int n, int m)
{
int* arr = new int[n + 1];
for (int i = 1; i <= n; i++)
arr[i] = i;
int* joseph = new int[n];
int counter = m;
int curPoint = m;
int vi = 0;
while (true)
{
if (counter == m)
{
joseph[vi++] = arr[curPoint];
arr[curPoint] = 0;
counter = 0;
}
if (vi == n)
break;
curPoint++;
if (curPoint > n)
curPoint = 1;
if (arr[curPoint] != 0)
counter++;
}
printf("<");
for (int i = 0; i < n; i++)
{
printf("%d", joseph[i]);
if (i < n - 1)
printf(", ");
}
printf(">");
delete[] arr;
delete[] joseph;
arr = nullptr;
joseph = nullptr;
}
int main(void)
{
int n, m;
scanf("%d %d", &n, &m);
solution(n, m);
return 0;
}
|
#include <iostream>
#include "vector.h"
#include "vector.cpp"
int main()
{
vector_<double> v{ 1, 2, 3 };
vector_<int> vec {1, 0, 1};
vec.push_back(2);
std::cout << vec[3] << std::endl;
return 0;
}
|
//Write a method to generate the nth Fibonacci number
#include <iostream>
using namespace std;
//the iterative version should we way faster....
int fibonacci(int n){
if(n==0||n==1) return 1;
if(n>1){
return fibonacci(n-1) + fibonacci(n-2);
}else{
return -1;
}
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// My friend has a "bigital" clock. It displays 12-hour times
// in the
// form hh:mm:ss, using 6 columns of 1 watt light bulbs.
// Each column displays its value in binary, where a light is
// off
// to indicate a 0 and is on to indicate a 1. The clock can
// display all
// 12-hour times, from 01:00:00 to 12:59:59.
//
// For example, 03:22:59 requires 8 lights to be on and looks
// like this:
//
// 0 0 0 0 0 1
// 0 0 0 0 1 0
// 0 1 1 1 0 0
// 0 1 0 0 1 1
//
// Given tStart and tEnd, return the total number of kilowatt
// hours used by the clock in displaying all the times from
// tStart to tEnd,
// inclusive. The start and end time are less than 12 hours
// apart.
//
//
// DEFINITION
// Class:Bigital
// Method:energy
// Parameters:string, string
// Returns:double
// Method signature:double energy(string tStart, string tEnd)
//
//
// NOTES
// -A kilowatt hour is the energy used when using 1000 watts
// for an hour.
// -A return value with either an absolute or relative error
// of less than 1.0E-9 is considered correct.
//
//
// CONSTRAINTS
// -tStart and tEnd will each contain exactly 8 characters.
// -tStart and tEnd will each be in the form hh:mm:ss, where
// hh is between 01 and 12, inclusive, mm is between 00 and
// 59, inclusive, and ss is between 00 and 59, inclusive.
//
//
// EXAMPLES
//
// 0)
// "12:00:00"
// "12:00:00"
//
// Returns: 5.555555555555555E-7
//
//
//
//
// Two bulbs are on for just one second. This require 2
// watt seconds
// which (60 seconds per minute, 60 minutes per hour, 1000
// watts per
// kilowatt) is .000000555555555 kilowatt hours of energy.
//
//
//
// 1)
// "12:59:59"
// "01:00:00"
//
// Returns: 3.0555555555555556E-6
//
//
//
// Here the clock is running for 2 seconds, with lots of
// lights on for
// the first second and only 1 on for the second second.
//
//
// 2)
// "12:01:00"
// "12:00:00"
//
// Returns: 0.08392277777777778
//
//
//
// This is almost the full 12 hours.
//
//
// END CUT HERE
#line 94 "Bigital.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
template<class T>
T fromString(string inp)
{
stringstream s(inp);
T a;
s>>a;
return a;
}
VS toks(string inp,string delim)
{
char *ch = strdup(inp.c_str());
char *ptr = strtok(ch,delim.c_str());
VS ret;
while (ptr != NULL){
ret.push_back(ptr);
ptr = strtok(NULL,delim.c_str());
}
free(ch);
return ret;
}
template<class T>
vector<T> toksT(string inp,string delim)
{
VS temp = toks(inp,delim);
vector<T> ret;
for(int i=0;i<temp.size();i++)
ret.push_back(fromString<T>(temp[i]));
return ret;
}
bool lesss(VI a, VI b) {
if (a[0]==b[0]) {
if (a[1]==b[1]) {
return a[2]<b[2];
}
return a[1]<b[1];
}
return a[0]<b[0];
}
long long coun(int t) {
long long ret = 0;
while (t) {
if (t&1) ret++;
t >>= 1;
}
return ret;
}
long long cou(int t) {
return coun(t/10) + coun(t%10);
}
long long mycount(int h, int m, int s) {
h %= 12;
if (!h) h = 12;
return cou(h) + cou(m) + cou(s);
}
class Bigital
{
public:
double energy(string tStart, string tEnd)
{
VI ts = toksT<int>(tStart, ":");
VI te = toksT<int>(tEnd, ":");
if (lesss(te, ts)) {
te[0] += 12;
}
int hh = ts[0];
int mm = ts[1];
int ss = ts[2];
long long ret = 0;
for(; hh < te[0]; ++hh) {
for(; mm < 60; ++mm) {
for(; ss < 60; ++ss) {
ret += mycount(hh, mm, ss);
}
ss = 0;
}
mm = 0;
}
for(;mm < te[1]; ++mm) {
for(; ss < 60; ++ss) {
ret += mycount(hh,mm,ss);
}
ss=0;
}
for(; ss<= te[2]; ++ss) {
ret += mycount(hh,mm,ss);
}
return ret/1000.0/60.0/60.0;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "12:00:00"; string Arg1 = "12:00:00"; double Arg2 = 5.555555555555555E-7; verify_case(0, Arg2, energy(Arg0, Arg1)); }
void test_case_1() { string Arg0 = "12:59:59"; string Arg1 = "01:00:00"; double Arg2 = 3.0555555555555556E-6; verify_case(1, Arg2, energy(Arg0, Arg1)); }
void test_case_2() { string Arg0 = "12:01:00"; string Arg1 = "12:00:00"; double Arg2 = 0.08392277777777778; verify_case(2, Arg2, energy(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Bigital ___test;
___test.run_test(-1);
}
// END CUT HERE
|
/*
** EPITECH PROJECT, 2019
** tek3
** File description:
** UdpSocket
*/
#ifndef UDPSOCKET_HPP_
#define UDPSOCKET_HPP_
#include <iostream>
#include <QNetworkInterface>
#include <QString>
#include <QObject>
#include <QUdpSocket>
#define MAX_DATAGRAM_SIZE (3832)
namespace babel {
class Core;
class CallThread;
namespace network {
class UdpSocket : public QObject {
Q_OBJECT
public:
explicit UdpSocket(const int &port, const std::string &target_ip, const int &target_port, babel::Core *parent = 0);
explicit UdpSocket(const int &port, babel::CallThread *parent = 0);
~UdpSocket();
signals:
public slots:
void readyRead();
public:
void write(const char *buffer, const unsigned int &size) const;
void read(char *buffer);
void setTarget(std::string target, const int &port);
private:
QUdpSocket *_socket;
QHostAddress _address;
qint16 _port;
};
}
}
#endif /* !UdpSocket_HPP_ */
|
#pragma once
// GcTasksPane
class GcTasksPane : public CMFCTasksPane
{
DECLARE_DYNAMIC(GcTasksPane)
public:
GcTasksPane();
virtual ~GcTasksPane();
void SetVisibleCaptionBar(bool bShow);
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};
|
#pragma once
#include "Game.h"
#include "SDL.h"
#include "SDL_image.h"
class TextureLoader
{
public:
static SDL_Texture* loadTexutre(const char* fileName, SDL_Renderer* renderer);
static void draw(SDL_Renderer* renderer, SDL_Texture* texture, SDL_Rect* src, SDL_Rect* dst);
};
|
#pragma once
#include "uiWindow.h"
#include "Maho.h"
#include "ofxFastFboReader.h"
#include "grotes.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key){};
void mouseMoved(int x, int y ){};
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button){};
void mouseReleased(int x, int y, int button){};
void windowResized(int w, int h){};
void dragEvent(ofDragInfo dragInfo){};
void gotMessage(ofMessage msg){};
void mappingDraw();
//xtion
ofPixels pix;
ofTexture tex;
ofxCvColorImage cImg;
ofxCvGrayscaleImage gImg;
ofxCvContourFinder cfinder;
ofxFastFboReader fboReader;
//fenster
uiWindow ui;
int counter;
//openCv
//grotesQ
//magic
Maho maho;
//another
Kirakira kirakira;
//mask
ofShader maskShader;
ofFbo mainMaskFbo;
ofImage mainMaskImg;
//videos
ofRectangle himawariAlpha;
ofRectangle kajiAlpha;
ofColor videoMaskColor;
int fadeCurrentTimeMilis;
int ct;
//testMonitor
ofFbo testMonitor;
//custom
void fadingWhite();
//onetime
};
|
#ifndef MOTION
#define MOTION
class Motion
{
private:
bool Forward = false;
bool Backward = false;
bool Left = false;
bool Right = false;
public:
void setMotionForward(bool val) { Forward = val; };
bool getMotionForward() { return Forward; };
void setMotionBackward(bool val) { Backward = val; };
bool getMotionBackward() { return Backward; };
void setMotionLeft(bool val) { Left = val; };
bool getMotionLeft() { return Left; };
void setMotionRight(bool val) { Right = val; };
bool getMotionRight() { return Right; };
};
#endif
|
const int RGB_RED_PIN = 3;
const int RGB_GREEN_PIN = 5;
const int RGB_BLUE_PIN = 6;
const int DELAY_MS = 20;
const int MAX_COLOR_VALUE = 255;
enum RGB{
RED,
GREEN,
BLUE,
NUM_COLORS
};
int _rgbLedValues[] = {255, 0, 0}; // Red, Green, Blue
enum RGB _curFadingUpColor = GREEN;
enum RGB _curFadingDownColor = RED;
const int FADE_STEP = 5;
void setup() {
pinMode(RGB_RED_PIN, OUTPUT);
pinMode(RGB_GREEN_PIN, OUTPUT);
pinMode(RGB_BLUE_PIN, OUTPUT);
Serial.begin(9600);
Serial.println("Red, Green, Blue");
setColor(_rgbLedValues[RED], _rgbLedValues[GREEN], _rgbLedValues[BLUE]);
delay(DELAY_MS);
}
void loop() {
_rgbLedValues[_curFadingUpColor] += FADE_STEP;
_rgbLedValues[_curFadingDownColor] -= FADE_STEP;
if(_rgbLedValues[_curFadingUpColor] > MAX_COLOR_VALUE){
_rgbLedValues[_curFadingUpColor] = MAX_COLOR_VALUE;
_curFadingUpColor = (RGB)(((int)_curFadingUpColor + 1) % NUM_COLORS);
}
if(_rgbLedValues[_curFadingDownColor] < 0){
_rgbLedValues[_curFadingDownColor] = 0;
_curFadingDownColor = (RGB)(((int)_curFadingDownColor + 1) % NUM_COLORS);
}
setColor(_rgbLedValues[RED], _rgbLedValues[GREEN], _rgbLedValues[BLUE]);
delay(DELAY_MS);
}
void setColor(int red, int green, int blue)
{
Serial.print(red);
Serial.print(", ");
Serial.print(green);
Serial.print(", ");
Serial.println(blue);
analogWrite(RGB_RED_PIN, red);
analogWrite(RGB_GREEN_PIN, green);
analogWrite(RGB_BLUE_PIN, blue);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.