text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef JAYARITHDECODER_H #define JAYARITHDECODER_H #include "modules/jaypeg/jaypeg.h" #ifdef JAYPEG_JP2_SUPPORT #include "modules/jaypeg/src/jayentropydecoder.h" #define JAYPEG_ENTROPY_NUM_CONTEXT 19 class JayArithDecoder : public JayEntropyDecoder { public: JayArithDecoder(); ~JayArithDecoder(); int init(class JayStream *stream); int readStream(class JayStream *stream, unsigned short &sample); void reset(); private: static const unsigned short context_qe[]; static const unsigned char context_nmps[]; static const unsigned char context_nlps[]; static const unsigned char context_switch[]; static const unsigned char context_initial_index[]; unsigned short curmps[JAYPEG_ENTROPY_NUM_CONTEXT]; unsigned char curindex[JAYPEG_ENTROPY_NUM_CONTEXT]; unsigned int lps_exchange(unsigned int cx, unsigned int d); unsigned int mps_exchange(unsigned int cx, unsigned int d); int renormd(class JayStream *stream); int bytein(class JayStream *stream); int decode(class JayStream *stream, unsigned int cx, unsigned int &d); unsigned int ct; unsigned int creg; unsigned short areg; }; #endif // JAYPEG_JP2_SUPPORT #endif
#pragma once class GameCursor; // THIS IS CAMERA. class GameCamera; class AIEditNodeHp; class AIEditNodeInequ; class AIEditNodeButton; class AIEditNodeTechnique; class AIEditNodeAbnormalState; class AIEditNodeProcess; class AIEditNodeOrder; class AIEditNode : public GameObject { public: ~AIEditNode(); bool Start() override final; void Update() override final; void Inequ(); void Technique(); void Abnormal(); void FontsConfirmation(); void SetChoice1(bool a) { Choice1 = a; } bool GetChoice1() { return Choice1; } enum Node { enHp = 200, enMp, enAb, enTechnique, enNull = 0, }; int GetNode() { return m_Node; } bool Getnodefont() { return Nodefont; } private: Node m_Node = enNull; int button = 4; //ボタンの数 bool Choice1 = false; //何かを選択するとtrueになる bool Nodefont = false; //AIEditNodeSelectFontsで使うよ。 bool contact1 = false; bool contact2 = false; //技を選択するとtrueになる。 CVector2 SetShadowPos = { 5.f,-5.f }; CVector3 cursorpos = CVector3::Zero(); CVector3 m_position = CVector3::Zero(); CVector3 m_pointposition = CVector3::Zero(); std::vector<FontRender*> m_fonts; std::vector<FontRender*> m_font; std::vector<AIEditNodeButton*> m_nodebuttons; SpriteRender* m_spriteRender = nullptr; SpriteRender* sr = nullptr; GameCursor * m_gamecursor = nullptr; AIEditNodeHp * m_aieditnodehp = nullptr; AIEditNodeInequ* m_aieditnodeinequ = nullptr; AIEditNodeButton * m_aieditnodebutton = nullptr; AIEditNodeTechnique* m_aieditnodetechnique = nullptr; AIEditNodeAbnormalState* m_aieditnodeabnorimalstate = nullptr; AIEditNodeProcess* m_aieditnodeprocess = nullptr; AIEditNodeOrder* m_aieditnodeoreder = nullptr; };
#include<cstdio> #include<malloc.h> #include<stdlib.h> #include<conio.h> struct node { int a; struct node *next; }; void removeLoop(struct node *loop_node, struct node *head); void insert(struct node **ptr,int data) { struct node *newnode; if(*ptr==NULL) { //a list must undergo size allocation *ptr=(struct node *)malloc(sizeof(struct node)); (*ptr)->a=data; (*ptr)->next=NULL; } else { struct node *temp; temp=*ptr; while(temp->next!=NULL) { temp=temp->next; } //new node size allocation newnode=(struct node *)malloc(sizeof(struct node)); newnode->a=data; newnode->next=NULL; temp->next=newnode; } } int display(struct node *ptr) { int count=0; while(ptr!=NULL) { printf("%d\t",ptr->a); ptr=ptr->next; count++; } return count; } void del(struct node **ptr,int data) { struct node *t,*temp; if((*ptr)->a==data) { //delete first node t=(*ptr); (*ptr)=(*ptr)->next; return; } temp=*ptr; while(temp->next!=NULL) { if(temp->next->a==data) break; temp=temp->next; } if(temp->next==NULL) { //reached last node printf("Element not found..\n"); return; } t=temp->next; temp->next=temp->next->next; delete(t); } void pointtomid(struct node **ptr,int mid) { int count=0; struct node *temp = *ptr; struct node *t = *ptr; while(count<mid) { temp = temp->next; count++; } //printf("%d",temp->a); while(t->next!=NULL) { t = t->next; } t->next=temp; printf("Mid = %d\n",t->next->a); } int detectAndRemoveLoop(struct node *list) { struct node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { removeLoop(slow_p, list); return 1; } } return 0; } void removeLoop(struct node *loop_node, struct node *head) { struct node *ptr1; struct node *ptr2; ptr1 = head; while(1) { ptr2 = loop_node; while(ptr2->next != loop_node && ptr2->next != ptr1) { ptr2 = ptr2->next; } if(ptr2->next == ptr1) break; else ptr1 = ptr1->next; } ptr2->next = NULL; } int main() { struct node *p,*lastnode=NULL; p=NULL;int cnt=0; int c,mid; int num; for(int i=1;i<8;i++) { insert(&p,i); } c = display(p); // get count while displaying mid = c/2; pointtomid(&p,mid); // last node points to middle detectAndRemoveLoop(p); //Remove loops so yu can proceed further del(&p,7); del(&p,5); c = display(p); // // delete a num // get the count again mid = c/2; pointtomid(&p,mid); // c = display(p); this will give looped data //detectAndRemoveLoop(p); Use this to remove loops // c = display(p); and print the data in list getch(); }
#ifndef UICURVE_H #define UICURVE_H #include "uielement.h" #include "uirectangle.h" #include <iostream> class QPainterPath; class UiRectangle; class UiCurve : public UiElement { Q_OBJECT public: UiCurve(QWidget *parent); void change(UiRectangle* p1, UiRectangle* p2, UiRectangle* p3, UiRectangle* p4); void change(); UiRectangle** Points(){return points;} void setFocusPoint(int i, QPointF point) { setFocus(i); setFocusPoint(point); } void setFocusPoint(QPointF point) { points[focusPoint - 1]->change(QPointF(point.x() - 3, point.y() - 3), QPointF(point.x() + 3, point.y() + 3)); } UiRectangle* pFocusPoint(int i) { if(i > 0 && i < 5) { return points[i - 1]; } else { std::cout<<"invalid parameter in UiCurve::pFocusPoint(int i)"<<std::endl; return NULL; } } void setFocus(int i) { focusPoint = i; } int getFocus() { return focusPoint; } UiRectangle* pFocusPoint() { return pFocusPoint(focusPoint); } protected: void paintEvent(QPaintEvent *); private: std::vector<QPointF>pointArray; //std::vector<UiRectangle> points; UiRectangle** points; bool activeColour; int focusPoint; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 2010-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" #ifdef MEDIA_JIL_PLAYER_SUPPORT #include "modules/display/vis_dev.h" #include "modules/doc/frm_doc.h" #include "modules/doc/html_doc.h" #include "modules/dom/domenvironment.h" #include "modules/dom/domutils.h" #include "modules/layout/box/box.h" #include "modules/media/jilmediaelement.h" #include "modules/media/src/controls/mediacontrols.h" #include "modules/style/css_media.h" JILMediaElement::JILMediaElement(HTML_Element* el) : Media(el), m_listener(NULL), m_frm_doc(NULL), m_player(NULL), m_controls(NULL), m_video_width(0), m_video_height(0), m_paused(TRUE), m_suspended(FALSE), m_has_controls(FALSE), m_muted(FALSE), m_playback_ended(TRUE), m_volume(1.0) { m_progress_update_timer.SetTimerListener(this); } JILMediaElement::~JILMediaElement() { Cleanup(); } void JILMediaElement::Cleanup() { m_progress_update_timer.Stop(); if (m_frm_doc) m_frm_doc->RemoveMedia(this); m_frm_doc = NULL; OP_DELETE(m_player); m_player = NULL; OP_DELETE(m_controls); m_controls = NULL; } OP_STATUS JILMediaElement::TakeOver(JILMediaElement* src_element) { OP_ASSERT(src_element != this); if (!src_element) return OpStatus::OK; Cleanup(); m_listener = src_element->m_listener; m_player = src_element->m_player; // copy all the attributes m_video_width = src_element->m_video_width; m_video_height = src_element->m_video_height; m_paused = src_element->m_paused; m_suspended = src_element->m_suspended; m_has_controls = src_element->m_has_controls; m_muted = src_element->m_muted; m_playback_ended = src_element->m_playback_ended; m_volume = src_element->m_volume; RETURN_IF_ERROR(EnsureFramesDocument()); RETURN_IF_ERROR(m_frm_doc->AddMedia(this)); RETURN_IF_ERROR(ManageMediaControls()); RETURN_IF_ERROR(HandleTimeUpdate(TRUE)); // reset all attrs in src element src_element->m_listener = NULL; src_element->m_player = NULL; src_element->m_paused = FALSE; src_element->m_suspended = FALSE; src_element->m_has_controls = FALSE; src_element->m_muted = FALSE; src_element->m_playback_ended = FALSE; src_element->m_volume = 1.0; src_element->Cleanup(); if (m_player) m_player->SetListener(this); return OpStatus::OK; } UINT32 JILMediaElement::GetIntrinsicWidth() { UINT32 width = 0; if (OpStatus::IsSuccess(EnsureFramesDocument()) && m_frm_doc->GetShowImages()) width = m_video_width; return width; } UINT32 JILMediaElement::GetIntrinsicHeight() { UINT32 height = 0; if (OpStatus::IsSuccess(EnsureFramesDocument()) && m_frm_doc->GetShowImages()) height = m_video_height; return height; } OP_STATUS JILMediaElement::Paint(VisualDevice* visdev, OpRect video, OpRect content) { OpBitmap* bm = NULL; if (m_player && IsImageType()) RETURN_IF_MEMORY_ERROR(m_player->GetFrame(bm)); if (bm) visdev->BitmapOut(bm, OpRect(0, 0, bm->Width(), bm->Height()), video); if (m_controls) m_controls->Paint(visdev, content); return OpStatus::OK; } OP_STATUS JILMediaElement::Open(const URL &url) { RETURN_IF_ERROR(EnsureFramesDocument()); if (url.IsEmpty()) return OpStatus::ERR; // Cancel loading/playing resource. OP_DELETE(m_player); m_player = NULL; OP_ASSERT(m_frm_doc); RETURN_IF_ERROR(MediaPlayer::Create(m_player, url, URL(), IsImageType(), m_frm_doc->GetWindow())); m_player->SetListener(this); // possibly set via DOM before the player was created OpStatus::Ignore(m_player->SetPlaybackRate(1.0)); OpStatus::Ignore(m_player->SetVolume(m_muted ? 0 : m_volume)); m_paused = TRUE; m_playback_ended = TRUE; //stop progress updates m_progress_update_timer.Stop(); //this will start buffering media content OpStatus::Ignore(m_player->Pause()); return OpStatus::OK; } OP_STATUS JILMediaElement::Play(BOOL resume_playback) { if (!resume_playback || m_playback_ended) RETURN_IF_ERROR(SetPosition(0)); if (m_paused) { if (m_player) m_player->Play(); if (m_playback_ended && m_listener) m_listener->OnPlaybackStart(); m_paused = FALSE; m_playback_ended = FALSE; RETURN_IF_ERROR(HandleTimeUpdate(TRUE)); } return OpStatus::OK; } OP_STATUS JILMediaElement::Pause() { if (!m_paused) { m_paused = TRUE; RETURN_IF_ERROR(HandleTimeUpdate(FALSE)); if (m_player) m_player->Pause(); if (m_listener) m_listener->OnPlaybackPause(); } return OpStatus::OK; } OP_STATUS JILMediaElement::Stop() { if (m_player) m_player->Pause(); if (m_listener) m_listener->OnPlaybackStop(); m_playback_ended = TRUE; m_paused = FALSE; RETURN_IF_ERROR(SetPosition(0)); RETURN_IF_ERROR(HandleTimeUpdate(FALSE)); return OpStatus::OK; } OP_STATUS JILMediaElement::SetPosition(const double position) { OP_ASSERT(position >= 0 && position <= GetDuration()); if (m_player) OpStatus::Ignore(m_player->SetPosition(position)); RETURN_IF_ERROR(HandleTimeUpdate(!m_paused && !m_suspended)); return OpStatus::OK; } double JILMediaElement::GetDuration() const { double duration = op_nan(NULL); if (m_player) OpStatus::Ignore(m_player->GetDuration(duration)); return duration; } void JILMediaElement::OnMouseEvent(DOM_EventType event_type, MouseButton button, int x, int y) { if (m_controls) { // Element wide events switch(event_type) { case ONMOUSEOVER: m_controls->OnElementMouseOver(); break; case ONMOUSEOUT: m_controls->OnElementMouseOut(); break; default: break; } // Controls events Box* layout_box = m_element->GetLayoutBox(); if (!layout_box) return; // Translate mouse position to controls coordinate space. RECT rect; AffinePos rect_pos; if (!layout_box->GetRect(m_frm_doc, CONTENT_BOX, rect_pos, rect)) return; OpRect content = OpRect(0, 0, rect.right - rect.left, rect.bottom - rect.top); OpRect controls = m_controls->GetControlArea(content); OpPoint wpoint(x - controls.x, y - controls.y); if (m_controls->GetBounds().Contains(wpoint)) { switch (event_type) { case ONMOUSEDOWN: m_controls->GenerateOnMouseDown(wpoint, button, 1); break; //case ONMOUSEUP: //Not needed. Hooked widgets gets mouseup in HTML_Document::MouseAction. case ONMOUSEMOVE: // Hooked mousemove events is given to the widget from HTML_Document::MouseAction if (!OpWidget::hooked_widget) m_controls->GenerateOnMouseMove(wpoint); break; default: break; } } } } BOOL JILMediaElement::IsFocusable() const { return m_controls != NULL; } BOOL JILMediaElement::FocusNextInternalTabStop(BOOL forward) { if (m_controls) { OpWidget* next = m_controls->GetNextInternalTabStop(forward); if (next) { next->SetFocus(FOCUS_REASON_KEYBOARD); return TRUE; } } return FALSE; } void JILMediaElement::FocusInternalEdge(BOOL forward) { if (m_controls) { OpWidget* widget = m_controls->GetFocusableInternalEdge(forward); if (widget) widget->SetFocus(FOCUS_REASON_KEYBOARD); } } void JILMediaElement::HandleFocusGained() { if (m_frm_doc && m_frm_doc->GetHtmlDocument()) m_frm_doc->GetHtmlDocument()->SetFocusedElement(m_element); } void JILMediaElement::Update(BOOL just_control_area) { VisualDevice* visdev; if (m_element->GetLayoutBox() && OpStatus::IsSuccess(EnsureFramesDocument()) && (visdev = m_frm_doc->GetVisualDevice())) { OpRect update_rect; if (just_control_area) { // Update only controls area. if (!m_controls) return; // do nothing RECT content_box; m_element->GetLayoutBox()->GetRect(m_frm_doc, CONTENT_BOX, content_box); const OpRect content = OpRect(&content_box); update_rect = m_controls->GetControlArea(content); } else { // Update entire video area. RECT bounding_box; m_element->GetLayoutBox()->GetRect(m_frm_doc, BOUNDING_BOX, bounding_box); update_rect = OpRect(&bounding_box); } visdev->Update(update_rect.x, update_rect.y, update_rect.width, update_rect.height); } } OP_STATUS JILMediaElement::HandleTimeUpdate(BOOL schedule_next_update) { OP_ASSERT(!m_suspended); if (m_controls) m_controls->OnTimeUpdate(TRUE); if (schedule_next_update) m_progress_update_timer.Start(1000); return OpStatus::OK; } OP_STATUS JILMediaElement::EnsureFramesDocument() { OP_ASSERT(!m_suspended); if (!m_frm_doc) { /* The media element might be created by logdoc or via DOM, in * either case we need to find its FramesDocument. */ if (LogicalDocument* log_doc = m_element->GetLogicalDocument()) m_frm_doc = log_doc->GetFramesDocument(); else if (DOM_Environment* dom_env = DOM_Utils::GetDOM_Environment(m_element->GetESElement())) m_frm_doc = dom_env->GetFramesDocument(); if (m_frm_doc) { OP_STATUS status = m_frm_doc->AddMedia(this); if (OpStatus::IsError(status)) { m_frm_doc = NULL; return status; } } } return m_frm_doc ? OpStatus::OK : OpStatus::ERR; } void JILMediaElement::Suspend(BOOL removed) { if (!m_suspended) { m_suspended = TRUE; if (m_player) OpStatus::Ignore(m_player->Suspend()); } if (removed) m_frm_doc = NULL; m_progress_update_timer.Stop(); OP_DELETE(m_controls); m_controls = NULL; } OP_STATUS JILMediaElement::Resume() { if (m_suspended) { m_suspended = FALSE; if (m_player) RETURN_IF_ERROR(m_player->Resume()); RETURN_IF_ERROR(ManageMediaControls()); } return OpStatus::OK; } BOOL JILMediaElement::ControlsNeeded() const { return m_has_controls; } OP_STATUS JILMediaElement::ManageMediaControls() { if (ControlsNeeded()) { RETURN_IF_ERROR(EnsureFramesDocument()); if (!m_controls) { RETURN_IF_ERROR(MediaControls::Create(m_controls, this)); // Don't fade in the controls when just created. m_controls->ForceVisibility(); } else m_controls->EnsureVisibility(); } else { OP_DELETE(m_controls); m_controls = NULL; } return OpStatus::OK; } OP_STATUS JILMediaElement::EnableControls(BOOL enable) { m_has_controls = enable; return ManageMediaControls(); } void JILMediaElement::OnDurationChange(MediaPlayer* player) { OP_ASSERT(player == m_player); if (m_listener) m_listener->OnOpen(FALSE); // Invalidate controls and repaint if (m_controls) m_controls->OnDurationChange(); } void JILMediaElement::OnVideoResize(MediaPlayer* player) { OP_ASSERT(player == m_player); UINT32 video_width, video_height; m_player->GetVideoSize(video_width, video_height); if (m_video_width != video_width || m_video_height != video_height) { m_video_width = video_width; m_video_height = video_height; if (OpStatus::IsSuccess(EnsureFramesDocument())) m_element->MarkDirty(m_frm_doc); } } void JILMediaElement::OnFrameUpdate(MediaPlayer* player) { OP_ASSERT(player == m_player); Update(); } void JILMediaElement::OnDecodeError(MediaPlayer* player) { if (m_listener) m_listener->OnOpen(TRUE); } void JILMediaElement::OnPlaybackEnd(MediaPlayer* player) { OP_ASSERT(player == m_player); m_paused = TRUE; // OnPlaybackEnd may start playing again if (m_listener) m_listener->OnPlaybackEnd(); if (m_paused) m_playback_ended = TRUE; //update progress bar but don't schedule next update RAISE_IF_MEMORY_ERROR(HandleTimeUpdate(FALSE)); // Update controls when playback ends Update(TRUE); } void JILMediaElement::OnError(MediaPlayer* player) { if (m_listener) m_listener->OnOpen(TRUE); } double JILMediaElement::GetMediaDuration() const { double duration = 0; if (m_player) m_player->GetDuration(duration); return duration; } double JILMediaElement::GetMediaPosition() { double position = 0; if (m_player) m_player->GetPosition(position); return position; } OP_STATUS JILMediaElement::SetMediaVolume(const double volume) { if (m_volume != volume) { if (m_player && !m_muted) m_player->SetVolume(volume); m_volume = volume; } return OpStatus::OK; } OP_STATUS JILMediaElement::SetMediaMuted(const BOOL muted) { if ((BOOL)m_muted != muted) { m_muted = muted; if (m_player) m_player->SetVolume(m_muted ? 0 : m_volume); } return OpStatus::OK; } OP_STATUS JILMediaElement::SetMediaPosition(const double position) { return m_player ? m_player->SetPosition(position) : OpStatus::ERR; } /* virtual */ const OpMediaTimeRanges* JILMediaElement::GetMediaBufferedTimeRanges() { const OpMediaTimeRanges* ranges = NULL; if (m_player) RAISE_IF_MEMORY_ERROR(m_player->GetBufferedTimeRanges(ranges)); return ranges; } void JILMediaElement::OnTimeOut(OpTimer* timer) { HandleTimeUpdate(TRUE); } #endif // MEDIA_JIL_PLAYER_SUPPORT
#ifndef tmptools__coretools__instance_of__hpp #define tmptools__coretools__instance_of__hpp namespace tmp { template <typename T> struct instance_of { typedef T type; instance_of(int = 0) {} }; } // tmp #endif // tmptools__coretools__instance_of__hpp
/* -*- 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. */ #include "core/pch.h" #include "modules/hardcore/mh/messobj.h" #include "modules/libgogi/pi_impl/mde_opwindow.h" #include "modules/libgogi/pi_impl/mde_opview.h" #include "modules/libgogi/pi_impl/mde_widget.h" #include "modules/libgogi/pi_impl/mde_generic_screen.h" #include "modules/libgogi/pi_impl/mde_dsmode.h" #include "modules/libgogi/pi_impl/mde_chrome_handler.h" #include "modules/libvega/vegarenderer.h" #include "modules/pi/OpBitmap.h" #ifdef DRAG_SUPPORT #include "modules/dragdrop/dragdrop_manager.h" #endif // DRAG_SUPPORT #ifdef MDE_OPWINDOW_CHROME_SUPPORT #include "modules/skin/OpSkinManager.h" #include "modules/skin/OpSkinElement.h" #include "modules/display/vis_dev.h" class MDE_ChromeWindow: private MessageObject { public: MDE_ChromeWindow() : left_chrome_width(1), right_chrome_width(1), top_chrome_height(1), bottom_chrome_height(1), m_window(NULL), m_ch(NULL) { } ~MDE_ChromeWindow() { g_main_message_handler->UnsetCallBacks(this); OP_DELETE(m_ch); OP_DELETE(m_window); } OP_STATUS Init(MDE_OpWindow *target_window) { m_ch = MDEChromeHandler::Create(); if (!m_ch) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_MDE_CHROMEWINDOW_CLOSE, MH_PARAM_1(this))); RETURN_IF_ERROR(OpWindow::Create(&m_window)); RETURN_IF_ERROR(m_window->Init(OpWindow::STYLE_TRANSPARENT, OpTypedObject::WINDOW_TYPE_UNKNOWN, target_window->GetParentWindow(), target_window->GetParentView(), 0)); RETURN_IF_ERROR(m_ch->InitChrome(m_window, target_window, left_chrome_width, top_chrome_height, right_chrome_width, bottom_chrome_height)); // This is needed because m_window->Init will SetZ to top. We might need to fix this by avoiding that instead. target_window->Raise(); return OpStatus::OK; } void SetZ(MDE_Z z) { ((MDE_OpWindow*)m_window)->GetMDEWidget()->SetZ(z); } void SetVisibility(bool visible) { m_window->Show(visible); } void SetRect(const MDE_RECT &rect) { BOOL resized = m_rect.w != rect.w || m_rect.h != rect.h; m_rect = rect; m_window->SetOuterPos(m_rect.x, m_rect.y); m_window->SetMaximumInnerSize(m_rect.w, m_rect.h); m_window->SetOuterSize(m_rect.w, m_rect.h); if (resized) m_ch->OnResize(m_rect.w, m_rect.h); } void Close(bool delayed = false) { if (delayed) g_main_message_handler->PostMessage(MSG_MDE_CHROMEWINDOW_CLOSE, MH_PARAM_1(this), 0); else { OP_DELETE(m_ch); m_ch = NULL; m_window->Close(FALSE); OP_DELETE(this); } } void SetIconAndTitle(OpBitmap* icon, uni_char* title) { m_ch->SetIconAndTitle(icon, title); } public: void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch (msg) { case MSG_MDE_CHROMEWINDOW_CLOSE: Close(false); break; } } int left_chrome_width; int right_chrome_width; int top_chrome_height; int bottom_chrome_height; MDE_RECT m_rect; OpWindow *m_window; MDEChromeHandler *m_ch; }; #endif // MDE_OPWINDOW_CHROME_SUPPORT MDE_OpWindow::MDE_OpWindow() { mdeWidget = NULL; mdeWidgetShadow = NULL; windowListener = NULL; minInnerWidth = 0; minInnerHeight = 0; maxInnerWidth = 0; maxInnerHeight = 0; cursor = CURSOR_DEFAULT_ARROW; #ifndef GOGI cursorListener = NULL; #endif #ifdef MDE_DS_MODE dsMode = 0; #endif // MDE_DS_MODE m_state = RESTORED; m_state_before_minimize = RESTORED; m_allow_as_active = TRUE; cache_bitmap = NULL; m_title = NULL; m_icon = NULL; m_restored_rect.Set(30, 30, 300, 200); #ifdef MDE_OPWINDOW_CHROME_SUPPORT chromeWin = NULL; #endif // MDE_OPWINDOW_CHROME_SUPPORT m_active = FALSE; } /*virtual*/ MDE_OpWindow::~MDE_OpWindow() { #ifdef MDE_DS_MODE OP_DELETE(dsMode); #endif // MDE_DS_MODE #ifdef MDE_OPWINDOW_CHROME_SUPPORT OP_DELETE(chromeWin); #endif // MDE_OPWINDOW_CHROME_SUPPORT if (mdeWidget) { mdeWidget->SetOpWindow(NULL); // to prevent call to WidgetDeleted OP_DELETE(mdeWidget); mdeWidget = NULL; } OP_DELETE(mdeWidgetShadow); mdeWidgetShadow = NULL; OP_DELETE(cache_bitmap); op_free(m_title); } /*virtual*/ OP_STATUS MDE_OpWindow::Init(Style style, OpTypedObject::Type type, OpWindow* parent_window, OpView* parent_view, void* native_handle, UINT32 effect) { m_parent_window = parent_window; m_parent_view = parent_view; MDE_View* parentWidget = GetParentWidget(parent_window, parent_view); if (!parentWidget && native_handle) parentWidget = ((MDE_Screen*)native_handle)->GetOperaView(); #ifdef VEGA_OPPAINTER_SUPPORT // Creating the OpPainter is delayed to here since the screen can be created // before opera is initialized and we cannot safly use libvega before that if (native_handle && !((MDE_Screen*)native_handle)->GetVegaPainter()) if (((MDE_Screen*)native_handle)->IsType("MDE_GENERICSCREEN")) RETURN_IF_ERROR(((MDE_GenericScreen*)native_handle)->CreateVegaPainter()); else return OpStatus::ERR; #endif // VEGA_OPPAINTER_SUPPORT this->style = style; this->effect = effect; this->transparency = 255; this->ignore_mouse_input = FALSE; switch (style) { case STYLE_POPUP: // always create popups as toplevel windows if (parentWidget) { parentWidget = GetScreenView(parentWidget, parent_window, parent_view); } else { OP_ASSERT(FALSE); // no possible parent for popup return OpStatus::ERR; // we could fall back on the first of the screens -- but we probably hide more errors that way } case STYLE_UNKNOWN: case STYLE_DESKTOP: case STYLE_TOOLTIP: case STYLE_NOTIFIER: case STYLE_MODAL_DIALOG: case STYLE_MODELESS_DIALOG: case STYLE_BLOCKING_DIALOG: case STYLE_CONSOLE_DIALOG: case STYLE_CHILD: case STYLE_WORKSPACE: case STYLE_EMBEDDED: case STYLE_ADOPT: default: // FIXME: the null in this case should probably be a painter to paint the window #ifdef VEGA_OPPAINTER_SUPPORT mdeWidget = OP_NEW(MDE_Widget, (OpRect(0,0,0,0))); #else mdeWidget = OP_NEW(MDE_Widget, (NULL, OpRect(0,0,0,0))); #endif if (mdeWidget) { mdeWidget->SetVisibility(false); mdeWidget->SetVisibilityListener(this); } break; } if (!mdeWidget) { return OpStatus::ERR_NO_MEMORY; } UpdateTransparency(); if (parentWidget) { parentWidget->AddChild(mdeWidget); maxInnerWidth = parentWidget->m_rect.w; maxInnerHeight = parentWidget->m_rect.h; } if (effect & OpWindow::EFFECT_DROPSHADOW) { // FIXME: the null in this case should probably be a painter to paint the window #ifdef VEGA_OPPAINTER_SUPPORT mdeWidgetShadow = OP_NEW(MDE_Widget, (OpRect(0,0,0,0))); #else // VEGA_OPPAINTER_SUPPORT mdeWidgetShadow = OP_NEW(MDE_Widget, (NULL, OpRect(0,0,0,0))); #endif // !VEGA_OPPAINTER_SUPPORT if (mdeWidgetShadow) { mdeWidgetShadow->SetOpWindow(this); mdeWidgetShadow->SetIsShadow(true, false); mdeWidgetShadow->SetTransparent(TRUE); if (parentWidget) parentWidget->AddChild(mdeWidgetShadow); } } mdeWidget->SetOpWindow(this); // FIXME: This might not be needed if style is implemented properly if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_TOP); mdeWidget->SetZ(MDE_Z_TOP); return OpStatus::OK; } OpBitmap *MDE_OpWindow::GetCacheBitmap() { if (!cache_bitmap) return NULL; int w = mdeWidget->m_rect.w; int h = mdeWidget->m_rect.h; if (cache_bitmap->Width() != (UINT32)w || cache_bitmap->Height() != (UINT32)h) { OP_DELETE(cache_bitmap); cache_bitmap = NULL; } if (!cache_bitmap && w > 0 && h > 0) OpBitmap::Create(&cache_bitmap, w, h, FALSE, mdeWidget->m_is_transparent, 0, 0, TRUE); return cache_bitmap; } void MDE_OpWindow::SetCached(BOOL cached) { if (cached) { if (cache_bitmap) return; OpBitmap::Create(&cache_bitmap, mdeWidget->m_rect.w, mdeWidget->m_rect.h, FALSE, mdeWidget->m_is_transparent, 0, 0, TRUE); mdeWidget->InvalidateCache(); } else { if (!cache_bitmap) return; OP_DELETE(cache_bitmap); cache_bitmap = NULL; } } void MDE_OpWindow::UpdateTransparency() { bool transp = false; if (transparency != 255) transp = true; else if (style == STYLE_GADGET || style == STYLE_OVERLAY || style == STYLE_TRANSPARENT || style == STYLE_BITMAP_WINDOW #ifdef PI_ANIMATED_WINDOWS || style == STYLE_ANIMATED #endif // PI_ANIMATED_WINDOWS || (effect & OpWindow::EFFECT_TRANSPARENT)) transp = true; if (mdeWidget->m_is_transparent != transp) { OP_DELETE(cache_bitmap); cache_bitmap = NULL; } mdeWidget->SetTransparent(transp); } /*virtual*/ MDE_View* MDE_OpWindow::GetScreenView(const MDE_View *parentWidget, const OpWindow* parent_window, const OpView* parent_view) const { MDE_View* root = (MDE_View*) parentWidget; while (root->m_parent) root = root->m_parent; return root; } /*virtual*/ MDE_View* MDE_OpWindow::GetParentWidget(const OpWindow* parent_window, const OpView* parent_view) const { MDE_View *parentWidget = NULL; if (parent_window) parentWidget = ((MDE_OpWindow*)parent_window)->GetMDEWidget(); else if (parent_view) parentWidget = ((MDE_OpView*)parent_view)->GetMDEWidget(); return parentWidget; } /*virtual*/ void MDE_OpWindow::SetParent(OpWindow* parent_window, OpView* parent_view, BOOL behind) { OP_ASSERT(mdeWidget); if (style == STYLE_POPUP) { return; } m_parent_window = parent_window; m_parent_view = parent_view; MDE_View *parentWidget = GetParentWidget(parent_window, parent_view); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) { dsMode->m_parent->RemoveChild(dsMode); parentWidget->AddChild(dsMode); } else #endif // MDE_DS_MODE { mdeWidget->m_parent->RemoveChild(mdeWidget); parentWidget->AddChild(mdeWidget); } maxInnerWidth = parentWidget->m_rect.w; maxInnerHeight = parentWidget->m_rect.h; if (m_state == MAXIMIZED) { // Maximize again to adapt to the new parents size. Maximize(); } else if (m_state == RESTORED) { // Maximize and restore again, so the restored chrome will be recreated in the new parent. Maximize(); Restore(); } } /*virtual*/ void MDE_OpWindow::SetWindowListener(OpWindowListener *windowlistener) { OP_ASSERT(mdeWidget || !windowlistener); this->windowListener = windowlistener; } MDE_OpWindow * MDE_OpWindow::GetBottomMostWindow() { if (!mdeWidget->m_parent) return 0; for (MDE_View* v = mdeWidget->m_parent->m_first_child; v; v = v->m_next) { if (v->IsType("MDE_Widget")) { MDE_Widget* w = static_cast<MDE_Widget*>(v); if (OpWindow* ow = w->GetOpWindow()) { MDE_OpWindow* mw = static_cast<MDE_OpWindow*>(ow); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (!mw->IsChromeWindow()) #endif // MDE_OPWINDOW_CHROME_SUPPORT return mw; } } } return 0; } MDE_OpWindow* MDE_OpWindow::NextWindow() { for (MDE_View* v = mdeWidget->m_next; v; v = v->m_next) if (v->IsType("MDE_Widget")) { MDE_Widget* w = static_cast<MDE_Widget*>(v); if (OpWindow* ow = w->GetOpWindow()) { MDE_OpWindow* mw = static_cast<MDE_OpWindow*>(ow); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (!mw->IsChromeWindow()) #endif // MDE_OPWINDOW_CHROME_SUPPORT return mw; } } return 0; } #ifdef MDE_OPWINDOW_CHROME_SUPPORT /** returns TRUE if view is an MDE_Widget with an associated MDE_OpWindow that has chrome */ static BOOL HasDecorations(MDE_View* view) { if (view && view->IsType("MDE_Widget")) { MDE_Widget* widget = static_cast<MDE_Widget*>(view); if (widget->GetOpWindow()) { MDE_OpWindow* window = static_cast<MDE_OpWindow*>(widget->GetOpWindow()); return window->HasChrome(); } } return FALSE; } void MDE_OpWindow::LowerWindow() { LowerWindowOneStep(); /* Now that this window has been lowered past another window, * check if that other window has decorations. In that case, we * need to lower this new window past the decorations too. * * (mdeWidget->m_next is the window above mdeWidget in the * Z-order. That's why we have to lower this window * before checking what mdeWidget->m_next is.) */ if (HasDecorations(mdeWidget->m_next)) LowerWindowOneStep(); } void MDE_OpWindow::LowerWindowOneStep() { if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_LOWER); if (chromeWin) chromeWin->SetZ(MDE_Z_LOWER); mdeWidget->SetZ(MDE_Z_LOWER); } #else // MDE_OPWINDOW_CHROME_SUPPORT void MDE_OpWindow::LowerWindow() { if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_LOWER); mdeWidget->SetZ(MDE_Z_LOWER); } #endif // MDE_OPWINDOW_CHROME_SUPPORT void MDE_OpWindow::MoveToBottomOfWindowStack() { MDE_OpWindow* bottomwindow = 0; MDE_OpWindow * candidate = GetBottomMostWindow(); while (candidate && !bottomwindow) { if (candidate->m_state != MINIMIZED) bottomwindow = candidate; else candidate = candidate->NextWindow(); } /* If this assert fails, I have misunderstood something and the * test below is probably wrong. */ OP_ASSERT(mdeWidget->GetOpWindow() == this); // Now move the window below the current bottom-most visible window. if (bottomwindow && bottomwindow != this) { /* 'prev' is used to break out of the loop if we fail to find * bottomwindow. */ MDE_View * prev = bottomwindow->mdeWidget; while (NextWindow() != bottomwindow && mdeWidget->m_next != prev) { prev = mdeWidget->m_next; LowerWindow(); } } } #ifdef MDE_OPWINDOW_CHROME_SUPPORT BOOL MDE_OpWindow::IsChromeWindow() { MDE_View * v = mdeWidget->m_next; if (!v) return FALSE; if (!v->IsType("MDE_Widget")) return FALSE; MDE_Widget* w = static_cast<MDE_Widget*>(v); OpWindow* ow = w->GetOpWindow(); if (!ow) return FALSE; MDE_ChromeWindow * next_chrome = static_cast<MDE_OpWindow*>(ow)->chromeWin; if (!next_chrome) return FALSE; return next_chrome->m_window == this; }; #endif /*virtual*/ void MDE_OpWindow::SetDesktopPlacement(const OpRect& rect, State state, BOOL inner, BOOL behind, BOOL center) { State old_state = m_state; if (state == MINIMIZED && m_state != MINIMIZED) m_state_before_minimize = m_state; m_state = state; if (state == MAXIMIZED || state == MINIMIZED) { if (mdeWidgetShadow && mdeWidgetShadow->IsFullscreenShadow()) { mdeWidgetShadow->m_parent->RemoveChild(mdeWidgetShadow); OP_DELETE(mdeWidgetShadow); mdeWidgetShadow = NULL; } if (state == MAXIMIZED) SetWidgetRect(MDE_MakeRect(0,0,mdeWidget->m_parent->m_rect.w, mdeWidget->m_parent->m_rect.h)); else SetWidgetRect(MDE_MakeRect(rect.x, rect.y, rect.width, rect.height)); } else { MDE_RECT r = MDE_MakeRect(rect.x, rect.y, rect.width, rect.height); /*if (!mdeWidgetShadow && ((effect & OpWindow::EFFECT_DROPSHADOW) || (style == STYLE_DESKTOP))) { // FIXME: the null in this case should probably be a painter to paint the window #ifdef VEGA_OPPAINTER_SUPPORT mdeWidgetShadow = OP_NEW(MDE_Widget, (OpRect(0,0,0,0))); #else // VEGA_OPPAINTER_SUPPORT mdeWidgetShadow = OP_NEW(MDE_Widget, (NULL, OpRect(0,0,0,0))); #endif // !VEGA_OPPAINTER_SUPPORT if (mdeWidgetShadow) { mdeWidgetShadow->SetOpWindow(this); mdeWidgetShadow->SetIsShadow(true, true); mdeWidgetShadow->SetTransparent(TRUE); mdeWidget->m_parent->AddChild(mdeWidgetShadow); } }*/ if (center) { r.x = (mdeWidget->m_parent->m_rect.w-rect.width+1)/2; r.y = (mdeWidget->m_parent->m_rect.y-rect.height+1)/2; } SetWidgetRect(r); } if (state == MINIMIZED) { // Make invisible and deactivate SetWidgetVisibility(false); if (state != old_state) DeactivateAndActivateTopmost(TRUE); // Put window at bottom (so futher minimizing will not pick this one to activate next) if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_BOTTOM); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetZ(MDE_Z_BOTTOM); #endif // MDE_OPWINDOW_CHROME_SUPPORT mdeWidget->SetZ(MDE_Z_BOTTOM); } else { SetWidgetVisibility(true); if (windowListener) { windowListener->OnResize(mdeWidget->m_rect.w, mdeWidget->m_rect.h); windowListener->OnShow(TRUE); } } if (behind) { MoveToBottomOfWindowStack(); } if (!mdeWidget->m_next && state != MINIMIZED) Activate(); } /*virtual*/ void MDE_OpWindow::GetDesktopPlacement(OpRect& rect, State& state) { rect.x = mdeWidget->m_rect.x; rect.y = mdeWidget->m_rect.y; rect.width = mdeWidget->m_rect.w; rect.height = mdeWidget->m_rect.h; state = m_state; } /*virtual*/ void MDE_OpWindow::Restore() { SetDesktopPlacement(m_restored_rect, RESTORED); } /*virtual*/ void MDE_OpWindow::Minimize() { SetDesktopPlacement(OpRect(mdeWidget->m_rect.x,mdeWidget->m_rect.y,mdeWidget->m_rect.w,mdeWidget->m_rect.h), MINIMIZED); } /*virtual*/ void MDE_OpWindow::Maximize() { SetDesktopPlacement(OpRect(0,0,mdeWidget->m_rect.w,mdeWidget->m_rect.h), MAXIMIZED); } /*virtual*/ void MDE_OpWindow::Fullscreen() { OP_ASSERT(0); } /*virtual*/ void MDE_OpWindow::LockUpdate(BOOL lock) { OP_ASSERT(0); } /*virtual*/ void MDE_OpWindow::Show(BOOL show) { if (mdeWidget->m_is_visible == (show ? true : false)) return; #ifdef MDE_DS_MODE if (dsMode) dsMode->SetVisibility(show ? true : false); #endif // MDE_DS_MODE SetWidgetVisibility(show ? true : false); if (windowListener) windowListener->OnShow(show); #if defined(VEGA_OPPAINTER_SUPPORT) && defined(VEGA_OPPAINTER_ANIMATIONS) /* Disabled for now. Should be done in a different position since we don't want *all* windows to animate. if (mdeWidget && mdeWidget->m_screen && !MDE_RectIsEmpty(mdeWidget->m_rect)) { VEGAOpPainter* painter = ((MDE_GenericScreen*)mdeWidget->m_screen)->GetVegaPainter(); painter->prepareAnimation(OpRect(mdeWidget->m_rect.x, mdeWidget->m_rect.y, mdeWidget->m_rect.w, mdeWidget->m_rect.h), show?VEGAOpPainter::ANIM_SHOW_WINDOW:VEGAOpPainter::ANIM_HIDE_WINDOW); painter->startAnimation(OpRect(mdeWidget->m_rect.x, mdeWidget->m_rect.y, mdeWidget->m_rect.w, mdeWidget->m_rect.h)); }*/ #endif // VEGA_OPPAINTER_SUPPORT && VEGA_OPPAINTER_ANIMATIONS if (!mdeWidget->m_next && show) Activate(); } /*virtual*/ void MDE_OpWindow::SetFocus(BOOL focus) { // FIXME: is this correct? (focus stuff for mde) OP_ASSERT(mdeWidget); if (focus) { Raise(); } if (m_allow_as_active) { NotifyOnActivate(focus, this); } #if defined(VEGA_OPPAINTER_SUPPORT) && defined(VEGA_OPPAINTER_ANIMATIONS) if (mdeWidget && mdeWidget->m_screen) { VEGAOpPainter* painter = ((MDE_GenericScreen*)mdeWidget->m_screen)->GetVegaPainter(); painter->prepareAnimation(OpRect(mdeWidget->m_rect.x, mdeWidget->m_rect.y, mdeWidget->m_rect.w, mdeWidget->m_rect.h), VEGAOpPainter::ANIM_SWITCH_TAB); painter->startAnimation(OpRect(mdeWidget->m_rect.x, mdeWidget->m_rect.y, mdeWidget->m_rect.w, mdeWidget->m_rect.h)); } #endif // VEGA_OPPAINTER_SUPPORT && VEGA_OPPAINTER_ANIMATIONS } /*virtual*/ void MDE_OpWindow::CloseInternal() { if (mdeWidget->m_parent) mdeWidget->m_parent->RemoveChild(mdeWidget); if (mdeWidgetShadow && mdeWidgetShadow->m_parent) mdeWidgetShadow->m_parent->RemoveChild(mdeWidgetShadow); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { chromeWin->Close(); chromeWin = NULL; } #endif // MDE_OPWINDOW_CHROME_SUPPORT #ifdef MDE_DS_MODE if (dsMode) dsMode->SetVisibility(FALSE); #endif // MDE_DS_MODE } void MDE_OpWindow::Close(BOOL user_initiated) { CloseInternal(); if (windowListener) { windowListener->OnClose(user_initiated); } } void MDE_OpWindow::WidgetDeleted() { CloseInternal(); mdeWidget = NULL; if (windowListener) { windowListener->OnClose(FALSE); } } /*virtual*/ void MDE_OpWindow::GetOuterSize(UINT32* width, UINT32* height) { GetInnerSize(width, height); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { *width += chromeWin->left_chrome_width+chromeWin->right_chrome_width; *height += chromeWin->top_chrome_height+chromeWin->bottom_chrome_height; } #endif // MDE_OPWINDOW_CHROME_SUPPORT } /*virtual*/ void MDE_OpWindow::SetOuterSize(UINT32 width, UINT32 height) { #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { width -= chromeWin->left_chrome_width+chromeWin->right_chrome_width; height -= chromeWin->top_chrome_height+chromeWin->bottom_chrome_height; } #endif // MDE_OPWINDOW_CHROME_SUPPORT SetInnerSize(width, height); } /*virtual*/ void MDE_OpWindow::GetInnerSize(UINT32* width, UINT32* height) { OP_ASSERT(mdeWidget); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) { *width = dsMode->m_rect.w; *height = dsMode->m_rect.h; } else #endif // MDE_DS_MODE { *width = MAX(mdeWidget->m_rect.w,0); *height = MAX(mdeWidget->m_rect.h,0); } } /*virtual*/ BOOL MDE_OpWindow::SetWidgetRect(const MDE_RECT& mr) { BOOL changed = !MDE_RectIsIdentical(mr, mdeWidget->m_rect); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) { dsMode->SetRect(mr); dsMode->Resize(mr.w,mr.h); changed = TRUE; } else #endif // MDE_DS_MODE mdeWidget->SetRect(mr); MDE_RECT view_rect = mr; if (m_state == RESTORED) m_restored_rect.Set(mr.x, mr.y, mr.w, mr.h); #ifdef MDE_OPWINDOW_CHROME_SUPPORT BOOL need_chrome = (m_state != MAXIMIZED); if (!mdeWidget->m_parent || (mr.x == 0 && mr.y == 0 && mr.w == mdeWidget->m_parent->m_rect.w && mr.h == mdeWidget->m_parent->m_rect.h)) need_chrome = FALSE; // Delete chrome if we maximize if (chromeWin && !need_chrome) { chromeWin->Close(true); chromeWin = NULL; } // Add chrome if we restore else if (!chromeWin && style == STYLE_DESKTOP && need_chrome) { chromeWin = OP_NEW(MDE_ChromeWindow, ()); if (chromeWin && OpStatus::IsSuccess(chromeWin->Init(this))) chromeWin->SetIconAndTitle(m_icon, m_title); else { OP_DELETE(chromeWin); chromeWin = NULL; } } if (chromeWin) { view_rect.x -= chromeWin->left_chrome_width; view_rect.y -= chromeWin->top_chrome_height; view_rect.w += chromeWin->left_chrome_width+chromeWin->right_chrome_width; view_rect.h += chromeWin->top_chrome_height+chromeWin->bottom_chrome_height; chromeWin->SetRect(view_rect); } #endif // MDE_OPWINDOW_CHROME_SUPPORT if (mdeWidgetShadow) { MDE_RECT shadow_rect = view_rect; #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { shadow_rect.y += chromeWin->top_chrome_height - 1; shadow_rect.h -= chromeWin->top_chrome_height - 1; } #endif if (mdeWidgetShadow->IsFullscreenShadow() && mdeWidgetShadow->m_parent) { shadow_rect.x = 0; shadow_rect.y = 0; shadow_rect.w = mdeWidgetShadow->m_parent->m_rect.w; shadow_rect.h = mdeWidgetShadow->m_parent->m_rect.h; } else { shadow_rect.x += 5; shadow_rect.y += 5; } mdeWidgetShadow->SetRect(shadow_rect); } return changed; } void MDE_OpWindow::SetWidgetVisibility(bool vis) { mdeWidget->SetVisibility(vis); if (mdeWidgetShadow) mdeWidgetShadow->SetVisibility(vis); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetVisibility(vis); #endif // MDE_OPWINDOW_CHROME_SUPPORT } /*virtual*/ void MDE_OpWindow::SetInnerSize(UINT32 width, UINT32 height) { if (m_state != RESTORED && !(m_state == MAXIMIZED && width == (UINT32)mdeWidget->m_parent->m_rect.w && height == (UINT32)mdeWidget->m_parent->m_rect.h)) return; MDE_RECT mr; OP_ASSERT(mdeWidget); /* Treat maxInnerWidth == 0 as maxInnerWidth == infinite */ if (maxInnerWidth && width > maxInnerWidth) { width = maxInnerWidth; } /* Treat maxInnerHeight == 0 as maxInnerHeight == infinite */ if (maxInnerHeight && height > maxInnerHeight) { height = maxInnerHeight; } if (width < minInnerWidth) { width = minInnerWidth; } if (height < minInnerHeight) { height = minInnerHeight; } #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) mr = dsMode->m_rect; else #endif // MDE_DS_MODE mr = mdeWidget->m_rect; mr.w = width; mr.h = height; if (!SetWidgetRect(mr)) return; for (MDE_View* w = mdeWidget->m_first_child; w; w = w->m_next) { MDE_OpWindow *child_window = NULL; if (w->IsType("MDE_Widget")) child_window = (MDE_OpWindow*)((MDE_Widget*)w)->GetOpWindow(); if (child_window) child_window->SetMaximumInnerSize(width, height); if (child_window && child_window->m_state == MAXIMIZED) { child_window->SetInnerSize(width, height); child_window->SetInnerPos(0, 0); } else if (child_window) { if (child_window->mdeWidgetShadow && child_window->mdeWidgetShadow->IsFullscreenShadow()) { MDE_RECT shadow_rect; shadow_rect.x = 0; shadow_rect.y = 0; shadow_rect.w = mdeWidget->m_rect.w; shadow_rect.h = mdeWidget->m_rect.h; child_window->mdeWidgetShadow->SetRect(shadow_rect); } } } if (windowListener) windowListener->OnResize(mdeWidget->m_rect.w, mdeWidget->m_rect.h); } /*virtual*/ void MDE_OpWindow::GetOuterPos(INT32* x, INT32* y) { GetInnerPos(x, y); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { *x -= chromeWin->left_chrome_width; *y -= chromeWin->top_chrome_height; } #endif // MDE_OPWINDOW_CHROME_SUPPORT } /*virtual*/ void MDE_OpWindow::SetOuterPos(INT32 x, INT32 y) { #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) { x += chromeWin->left_chrome_width; y += chromeWin->top_chrome_height; } #endif // MDE_OPWINDOW_CHROME_SUPPORT SetInnerPos(x, y); } /*virtual*/ void MDE_OpWindow::GetInnerPos(INT32* x, INT32* y) { OP_ASSERT(mdeWidget); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) { *x = dsMode->m_rect.x; *y = dsMode->m_rect.y; } else #endif // MDE_DS_MODE { *x = mdeWidget->m_rect.x; *y = mdeWidget->m_rect.y; } } /*virtual*/ void MDE_OpWindow::SetInnerPos(INT32 x, INT32 y) { if (m_state != RESTORED && !(m_state == MAXIMIZED && x == 0 && y == 0)) return; MDE_RECT mr; OP_ASSERT(mdeWidget); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) mr = dsMode->m_rect; else #endif // MDE_DS_MODE mr = mdeWidget->m_rect; mr.x = x; mr.y = y; SetWidgetRect(mr); } /*virtual*/ void MDE_OpWindow::SetMinimumInnerSize(UINT32 width, UINT32 height) { minInnerWidth = width; minInnerHeight = height; } /*virtual*/ void MDE_OpWindow::SetMaximumInnerSize(UINT32 width, UINT32 height) { maxInnerWidth = width; maxInnerHeight = height; } /*virtual*/ void MDE_OpWindow::GetMargin(INT32* left_margin, INT32* top_margin, INT32* right_margin, INT32* bottom_margin) { OP_ASSERT(left_margin && top_margin && right_margin && bottom_margin); (*left_margin) = 0; (*top_margin) = 0; (*right_margin) = 0; (*bottom_margin) = 0; } /*virtual*/ void MDE_OpWindow::SetTransparency(INT32 transparency) { if (this->transparency != transparency) { this->transparency = transparency; UpdateTransparency(); Redraw(); } } /*virtual*/ void MDE_OpWindow::SetWorkspaceMinimizedVisibility(BOOL workspace_minimized_visibility) { OP_ASSERT(0); } /*virtual*/ void MDE_OpWindow::SetSkin(const char* skin) { OP_ASSERT(0); } /*virtual*/ void MDE_OpWindow::Redraw() { // I should probably update all children too mdeWidget->Invalidate(MDE_MakeRect(0,0,mdeWidget->m_rect.w,mdeWidget->m_rect.h), true); if (mdeWidgetShadow) mdeWidgetShadow->Invalidate(MDE_MakeRect(0,0,mdeWidgetShadow->m_rect.w,mdeWidgetShadow->m_rect.h)); } /*virtual*/ OpWindow::Style MDE_OpWindow::GetStyle() { return style; } /*virtual*/ void MDE_OpWindow::Raise() { OP_ASSERT(mdeWidget); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) dsMode->SetZ(MDE_Z_TOP); else #endif // MDE_DS_MODE { if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_TOP); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetZ(MDE_Z_TOP); #endif // MDE_OPWINDOW_CHROME_SUPPORT mdeWidget->SetZ(MDE_Z_TOP); } } /*virtual*/ void MDE_OpWindow::Lower() { OP_ASSERT(mdeWidget); #ifdef MDE_DS_MODE if (dsMode && dsMode->IsDSEnabled()) dsMode->SetZ(MDE_Z_BOTTOM); else #endif // MDE_DS_MODE { mdeWidget->SetZ(MDE_Z_BOTTOM); #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetZ(MDE_Z_BOTTOM); #endif // MDE_OPWINDOW_CHROME_SUPPORT if (mdeWidgetShadow) mdeWidgetShadow->SetZ(MDE_Z_BOTTOM); } DeactivateAndActivateTopmost(); } void MDE_OpWindow::DeactivateAndActivateTopmost(BOOL minimizing) { MDE_OpWindow* ow = NULL; if (mdeWidget->m_parent) { for (MDE_View* v = mdeWidget->m_parent->m_first_child; v; v = v->m_next) { if (v->IsType("MDE_Widget") && ((MDE_Widget*)v)->GetOpWindow() && ((MDE_OpWindow*)((MDE_Widget*)v)->GetOpWindow())->windowListener) { MDE_OpWindow* tw = (MDE_OpWindow*)((MDE_Widget*)v)->GetOpWindow(); if (tw != this && tw->m_state != MINIMIZED) { ow = tw; } } } } if (ow) ow->Activate(); else if (minimizing) NotifyOnActivate(FALSE, this); } /*virtual*/ void MDE_OpWindow::Activate() { if (IsActive()) return; OP_ASSERT(mdeWidget); if (!m_allow_as_active) return; State old_state = m_state; if (m_state == MINIMIZED) { m_state = m_state_before_minimize; if (m_state == MAXIMIZED && mdeWidget->m_parent) SetWidgetRect(MDE_MakeRect(0,0,mdeWidget->m_parent->m_rect.w, mdeWidget->m_parent->m_rect.h)); SetWidgetVisibility(true); } if (style != STYLE_POPUP) { // Find what we probably called OnActivate(TRUE) on before. // This isn't really a reliable way to do it. MDE_OpWindow* ow = NULL; for (MDE_View* v = mdeWidget->m_parent->m_first_child; v; v = v->m_next) { if (v->IsType("MDE_Widget") && ((MDE_Widget*)v)->GetOpWindow() && ((MDE_Widget*)v)->GetOpWindow() != this && ((MDE_OpWindow*)((MDE_Widget*)v)->GetOpWindow())->windowListener && ((MDE_OpWindow*)((MDE_Widget*)v)->GetOpWindow())->IsActive()) { ow = (MDE_OpWindow*)((MDE_Widget*)v)->GetOpWindow(); } } if (ow) NotifyOnActivate(FALSE, ow); } Raise(); if (windowListener) { if (old_state == MINIMIZED) { windowListener->OnResize(mdeWidget->m_rect.w, mdeWidget->m_rect.h); windowListener->OnShow(TRUE); } NotifyOnActivate(TRUE, this); } } void MDE_OpWindow::Deactivate() { if (m_allow_as_active && IsActive()) { NotifyOnActivate(FALSE, this); } } void MDE_OpWindow::NotifyOnActivate(BOOL activate, MDE_OpWindow* ow) { OP_ASSERT(ow); if (ow && ow->windowListener && activate != ow->IsActive()) { ow->windowListener->OnActivate(activate); ow->SetActive(activate); } } /*virtual*/ void MDE_OpWindow::Attention() { OP_ASSERT(0); } #ifndef MOUSELESS /*virtual*/ void MDE_OpWindow::SetCursor(CursorType cursor) { #ifndef GOGI if (this->cursor == cursor) return; #endif this->cursor = cursor; if (!mdeWidget->m_screen) return; // Check if we are currently hovering this view with the mouse. Otherwise we shouldn't change the cursor! MDE_View *hovered_view = mdeWidget->m_screen->GetViewAt(mdeWidget->m_screen->m_mouse_x, mdeWidget->m_screen->m_mouse_y, true); while (hovered_view) { if (hovered_view == mdeWidget) break; hovered_view = hovered_view->m_parent; } #ifdef MDE_SUPPORT_DND if (!hovered_view && g_drag_manager->IsDragging()) { // Check if we are currently hovering this view. Otherwise we shouldn't change the cursor! hovered_view = mdeWidget->m_screen->GetViewAt(mdeWidget->m_screen->m_drag_x, mdeWidget->m_screen->m_drag_y, true); while (hovered_view) { if (hovered_view == mdeWidget) break; hovered_view = hovered_view->m_parent; } } #endif // MDE_SUPPORT_DND if (!hovered_view) return; #ifdef GOGI ((MDE_GenericScreen*)mdeWidget->m_screen)->SetCursor(this, cursor); #else // !GOGI if (cursorListener) cursorListener->OnSetCursor(cursor, (MDE_Screen*)mdeWidget->m_screen); #endif // GOGI } /*virtual*/ CursorType MDE_OpWindow::GetCursor() { return cursor; } #endif // !MOUSELESS /*virtual*/ const uni_char* MDE_OpWindow::GetTitle() const { return m_title; } /*virtual*/ void MDE_OpWindow::SetTitle(const uni_char* title) { op_free(m_title); if (title) m_title = uni_strdup(title); else m_title = NULL; #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetIconAndTitle(m_icon, m_title); #endif // MDE_OPWINDOW_CHROME_SUPPORT } /*virtual*/ void MDE_OpWindow::SetIcon(OpBitmap* icon) { m_icon = icon; #ifdef MDE_OPWINDOW_CHROME_SUPPORT if (chromeWin) chromeWin->SetIconAndTitle(m_icon, m_title); #endif // MDE_OPWINDOW_CHROME_SUPPORT } #ifndef GOGI void MDE_OpWindow::SetCursorListener(OpCursorListener *cl) { cursorListener = cl; } #endif #ifdef MDE_DS_MODE /*virtual*/ OP_STATUS MDE_OpWindow::SetDSMode(BOOL enable) { if (enable && !dsMode) { dsMode = OP_NEW(MDE_DSMode, ()); if (!dsMode) return OpStatus::ERR_NO_MEMORY; } if (dsMode) { RETURN_IF_ERROR(dsMode->EnableDS(enable, mdeWidget)); if (windowListener) windowListener->OnResize(mdeWidget->m_rect.w, mdeWidget->m_rect.h); } return OpStatus::OK; } BOOL MDE_OpWindow::GetDSMode() { return dsMode && dsMode->IsDSEnabled(); } #endif // MDE_DS_MODE void MDE_OpWindow::OnVisibilityChanged(bool vis) { if (windowListener) windowListener->OnVisibilityChanged(vis); } void MDE_OpWindow::OnRectChanged(const MDE_RECT &old_rect) { if (!windowListener) return; OP_ASSERT(mdeWidget->m_rect.x != old_rect.x || mdeWidget->m_rect.y != old_rect.y || mdeWidget->m_rect.w != old_rect.w || mdeWidget->m_rect.h != old_rect.h); if (mdeWidget->m_rect.x != old_rect.x || mdeWidget->m_rect.y != old_rect.y) windowListener->OnMove(); // FIX: Should probably move the OnResize handling here too! But maybe we should only send theese callbacks when the window has been made visible? //if (mdeWidget->m_rect.w != old_rect.w || mdeWidget->m_rect.h != old_rect.h) // windowListener->OnResize(mdeWidget->m_rect.w, mdeWidget->m_rect.h); } bool MDE_OpWindow::PaintOnBitmap(OpBitmap *bitmap) { if (OpPainter *painter = bitmap->GetPainter()) { #ifdef VEGA_OPPAINTER_SUPPORT ((VEGAOpPainter*)painter)->GetRenderer()->clear(0, 0, bitmap->Width(), bitmap->Height(), 0x00000000); #endif bool ret = false; MDE_View *tmp = mdeWidget->m_first_child; while (tmp) { if (tmp->IsType("MDE_Widget")) ret |= ((MDE_Widget*)tmp)->Paint(painter); tmp = tmp->m_next; } bitmap->ReleasePainter(); return ret; } return false; } OpBitmap *MDE_OpWindow::CreateBitmapFromWindow() { int w = mdeWidget->m_rect.w, h = mdeWidget->m_rect.h; OpBitmap *bitmap = NULL; if (OpStatus::IsError(OpBitmap::Create(&bitmap, w, h, FALSE, TRUE, 0, 0, TRUE))) return NULL; if (PaintOnBitmap(bitmap)) return bitmap; OP_DELETE(bitmap); return NULL; }
#pragma once #include "IComponent.h" namespace Hourglass { class AudioSource : public IComponent { DECLARE_COMPONENT_TYPEID public: void Start(); void Shutdown(); IComponent* MakeCopyDerived() const; void PostAudioEvent(uint64_t eventId) const; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-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 WBXML_DECODER_H #define WBXML_DECODER_H #include "modules/url/protocols/http_te.h" class WBXML_Parser; class WBXML_Decoder : public Data_Decoder { private: WBXML_Parser *m_parser; char* m_src_buf; UINT32 m_src_buf_pos; UINT32 m_src_buf_len; public: WBXML_Decoder(); virtual ~WBXML_Decoder(); #ifdef OOM_SAFE_API virtual unsigned int ReadDataL(char *buf, unsigned int blen, URL_DataDescriptor *desc, BOOL &read_storage, BOOL &more); #else virtual unsigned int ReadData(char *buf, unsigned int blen, URL_DataDescriptor *desc, BOOL &read_storage, BOOL &more); #endif //OOM_SAFE_API /** Get character set associated with this Data_Decoder. * @return NULL if no character set is associated */ virtual const char *GetCharacterSet(); /** Get character set detected for this CharacterDecoder. * @return Name of character set, NULL if no character set can be * determined. */ virtual const char *GetDetectedCharacterSet(); /** Stop guessing character set for this document. * Character set detection wastes cycles, and avoiding it if possible * is nice. */ virtual void StopGuessingCharset(); BOOL IsWml(); virtual BOOL IsA(const uni_char *type); }; #endif // WBXML_DECODER_H
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; /////////////// better one ///////////////// int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) vector<int> opt(A.size(),0); // best sol that end at index i for (int i=1; i<A.size(); ++i){ int j = 6; if(i-j>=0) opt[i] = opt[i-j]+A[i]; else opt[i] = A[i]; for(j = 5; j>0; --j){ if(i-j>=0) opt[i] = max(opt[i], opt[i-j]+A[i]); else opt[i] = A[i]; } } return A[0]+opt[A.size()-1]; }
#ifndef DATA_H #define DATA_H #include "../StdIncl.hpp" namespace uipf{ /** The elements of Type declare all possible Type-sorts the data objects can be. For creating a new Type-sort: - add an enum in Type - case: standard class: create a new .hpp and .cpp classes, which derive from the class Data.hpp - case: template class: create a new .hpp template class, which derive from the class Data.hpp */ enum Type { STRING, INTEGER, FLOAT, BOOL, MATRIX, STRING_LIST, INTEGER_LIST, FLOAT_LIST, BOOL_LIST, MATRIX_LIST, }; // returns the string representation of a type std::string type2string(Type t); // Data which represents an arbitrary element // It is a virtual class and cant be instantiated class Data { public: typedef SMARTPOINTER<Data> ptr; typedef const SMARTPOINTER<Data> c_ptr; public: // constructor (can't be virtual!) Data(void){}; // destructor virtual ~Data(void){}; // returns the data type of this data object // this is a virtual method, which has to be overwritten in the class, which derives of Data virtual Type getType() const = 0; }; } // namespace #endif
#include "engine.h" Camera::Camera(int width, int height, Vector *orig, Matrix *orientation, double fov, double near, double far) { this->origin = orig; this->translation = new Matrix(TRANSLATION, -orig->x, -orig->y, -orig->z); this->rotation = orientation; this->view = this->rotation->mult(this->translation); this->projection = new Matrix(PROJECTION, fov, near, far, width / height); this->width = width; this->height = height; } void Camera::watch_vector(Vector *vec) { this->view->transform(vec); this->projection->transform(vec); vec->x = (this->width * (vec->x + 1)) / 2; vec->y = (this->height * (vec->y + 1)) / 2; } void Camera::mod_angles(double th, double ph, double ps) { this->rotation->mod_angles(th, ph, ps); delete this->view; this->view = this->rotation->mult(this->translation); } void Camera::mod_location(double x, double y, double z) { this->translation->mod_location(x, y, z); delete this->view; this->view = this->rotation->mult(this->translation); } Camera::~Camera() { delete this->origin; delete this->translation; delete this->rotation; delete this->projection; delete this->view; }
#include "pch.h" #include "Component.h" #include "GameObject.h" Component::Component() noexcept { printf("creating Component: "); } void Component::SetOwner(GameObject& aOwner) noexcept { m_owner = &aOwner; }
#ifndef _VECTOR_4_H #define _VECTOR_4_H #include "BaseVector4.h" class Vector4 : public BaseVector4 { // constructor and destructor public: Vector4(void); Vector4(float x, float y, float z, float w); ~Vector4(void); // Operator Overloads public: Vector4& operator= (const Vector4& rhs); Vector4 operator+ (const Vector4& rhs) const; Vector4 operator- (const Vector4& rhs) const; Vector4 operator* (const float scalar) const; Vector4& operator+= (const Vector4& rhs); Vector4& operator-= (const Vector4& rhs); Vector4& operator*= (const float scalar); bool operator== (const Vector4& rhs); bool operator!= (const Vector4& rhs); //Accessors public: float X (void) const; float Y (void) const; float Z (void) const; float W (void) const; float& X (void); float& Y (void); float& Z (void); float& W (void); float GetX (void) const; float GetY (void) const; float GetZ (void) const; float GetW (void) const; void SetX (float x); void SetY (float y); void SetZ (float z); void SetW (float w); void SetValues (float x, float y, float z); //Arthemetic method public: void Add (const Vector4& rhs); void Subtract (const Vector4& rhs); void Multiply (const Vector4& rhs); void Multiply (float scalar); void Divide (const Vector4& rhs); float DotProduct (const Vector4& rhs); Vector4 CrossProduct (const Vector4& rhs, const Vector4& rhs2); void Normalize (void); float MagnitudeSquare (void); void Zero (void); //static arthemetic methods public: static void Add (const Vector4& vec1, const Vector4& vec2, Vector4& out); static void Subtract (const Vector4& vec1, const Vector4& vec2, Vector4& out); static void Multiply (const Vector4& vec1, const Vector4& vec2, Vector4& out); static void Multiply (float scalar, Vector4& in, Vector4& out); static void Divide (const Vector4& vec1, const Vector4& vec2, Vector4& out); static float DotProduct (const Vector4& vec1, const Vector4& vec2); static void CrossProduct (const Vector4& vec1, const Vector4& vec2, Vector4& out); static void Normalize (const Vector4& in, Vector4& out); static float MagnitudeSquare (const Vector4& rhs); static void Zero (Vector4& out); static Vector4 Lerp (Vector4& start, Vector4& end, float amount); static void Lerp (Vector4& start, Vector4& end, float amount, Vector4& out); }; #endif
#include<stdio.h> #include<iostream> #include<stdlib.h> using namespace std; int size=0; int error=0; struct node { int data; struct node *left; struct node *right; }*p,*q,*root; const char error_msg[][50] = { "", "BST duuren!", "BST xooson!", }; void insert(int item){ p=(struct node*)malloc(sizeof(struct node)); p->data = item; p->left = NULL; p->right = NULL; if(size==0){ root = p; size++; } else{ size++; q=root; while(1){ if(p->data>q->data){ if(q->right==NULL){ q->right = p; break; }else{ q=q->right; } }else{ if(q->left==NULL){ q->left =p; break; }else{ q=q->left; } } } } } int deletenode(int n){ } int search(int n){ if(size==1){ if(root->data==n){ return 0; }else{ return 1; } }else{ while(1){ if(n>q->data){ if(q->right==NULL){ return 1; }else{ q=q->right; } }else if(n<q->data){ if(q->left==NULL){ return 1; }else{ q=q->left; } }else{ return 0; } } } } //inoreder void print(node *q) { if(q == NULL) return; print(q->left); //Visit left subtree printf("%d ",q->data); //Print data print(q->right); // Visit right subtree } int main(){ int n, i, a,t; while(1){ cout<<"1: insert, 2: delete, 3: search, 4: print, 0: exit\n"; cin>>t; error=0; switch(t){ case 1: cout<<"Oruulah utga: "; cin>>a; insert(a); if(error) cout<<"Aldaa: "<<error_msg[error]; else cout<<a<<" utga orloo\n"; break; case 2: cout<<"Ustgah too: "; cin>>a; deletenode(a); if(error) cout<<"Aldaa: "<<error_msg[error]; else cout<<a<<" utga ustlaa\n"; break; case 3: cout<<"Haih too: "; cin>>a; if(search(a)) cout<<a<<" utga oldsongui\n"; else cout<<a<<" utga oldloo\n"; break; case 4: print(q); break; default: exit(0); } } }
#include<bits/stdc++.h> using namespace std; #define maxn 10005 int dp[maxn][4]; string buf[maxn][4]; string str; int main() { ios::sync_with_stdio(false); cin.tie(0); set<string> res; cin>>str; int len=str.size(); dp[len][2]=1; buf[len][2]=""; for(int i=len-2; i>=5; i--) { string t = str.substr(i, 2); if(dp[i+2][2]&&buf[i+2][2]!=t||dp[i+2][3]) { dp[i][2]=1; buf[i][2]=t; res.insert(t); } t=str.substr(i,3); if(dp[i+3][2]||(dp[i+3][3]&&buf[i+3][3]!=t)) { dp[i][3]=1; buf[i][3]=t; res.insert(t); } } cout<<res.size()<<endl; for(string x:res) { cout<<x<<"\n"; } return 0; }
/* STM32F103C8 Black Pill ( PB12) Serialport set and display RTC clock , Write by CSNOL https://github.com/csnol/STM32-Examples based on https://github.com/rogerclarkmelbourne/Arduino_STM32 1. Blink on PB12 per 1s. 2. change to your timezone in the sketch; . 3. get Unix epoch time from https://www.epochconverter.com/ ; 4. last step input the 10 bits number( example: 1503945555) to Serialport ; 5. the clock will be reset to you wanted. 6. This sketch needs RTClock.h updated ## Why the 10 bits Unix epoch time be used? ****Because I wanna connect to NTP server by ESP-8266. ****in the <NTPClient.h> library. getNtpTime() will return this 10 bits Unix epoch time. */ #include <RTClock.h> RTClock rtclock (RTCSEL_LSE); // initialise time_t tt; tm_t mtt = { 47, 8, 27, 0, 1, 20, 30, 30 }; char weekday1[][7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // 0,1,2,3,4,5,6 uint8_t timeread[11]; int timezone = -7 * 3600; // timezone -8 + DST +1 = -7 CA USA time_t tt1; #define LED_PIN PB12 // This function is called in the attachSecondsInterrpt void blink () { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); tt++; } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); tt = rtclock.makeTime(mtt); tt1 = tt; rtclock.attachSecondsInterrupt(blink);// Call blink } int i = 0; void loop() { while (Serial.available()) { timeread[i] = Serial.read(); if (i < 11) { i++; } else { i = 0; tt = (timeread[0] - '0') * 1000000000 + (timeread[1] - '0') * 100000000 + (timeread[2] - '0') * 10000000 + (timeread[3] - '0') * 1000000 + (timeread[4] - '0') * 100000; tt += (timeread[5] - '0') * 10000 + (timeread[6] - '0') * 1000 + (timeread[7] - '0') * 100 + (timeread[8] - '0') * 10 + (timeread[9] - '0') + timezone; } } if (tt1 != tt) { tt1 = tt; rtclock.breakTime(tt, mtt); Serial.print("Date: "); Serial.print(mtt.day); Serial.print("- "); Serial.print(mtt.month); Serial.print(" "); Serial.print(mtt.year + 1970); Serial.print(" "); Serial.print(weekday1[mtt.weekday]); Serial.print(" Time: "); Serial.print(mtt.hour); Serial.print(" : "); Serial.print(mtt.minute); Serial.print(" : "); Serial.println(mtt.second); } }
#include "lnumber.h" #pragma comment(lib,"winmm.lib") #include<windows.h> #pragma comment(lib,"winmm.lib") void main(void){ string temp; string x1; string x2; int lines = 0; char symbol; cout << "input the operation : + - * /:" << endl; cin >> temp; symbol = temp[0]; cout << "input first number" << endl; cin >> x1; cout << "input second number" << endl; cin >> x2; if (symbol == '+'){ char* a = new char[x1.length()]; char* b = new char[x2.length()]; x1.copy(a, x1.length(), 0); x2.copy(b, x2.length(), 0); lnumber A(a, x1.length(), true); lnumber B(b, x2.length(), true); lnumber C; C = A + B; C.out(); } else if (symbol == '-'){ char* a = new char[x1.length()]; char* b = new char[x2.length()]; x1.copy(a, x1.length(), 0); x2.copy(b, x2.length(), 0); lnumber A(a, x1.length(), true); lnumber B(b, x2.length(), true); lnumber C; C = A - B; C.out(); } else if (symbol == '*'){ int e_l = pow(2, floor(log2(x1.length() + x2.length())) + 1); short *a = new short[e_l]; short *b = new short[e_l]; memset(a, 0, e_l * sizeof(short)); memset(b, 0, e_l * sizeof(short)); int j = x1.length()- 1; for (int i = 0; i < x1.length(); i++){ a[i] = x1[j--] - '0'; } j = x2.length() - 1; for (int i = 0; i < x2.length(); i++){ b[i] = x2[j--] - '0'; } lnumber A(a, x1.length(), e_l, true), B(b, x2.length(), e_l, true), C; A*B; } else if (symbol == '/'){ if (x1.length() < x2.length()){ cout << 0 << endl; cout << x1 << endl; } else{ char *a = new char[x1.length()]; char *b = new char[x1.length() + 1]; memset(b, '0', (x1.length() + 1) * sizeof(char)); x1.copy(a, x1.length(), 0); x2.copy(b, x1.length(), 0); lnumber A(a, x1.length(), true); lnumber B(b, x2.length(), true); lnumber C; C = A / B; C.out(); } } else{ cout << "+ - * / needed"; } /* short *y = new short[600000]; short *x = new short[600000]; int e_l = pow(2, floor(log2(1200000)) + 1); for (int i = 0; i < 600000; i++){ x[i] = i % 10; y[i] = i % 10; } */ /* short* x = new short[8]; short* y = new short[8]; short* x1 = new short[4]; short* x2 = new short[4]; complex* X1 = new complex[4]; x[0] = 8; x[1] = 7; x[2] = 6; x[3] = 0; x[4] = 0; x[5] = 0; x[6] = 0; x[7] = 0; y[0] = 2; y[1] = 3; y[2] = 4; y[3] = 0; y[4] = 0; y[5] = 0; y[6] = 0; y[7] = 0; complex* f1; complex* f2; complex* result; int e_length; e_length = pow(2, floor(log2(3 + 3)) + 1); f1 = FFT(x, 8, 8, x1); f2 = FFT(y, 8, 8, x1); complex* f = new complex[e_length]; for (int k = 0; k < e_length; k++){ f[k].r = f1[k].r * f2[k].r - f1[k].i * f2[k].i; f[k].i = f1[k].r * f2[k].i + f1[k].i * f2[k].r; } for (int i = 0; i < 8; i++) cout << f1[i].r << ' ' << f1[i].i << endl; result = REVERSE_FFT(f, e_length, e_length, X1); for (int i = 0; i < 8; i++) cout << result[i].r << ' ' << result[i].i << endl; */ // a[0] = 8; // a[1] = 8; //a[2] = 8; //a[3] = 4; //a[4] = 1; //a[5] = 0; //a[6] = '0'; //a[7] = '2'; // b[0] = 2; // b[1] = 0; // b[2] = 0; // b[3] = 0; // b[4] = 0; // b[5] = 0; // b[6] = 0; // b[7] = 0; // b[4] = 0; // b[5] = '0'; // b[6] = '2'; // b[7] = '4'; // c[0] = '3'; // c[1] = '2'; // cout << a[0] << a[1] << a[2]; /* char a[1]; char b[1]; char c[1]; a[0] = '1'; b[0] = '2'; c[0] = '4'; */ //char *s = new char[3]; // memset(a, '1', 60000); // memset(b, '1', 120002); // memset(b, '6', 2); // memset(b, 2, 3); /* for (int i = 0; i < 60000; i++) a[i] = 1; for (int i = 0; i < 120001; i++) b[i] = 0; for (int i = 0; i < 60000; i++) b[i] = 1; */ // cout << a[0] << a[1] << a[2]; // cout << b[0] << b[1]; /* lnumber *A = new lnumber(a, 8, true); lnumber *B = new lnumber(b, 8, true); lnumber *C = new lnumber(a, 2, true); */ /* lnumber A(x, 600000, e_l, true), B(y, 600000, e_l, true), C; DWORD t1, t2; t1 = timeGetTime(); A*B; t2 = timeGetTime(); cout << endl << (t2 - t1)*1.0 / 1000 << endl; */ /* lnumber A(a, 60000, true); lnumber B(b, 60000, true); lnumber C; DWORD t1, t2; t1 = timeGetTime(); A*B; t2 = timeGetTime(); cout << endl << (t2 - t1)*1.0 / 1000 << endl; //A = *A - *C; //A->out();*/ system("Pause"); }
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int n, x; set<int> s; int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> x; //s<T>.lower_bound(x) 返回第一个大于或等于x的数的迭代器 //set<int>::iterator it = s.lower_bound(x); auto it = s.lower_bound(x); if (it == s.end()) { s.insert(x); } else { s.erase(it); s.insert(x); } } cout << s.size() << endl; return 0; }
// // main.cpp // Tarea4Ejercicio1 // // Created by Daniel on 15/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include <iostream> #include "Pila.h" int main(int argc, const char * argv[]) { std::string expresion; std::cout<<"Inserte la expresión: "; std::cin>>expresion; Pila<char> * exp = new Pila<char>; for (int i = 0; i < expresion.length(); ++i) { exp->push(expresion[i]); } int cont = 0; for (int j = 0; j <expresion.length();++j){ char c = exp->pop()->getInfo(); if (cont < 0){ break; } else if (c == ')') { ++cont; } else if(c == '('){ --cont; } } if (cont == 0){ std::cout<<"La expresion está balanceada"<<std::endl; } else{ std::cout<<"La expresión no está balanceada"<<std::endl; } delete exp; return 0; }
void code_dir(){ std::fstream f("D:\\DS project\\station.txt", std::ios_base::in); char temp[50]; int var; cout << " ------------------------------- "<<'\n'; cout << " Station Code "<<'\n'; cout << " ------------------------------- "<<'\n'; for(int i =0; i < V; i++) { f >> temp; cout << " " << temp; int cap; cap = strlen(temp); for(int j = 0; j < 27-cap; j++) { cout << " "; } f >> var; cout << var; cout << "\n"; } }
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> void calculate_the_maximum(int n, int k) { int i,j,add,orr,xorr; for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { add=i&j; orr=i|j; xorr=i^j; } } for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { printf("%d\t%d\t%d",add,orr,xorr); } printf("\n"); } } int main() { int n, k,i,j,add,orr,xorr; scanf("%d %d", &n, &k); calculate_the_maximum(n, k); return 0; }
//Phoenix_RK //https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ /* Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true] */ class Solution { public: vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) { int great=*max_element(candies.begin(),candies.end()); vector<bool> possible; for(auto it=candies.begin();it!=candies.end();it++) { if(*it+extraCandies<great) possible.push_back(false); else possible.push_back(true); } return possible; } };
#include<bits/stdc++.h> using namespace std; double force(double arr[], double i, int n){ // total force at a given point double x=0; for(int j=0;j<n;j++) x += (1/double(i-arr[j])); return x; } int main() { // only gravity will pull me down // Magnet Array Problem int t, n, flg; cin >> t; while (t--) { cin >> n; double m[n]; for(auto &x: m) cin >> x; cout << fixed << setprecision(2); for(int i=1; i<n; i++) { double lo=m[i-1], hi=m[i], mid; while(lo<hi) { // binary search to find a point with zero resultant force mid=(lo+hi)/2; double x=force(m,mid,n); flg=0; if(abs(x)<1e-9) { cout << mid << " "; flg=1; break; } else if(x>0) lo=mid; else hi=mid; } if(!flg) cout << lo << " "; } cout << endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _STYLE_MANAGER_ #define _STYLE_MANAGER_ #include "modules/util/simset.h" #include "modules/display/style.h" #include "modules/logdoc/html.h" #include "modules/display/fontdb.h" #include "modules/pi/OpFont.h" #include "modules/display/webfont_manager.h" #include "modules/prefs/prefsmanager/opprefslistener.h" #include "modules/style/css_media.h" //#define STYLE_EX_FORM_TEXT 0 #define STYLE_EX_FORM_TEXTAREA 1 #define STYLE_EX_FORM_SELECT 2 #define STYLE_EX_FORM_BUTTON 3 #define STYLE_EX_FORM_TEXTINPUT 4 #define STYLE_MAIL_BODY 5 #define STYLE_EX_SIZE 6 #define NUMBER_OF_STYLES Markup::HTE_FIRST_SPECIAL #ifdef FONTSWITCHING /** * Used by the font switching algorithm as the block number of the * block for characters that don't seem to belong to any existing * block. */ #define UNKNOWN_BLOCK_NUMBER 128 /** * Used by the font switching algorithm to select fonts that match * the original when switching. */ enum FontPitch { UnknownPitch, FixedPitch, VariablePitch }; #endif // FONTSWITCHING class FontFaceElm; class HLDocProfile; /** StyleManager keeps tracks of Opera's styles and does fontswitching. Fonts: It owns an OpFontManager and an OpFontDatabase. The OpFontDatabase is initialized with the fonts from the OpFontManager. StyleManager has settings for the CSS generic fonts: serif, sans-serif, cursive, fantasy and monospace. The OpFontManager is queried for these. */ class StyleManager : public OpPrefsListener { public: struct UnicodeBlock { unsigned char block_number; uni_char lowest; uni_char highest; }; struct UnicodePointBlock { unsigned char block_number; UnicodePoint block_lowest; UnicodePoint block_highest; }; enum GenericFont { SERIF, SANS_SERIF, FANTASY, CURSIVE, MONOSPACE, UNKNOWN }; /** Returns the generic font type of base. */ static GenericFont GetGenericFontType(const OpFontInfo* base); /** Returns the GenericFont mapping to name, which should be one of "serif", "sans-serif", "fantasy", "cursive", "monospace". */ static GenericFont GetGenericFont(const uni_char* name); /** Returns the StyleManager::GenericFont mapping to the GenericFont declared in modules/pi/OpFont.h. */ static GenericFont GetGenericFont(::GenericFont font); private: StyleManager(); /** Second phase constructor. You must call this method prior to using the StyleManager object, unless it was created using the Create() method. @return OP_STATUS Status of the construction, always check this. */ OP_STATUS Construct(); Style* style[NUMBER_OF_STYLES]; Style* style_ex[STYLE_EX_SIZE]; void DeleteFontFaceList(); short FindFallback(GenericFont id); #ifdef FONTSWITCHING #ifndef PLATFORM_FONTSWITCHING /** used from font switching code: fetches number of fonts to iterate over */ UINT32 GetTotalFontCount(); /** Used from font switching code: returns the next font alphabetically, or NULL if font should not be a candidate for font switching. */ OpFontInfo* NextFontAlphabetical(UINT32 i); #endif // !PLATFORM_FONTSWITCHING UINT8* block_table; UnicodePointBlock* block_table_internal; UINT16 block_table_internal_count; BOOL block_table_present; void BuildOptimizedBlockTable(); void ReadUnicodeBlockLowestHighest(int table_index, UnicodePointBlock &block); #endif // FONTSWITCHING OpFontManager* fontManager; OpFontDatabase* fontDatabase; short generic_font_numbers[WritingSystem::NumScripts][UNKNOWN]; UINT32 fonts_in_hash; OpGenericStringHashTable fontface_hash; short* m_alphabetical_font_list; int m_ahem_font_number; Head preferredFonts; WritingSystem::Script locale_script; public: ~StyleManager(); /** Static method for OOM safe creation of the StyleManager. @return StyleManager* The created object if successful and NULL otherwise. */ static StyleManager* Create(); void BuildAlphabeticalList(); void InitFontFaceList(); OpFontInfo* GetFontInfo(int font_number); OpFontManager* GetFontManager() { return fontManager; } #ifdef _GLYPHTESTING_SUPPORT_ /** some scripts available as language codes do not exist in the OS/2 table. for these, we need to check the glyph support in the fonts. @param fontinfo The fontinfo to scan for glyphs to determine the writing system. */ void SetupFontScriptsFromGlyphs(OpFontInfo* fontinfo); #endif // _GLYPHTESTING_SUPPORT_ Style* GetStyle(HTML_ElementType helm) const; OP_STATUS SetStyle(HTML_ElementType helm, Style *s); Style* GetStyleEx(int id) const; void SetStyleEx(int id, Style *s); int GetFontSize(const FontAtt* font, BYTE fsize) const; int GetNextFontSize(const FontAtt* font, int current_size, BOOL smaller) const; short GetFontNumber(const uni_char* fontface); const uni_char* GetFontFace(int font_number); BOOL HasFont(int font_number); int GetNextFontWeight(int weight, BOOL bolder); /** Sets up a mapping between a generic font name and a specific, e.g. monospace -> Courier. @param generic_name the generic name to define for, one of monospace, fantasy, serif, sans-serif, cursive @param font_name the actual font name */ #ifdef PERSCRIPT_GENERIC_FONT void InitGenericFont(GenericFont id); void SetGenericFont(GenericFont id, const uni_char* font_name, WritingSystem::Script script = WritingSystem::NumScripts); #else // PERSCRIPT_GENERIC_FONT void SetGenericFont(GenericFont id, const uni_char* font_name); #endif // PERSCRIPT_GENERIC_FONT void SetGenericFont(GenericFont id, short font_number, WritingSystem::Script script); short GetGenericFontNumber(const uni_char* fontface, WritingSystem::Script script) const; short GetGenericFontNumber(GenericFont id, WritingSystem::Script script) const; #ifdef FONTSWITCHING /** finds the font stylewise closest to specified_font that claims support for script */ OpFontInfo* GetFontSupportingScript(OpFontInfo* specified_font, WritingSystem::Script script, BOOL force = FALSE); OpFontInfo* GetFontForScript(OpFontInfo* default_font, WritingSystem::Script script, BOOL force_fontswitch = FALSE); #endif // FONTSWITCHING OP_STATUS CreateFontNumber(const uni_char* family, int& fontnumber); void ReleaseFontNumber(int fontnumber); /** Returns a fontnumber to use for the given font-family and media-type. This takes into account webfonts, and should be used instead of GetOrCreateFontNumber when entering values into the cascade. @param hld_profile The HLDocProfile corresponding to the cascade @param font_family The font-family name to resolve @param media_type The media-type corresponding to the cascade (see CSS_MediaType) @param set_timestamp Controls if webfonts should be timestamped. Text using a timestamped webfont will not be displayed until the webfont is loaded successfully or the timestamp expires. An expired timestamp causes the text to be displayed with a fallback font until the webfont finishes loading, at which point the text will be redrawn using the webfont. A webfont will only get timestamped once to ensure that the timestamp doesn't drift as new text using the font is encountered. Text using a webfont that has not been timestamped will not be suppressed. It will be shown directly with the fallback font if the webfont has not been loaded. @return The fontnumber to use, -1 if no matching font was found (which should mean continue to use whatever the current font is), or -2 to suppress display of text while waiting for a webfont to load or expire. */ short LookupFontNumber(HLDocProfile* hld_profile, const uni_char* font_family, CSS_MediaType media_type, BOOL set_timestamp = FALSE); OP_STATUS AddWebFontInfo(OpFontInfo* fi); OP_STATUS RemoveWebFontInfo(OpFontInfo* fi); OP_STATUS DeleteWebFontInfo(OpFontInfo* fi, BOOL release_fontnumber = TRUE); /** If this font_number corresponds to one of the fonts installed on the platform */ BOOL IsSystemFont(unsigned int font_number) { return font_number < fontDatabase->GetNumSystemFonts(); } #ifdef FONTSWITCHING short GetBestFont(const uni_char* str, int len, short font_number, const WritingSystem::Script script); OP_STATUS SetPreferredFontForScript(UINT8 block_nr, BOOL monospace, const uni_char* font_name, BOOL replace = TRUE); OP_STATUS SetPreferredFont(UINT8 block_nr, BOOL monospace, const uni_char* font_name, const WritingSystem::Script script, BOOL replace = TRUE); /** Get the preferred font. @param block_nr the block number @monospace monospace or not @return the font that was set to be preferred */ OpFontInfo* GetPreferredFont(UINT8 block_nr, BOOL monospace, const WritingSystem::Script script); /** Check if codepage is relevant (and should play a role in fontswitching) for the given block. @return whether we have to look at the codepage to get the best font possible */ BOOL DEPRECATED(IsCodepageRelevant(UINT8 block_nr)); #ifndef PLATFORM_FONTSWITCHING /** Use the call below. */ inline OpFontInfo DEPRECATED(*GetRecommendedAlternativeFont(const OpFontInfo* specified_font, int block, OpFontInfo::CodePage preferred_codepage = OpFontInfo::OP_DEFAULT_CODEPAGE, BOOL use_preferred = TRUE)); /** This function can be called if specified_font didn't have the block or character you need. It will look through the available fonts and return the font that is as similar as possible to specified_font. If a font has the same properties (monospace/serifs/etc.) as the specified_font it will score a higher point and the probability is higher that it is the choosen font. If a font is preferred for the given codepage, it will also get a higher point. If FEATURE_GLYPHTESTING is supported and uc is not 0, the font will also be tested if it really contains the character and then get a much higher point. Can return NULL if no good font where found. */ OpFontInfo DEPRECATED(*GetRecommendedAlternativeFont(const OpFontInfo* specified_font, int block, OpFontInfo::CodePage preferred_codepage = OpFontInfo::OP_DEFAULT_CODEPAGE, const uni_char uc = (uni_char)0, BOOL use_preferred = TRUE)); OpFontInfo* GetRecommendedAlternativeFont(const OpFontInfo* specified_font, int block, WritingSystem::Script script = WritingSystem::Unknown, const UnicodePoint uc = (UnicodePoint)0, BOOL use_preferred = TRUE); #endif // !PLATFORM_FONTSWITCHING /** This method can be used to find out which Unicode block a character belongs to, and also what its boundaries are. */ void GetUnicodeBlockInfo(UnicodePoint ch, int &block_no, UnicodePoint &block_lowest, UnicodePoint &block_highest); void DEPRECATED(GetUnicodeBlockInfo(UnicodePoint ch, int &block_no, int &block_lowest, int &block_highest)); #ifdef _GLYPHTESTING_SUPPORT_ /** Return FALSE for characters that should never ever be displayed. F.ex newline, tab, NULL... */ BOOL ShouldHaveGlyph(UnicodePoint uc); #endif // _GLYPHTESTING_SUPPORT_ /** * Determine if this is a whitespace character that we should try to fontswitch, or if we should just * determine the width of the space ourselves. * * @param ch The unicode point * @return TRUE if there is no reason to try to fontswitch this whitespace */ static inline BOOL NoFontswitchNoncollapsingWhitespace(UnicodePoint ch) { return ch >= 0x2000 && ch <= 0x200a || ch == 0x202f; } #else // FONTSWITCHING short GetBestFont(const uni_char* str, int length, short font_number, const WritingSystem::Script) { return font_number; } #endif // FONTSWITCHING void OnPrefsInitL(); // OpPrefsListener interface: /** Signals a change in an integer preference. */ void PrefChanged(enum OpPrefsCollection::Collections id, int pref, int newvalue); /** Signals a change in a string preference. */ void PrefChanged(enum OpPrefsCollection::Collections id, int pref, const OpStringC &newvalue); #ifdef PREFS_HOSTOVERRIDE /** Signals the addition, change or removal of a host override. */ void HostOverrideChanged(enum OpPrefsCollection::Collections id, const uni_char *hostname); #endif /** Get the script the block belongs, but doesn't cover Han blocks */ static WritingSystem::Script ScriptForBlock(UINT8 block_nr); }; /** Representation of a font that is preferred for a certain unicode block (see http://www.unicode.org/charts/). */ class PreferredFont : public Link { public: PreferredFont(UINT8 block_nr, const WritingSystem::Script script) : block_nr(block_nr), font_info(NULL), monospace_font_info(NULL), script(script) { } UINT8 block_nr; OpFontInfo* font_info; OpFontInfo* monospace_font_info; WritingSystem::Script script; }; #ifdef FONTSWITCHING inline void StyleManager::GetUnicodeBlockInfo(UnicodePoint ch, int &block_no, int &block_lowest, int &block_highest) { UnicodePoint bl, bh; GetUnicodeBlockInfo(ch, block_no, bl, bh); block_lowest = bl; block_highest = bh; }; #endif // FONTSWITCHING #ifndef _NO_GLOBALS_ extern StyleManager* styleManager; #endif #endif /* _STYLE_MANAGER_ */
#include <iostream> #include "vector.hpp" void isValue(int& number) { while (std::cin.fail()) { std::cin.clear(); std::cin.ignore(256,'\n'); std::cout << "Please enter the intager number: "; std::cin >> number; } } void chooseFunction(const int function, Vector& vector) { int index = 0; int value = 0; switch (function) { case 1 : std::cout << "Enter the index: "; std::cin >> index; isValue(index); std::cout << "Enter the value: "; std::cin >> value; isValue(value); vector.insert(index, value); vector.printVector(); break; case 2 : std::cout << "Enter the value: "; std::cin >> value; isValue(value); vector.push_back(value); vector.printVector(); break; case 3: std::cout << "Enter the index: "; std::cin >> index; isValue(index); vector.erase(index); vector.printVector(); break; case 4 : vector.pop_back(); vector.printVector(); break; case 5 : std::cout << "Size of vector is " << vector.size() << std::endl; break; default : std::cout << "Invalid function choose!" << std::endl; break; } } int main() { Vector vector; int function = 0; do { std::cout << "=====Functions=====\n" << std::endl; std::cout << "1. insert(index, value)\n2. push_back()\n3. erase(index)\n4. pop_back()\n5. size()\n"; std::cout << "Enter 0 for exit or Choose the function: "; std::cin >> function; if (0 == function) { return 0; } isValue(function); chooseFunction(function, vector); } while (0 != function); return 0; }
#include<iostream> using namespace std; int main() { int k,t, i = 0; cin>>k; while(cin>>t) { if(k != i ) cout<<t<<" "; i++; } return 0; }
#include "kg/util/log.hh" #include <Windows.h> kg::log::~log() { _stream << "\r\n"; std::string s = _stream.str(); wchar_t * buf = new wchar_t[s.length() + 1] { 0 }; mbstowcs_s(nullptr, buf, s.length(), s.c_str(), _TRUNCATE); OutputDebugStringW(buf); delete[] buf; }
#include <iostream> using namespace std; int main() { int x; int kapinajums; cout << "Ievadi skaitli kuru gribi kapinat kvadrata" << endl; cin >> x; if(x > 0){ //Sis izpildisies ja x ir lielaks par 0 cout << "X ir lielaks par 0" << endl; kapinajums = x*x; cout << "Tavs skaitlis " << x << " kapinats kvadrata ir " << kapinajums<< endl; }else{ //Sis izpildisies ja x nebus lielaks par 0 cout << "X ir mazaks vai vienads ar 0"<< endl; } return 0; }
#include "shoot.h" Motor_C610 Turnplate[1] = {Motor_C610(1)}; Motor_C620 FriMotor[3] = {Motor_C620(3),Motor_C620(4),Motor_C620(1)}; void C_Shoot :: Control(E_ShootMode shoot_mode, E_ShootCtrlMode ctrl_mode, E_FriWheelState fri_wheel_stste, E_LaserState laser_state, E_BulletBayState bullet_bay_state, E_FireFlag fire_flag, uint8_t max_speed, uint16_t cooling_rate, uint16_t cooling_limit, uint16_t shooter_heat) { shootMode = shoot_mode; fireFlag = fire_flag; ctrlMode = ctrl_mode; friWheelState = fri_wheel_stste; laserState = laser_state; bulletBayState = bullet_bay_state; laserCtrl(); friWheelCtrl(); bulletBayCtrl(); heatCalc(); shootCtrl(); MotorMsgSend(&hcan1,FriMotor); } void C_Shoot :: heatCalc() { if(bulletSpeed!=lastBulletSpeed) { index++; heat+=10; } if(heatRf-heat>9) { heat+=10; } heat-= coolingRate/1000.0; if(heat<0) { heat = 0; } lastBulletSpeed = bulletSpeed; } void C_Shoot :: shootCtrl() { if(fireFlag == STOP_F) { delayCnt = 0; } if(friWheelState == OPEN_F && fireFlag == FIRE_F && fireFlag2 == FIRE_F) { switch(shootMode) { case RUN: if(abs(turnPlateAngle.Current-turnPlateAngle.Target)>360*3.6*1.8) //卡弹1.8倍就回拨 { turnPlateAngle.Target += 360*3.6*2; } else if(delayCnt == 0 && ((heat<heatLimit - 30)||heatLimit == -1)) //调试时关闭热量限制 25 //if(delayCnt == 0 ) { turnPlateAngle.Target -= 360*3.6; } delayCnt++; delayCnt%=period; break; } } turnPlateAngle.Current = FriMotor[2].getAngle(); turnPlateSpeed.Target = turnPlateAngle.Adjust(); turnPlateSpeed.Current = FriMotor[2].getSpeed(); FriMotor[2].Out = turnPlateSpeed.Adjust(); } void C_Shoot :: friWheelCtrl() { switch(friWheelState) { case OPEN_F: switch(maxSpeed) { case -1: leftFriSpeed.Target = friSpeed_30; rightFriSpeed.Target = -friSpeed_30; break; case 15: leftFriSpeed.Target = friSpeed_15; rightFriSpeed.Target = -friSpeed_15; break; case 18: leftFriSpeed.Target = friSpeed_18; rightFriSpeed.Target = -friSpeed_18; break; case 30: leftFriSpeed.Target = friSpeed_30; rightFriSpeed.Target = -friSpeed_30; break; } if(friWheelDelay<1000) { friWheelDelay++; } else { fireFlag2 = FIRE_F; } break; case CLOSE_F: leftFriSpeed.Target = 0; rightFriSpeed.Target = 0; friWheelDelay = 0; fireFlag2 = STOP_F; break; } leftFriSpeed.Current = FriMotor[0].getSpeed(); rightFriSpeed.Current = FriMotor[1].getSpeed(); FriMotor[0].Out = leftFriSpeed.Adjust(); FriMotor[1].Out = rightFriSpeed.Adjust(); } void C_Shoot :: laserCtrl() { switch(laserState) { case OPEN_L: HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_SET); break; case CLOSE_L: HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET); break; } } void C_Shoot :: bulletBayCtrl() { if(bulletBayDelay == 0) { switch(bulletBayState) { case OPEN_B: __HAL_TIM_SetCompare(&htim2,TIM_CHANNEL_2,1900); Pitch_Yaw.pitchAngle.Target = 6200; break; case CLOSE_B: __HAL_TIM_SetCompare(&htim2,TIM_CHANNEL_2,500); break; } } bulletBayDelay++; bulletBayDelay%=500; } void C_Shoot :: pid_init(E_ShootPidType type,float kp,float ki,float kd, float ki_max,float out_max) { switch(type) { case LEFT_FRI_SPEED: leftFriSpeed.SetPIDParam(kp, ki, kd, ki_max, out_max); break; case RIGHT_FRI_SPEED: rightFriSpeed.SetPIDParam(kp, ki, kd, ki_max, out_max); break; case TURNPLATE_SPEED: turnPlateSpeed.SetPIDParam(kp, ki, kd, ki_max, out_max); break; case TURNPLATE_ANGLE: turnPlateAngle.SetPIDParam(kp, ki, kd, ki_max, out_max); } } void C_Shoot :: Reset() { FriMotor[0].Out = FriMotor[1].Out = FriMotor[2].Out = 0; MotorMsgSend(&hcan1,FriMotor); } float C_Shoot :: abs(float x) { if(x>0) return x; else return -x; }
#include <iostream> class B { public: virtual void f() { std::cout << "B "; } }; class D : public B { public: virtual void f() { std::cout << "D "; } }; int main() { B b; D d; B &rb = d; // q1: what is the object slicing problem? B &pb = b; rb.f(); // q2: What is the output of b.f() and why is this output produced? pb.f(); // q3: What is the output of pb.f() and why is this output produced? } // q4: How can we correct this code to prevent the object slicing problem?
#include <iostream> using namespace std; int main() { int n, k, idx = 0, lsc = 0, acount = 0, bcount = 0, ans = 0; //lsc = left most char string s; cin >> n >> k >> s; while (idx < n) { if (s[idx] == 'a') acount++; else bcount++; if (acount <= k || bcount <= k) ans++, idx++; else { if (s[lsc] == 'a') acount--; else bcount--; lsc++, idx++; } } cout << ans << endl; }
#include<bits/stdc++.h> using namespace std; bool subsetSum(int arr[],int n,int sum) { int dp[n+1][sum+1]; for(int i=0;i<n+1;i++) { for(int j=0;j<sum+1;j++) { if(i==0) dp[i][j] = false; if(j==0) dp[i][j] = true; } } for(int i=1;i<n+1;i++) { for(int j=1;j<sum+1;j++) { if(arr[i-1] <= sum) { dp[i][j] = dp[i-1][j-arr[i-1]] || dp[i-1][j]; } else { dp[i][j] = dp[i-1][j]; } } } return dp[n][sum]; } int main() { int n; cout<<"Enter number of elements: "<<endl; cin>>n; int arr[n]; cout<<"Enter elements: "<<endl; for(int i=0;i<n;i++) { cin>>arr[i]; } int sum; cout<<"enter sum:" cin>>sum; bool isPresent = subsetSum(arr,n,sum); if(isPresent) cout<<"There is subset available in the given array"; else cout<<"No such subset present"; }
#include "../include/houghCirclesContrast.h" houghCirclesContrast::houghCirclesContrast(double param1, double param2, double minDist, int minRadius, int maxRadius) { this->param1 = param1; //thresh canny this->param2 = param2; //thresh acumulador this->minDist = minDist; //min distance between balls this->minRadius = minRadius; // min ball radius this->maxRadius = maxRadius; // max ball radius this->dp = 1.0; } std::vector<cv::Vec3f> houghCirclesContrast::run(cv::Mat frame, std::vector<cv::Vec3f> circles) { /* dp – Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height. minDist – Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed. param1 – First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller). param2 – Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first. minRadius – Minimum circle radius. maxRadius – Maximum circle radius. */ //std::vector<cv::Vec3f> circles; cv::Mat gray; // resize cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY); //cv::imshow("gray", gray); cv::HoughCircles( gray, circles, CV_HOUGH_GRADIENT, dp, minDist, param1, param2, minRadius, maxRadius ); return circles; }
/******************************************************************** created: 2008/05/24 created: 24:5:2008 13:14 filename: /rpc/rpc.hpp author: Содм purpose: A simple rpc implementation. Copyright (C) 2008 , all rights reserved. *********************************************************************/ #pragma once #pragma warning(push) #pragma warning(disable:4290) #pragma warning(disable:4996) #include "rpc_peer.hpp" #pragma warning(pop)
#pragma once #include "TerrainTextureCombineDialog.h" // CTerrainDialog 对话框 class CTerrainDialog : public CDialog { DECLARE_DYNCREATE(CTerrainDialog) public: CTerrainDialog(CWnd* pParent = NULL); // 标准构造函数 virtual ~CTerrainDialog(); // 对话框数据 enum { IDD = IDD_TERRAIN }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 BOOL OnInitDialog(); CTerrainTextureCombineDialog mTextureCombinDialog; DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedModify(); afx_msg void OnBnClickedPaint(); afx_msg void OnBnClickedLayerTextureBtn(); afx_msg void OnBnClickedLight(); };
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 1e6 + 10; int a[maxn],b[maxn],nxt[maxn]; int main() { int t,n,m,p,ca = 0; scanf("%d",&t); while (t--) { scanf("%d%d%d",&n,&m,&p); for (int i = 1;i <= n; i++) scanf("%d",&a[i]); for (int i = 1;i <= m; i++) scanf("%d",&b[i]);b[m+1] = 0; memset(nxt,0,sizeof(nxt)); nxt[0] = -1;nxt[1] = 0; for (int i = 2;i <= m; i++) { int j = nxt[i-1]; while (j >= 0 && b[j+1] != b[i]) j = nxt[j]; nxt[i] = j+1; } int ans = 0; for (int s = 1;s <= p; s++) { int j = 0; for (int i = s;i <= n; i += p) { while (j >= 0 && b[j+1] != a[i]) j = nxt[j]; j++; if (j == m) ans++; } } printf("Case #%d: %d\n",++ca,ans); } return 0; }
#include <bits/stdc++.h> #define REP(i, a, b) for(int i = (int)a; i < (int)b; i++) #define fastio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) #define pb push_back #define mp make_pair #define st first #define nd second #define vi vector<int> #define ii pair<int, int> #define ll long long int #define MAX 200010 #define MOD 1000000007 #define oo 0x7fffffff #define endl '\n' using namespace std; char solve(string s){ set<char> v = {'a', 'e', 'i', 'o', 'u'}; string a; REP(i, 0, s.size()){ if(v.find(s[i]) != v.end()) a += s[i]; } string r; REP(i, 0, a.size()){ r += a[i]; } int t = r.size(); REP(i, 0, t/2){ swap(r[i], r[t-i-1]); } if(r.compare(a) == 0) return 'S'; return 'N'; } int main() { fastio; string s; getline(cin, s); cout << solve(s) << endl; return 0; }
// Copyright 2011 Yandex #include <gtest/gtest.h> #include <vector> #include "ltr/crossvalidation/crossvalidation.h" #include "ltr/learners/best_feature_learner/best_feature_learner.h" #include "ltr/data/object.h" #include "ltr/data/feature_info.h" #include "ltr/measures/abs_error.h" #include "ltr/measures/measure.h" #include "ltr/crossvalidation/leave_one_out_splitter.h" #include "ltr/crossvalidation/validation_result.h" #include "ltr/scorers/fake_scorer.h" using std::vector; using ltr::FeatureInfo; using ltr::Object; using ltr::AbsError; using ltr::BestFeatureLearner; using ltr::cv::LeaveOneOutSplitter; using ltr::cv::Validate; using ltr::cv::ValidationResult; using ltr::FakeScorer; using ltr::PointwiseMeasure; const int data_length = 11; const FeatureInfo feature_info(1); TEST(CrossvalidationTest, SimpleCrossvalidationTest) { DataSet<Object> data(feature_info); for (int object_index = 0; object_index < data_length; ++object_index) { Object object; object << 1; data.add(object); } FakeScorer::Ptr fake_scorer(new FakeScorer()); fake_scorer->predict(data); AbsError::Ptr abs_measure_error(new AbsError); BestFeatureLearner<Object>::Ptr best_feature_learner( new BestFeatureLearner<Object>(abs_measure_error)); vector<PointwiseMeasure::Ptr> abs_measure_vector; abs_measure_vector.push_back(abs_measure_error); LeaveOneOutSplitter<Object>::Ptr loo_splitter(new LeaveOneOutSplitter<Object>); ValidationResult vr = Validate(data, abs_measure_vector, best_feature_learner, loo_splitter); EXPECT_EQ(data_length, vr.getSplitCount()); EXPECT_EQ(1, vr.getMeasureValues(0).size()); EXPECT_EQ(1, vr.getMeasureNames().size()); EXPECT_EQ(abs_measure_error->alias(), vr.getMeasureNames().at(0)); for (int split = 0; split < (int)vr.getSplitCount(); ++split) { Object test_obj; test_obj << 1; EXPECT_EQ(1, vr.getScorer(split)->score(test_obj)); EXPECT_EQ(0, vr.getMeasureValues(split).at(0)); } };
#ifndef CFBOARD_HPP #define CFBOARD_HPP #include <iostream> enum GameState {X_WON, O_WON, DRAW, UNFINISHED}; //Declaring enum type class CFBoard //CFBoard class declaration { private: char board[6][7]; GameState gameState; public: CFBoard(){ //default constructor std::cout << "1234567" << std::endl; for(int row = 0; row < 6; row++) //Initializing array of board { for(int col = 0; col < 7; col++) { board[row][col] = '.'; } } gameState = UNFINISHED; //Initializing gameState } bool makeMove(int, char); //makeMove funtion prototype and return bool value void updateGameState(int, int); //updateGameState prototype GameState getGameState(); // void print(); }; #endif
#include "civilian.h" #include <iostream> Civilian::Civilian() { xdir=-5; //moves left ydir=0; //doesnt move up or down image.load("civilian.png"); rect=image.rect(); //assigns image to object resetState(); //respawn } Civilian::~Civilian() { std::cout<<("Civilian deleted\n"); } void Civilian::resetState() { rect.moveTo(400,300); //respawn location } QRect Civilian::getRect() { return rect; } QImage & Civilian::getImage() { return image; } void Civilian::autoMove() { rect.translate(xdir, ydir); if ((rect.left() <= 0) || (rect.right() <= 0)){ //if object moves to edge of screen or off screen xdir = 5; image.load("civilian2.png"); //change image to simulate other civilians rect.moveTo(10,20); //move and move in other direction } if ((rect.right() >= 1200) || (rect.left() >= 1200)) { //if object moves to edge of screen or off screen xdir = -5; image.load("civilian.png"); //change image again rect.moveTo(1100,700); } } void Civilian::setXDir(int x) { xdir = x; } void Civilian::setYDir(int y) { ydir = y; } int Civilian::getXDir() { return xdir; } int Civilian::getYDir() { return ydir; }
#include "texture.h" #include "..\\core\filesystem.h" Texture::~Texture() { Texture::Destroy(); } bool Texture::Create(const Name& image_name) { bool start_success = true; texture_ = IMG_LoadTexture(renderer_->GetSDLRenderer(), image_name.c_str()); return start_success; } bool Texture::CreateFromFont(Font* font, const char* string, const color& font_color) { SDL_Color color; color.r = static_cast<Uint8>(font_color.r); color.g = static_cast<Uint8>(font_color.g); color.b = static_cast<Uint8>(font_color.b); color.a = 255; SDL_Surface* surface = TTF_RenderText_Solid(font->font_, string, color); ASSERT(surface); texture_ = SDL_CreateTextureFromSurface(renderer_->GetSDLRenderer(), surface); SDL_FreeSurface(surface); return (texture_ != nullptr); } void Texture::Destroy() { if (texture_) { SDL_DestroyTexture(texture_); texture_ = nullptr; } } void Texture::Draw(const vector2& position, float angle, const vector2& scale, const vector2& origin) { vector2 size = GetSize(); size = size * scale; vector2 screen_position = position - (size * origin); SDL_Rect dest; dest.x = static_cast<int>(screen_position.x); dest.y = static_cast<int>(screen_position.y); dest.w = static_cast<int>(size.x); dest.h = static_cast<int>(size.y); vector2 rotation_point = size * origin; SDL_Point pivot = { static_cast<int>(rotation_point.x), static_cast<int>(rotation_point.y) }; SDL_RenderCopyEx(renderer_->GetSDLRenderer(), texture_, NULL, &dest, angle, &pivot, SDL_FLIP_NONE); } void Texture::Draw(SDL_Rect& rect, const vector2& position, float angle, const vector2& scale, const vector2& origin) { vector2 size = GetSize(); size = size * scale; vector2 screen_position = position - (size * origin); SDL_Rect dest; dest.x = static_cast<int>(screen_position.x); dest.y = static_cast<int>(screen_position.y); dest.w = static_cast<int>(size.x); dest.h = static_cast<int>(size.y * renderer_->GetAspectRatio()); vector2 rotation_point = size * origin; SDL_Point pivot = { static_cast<int>(rotation_point.x), static_cast<int>(rotation_point.y) }; SDL_RenderCopyEx(renderer_->GetSDLRenderer(), texture_, &rect, &dest, angle, &pivot, SDL_FLIP_NONE); } vector2 Texture::GetSize() const { SDL_Point point; SDL_QueryTexture(texture_, 0, 0, &point.x, &point.y); return vector2(point.x, point.y); }
// MIT License // Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <vector> #include "Vector2.h" struct Settings { //If not provided in input file, these default values will be used Settings(): maxCollisionMargin(0.05), maxResidualPenetration(1.0e-3), maxSolverIterations(1000) {} //Margins and settings that can be used to improve convergence. double maxCollisionMargin; //Body dimension are extended by the collision margin, input is maximum, can be reduces during sim by sliders double maxResidualPenetration; //If all body penetrations are below this threshold value, output is produced and the program stops. int maxSolverIterations; //Maximum number of iterations in impulse solver. }; struct InputData { InputData(): domainSize(5.0,5.0), concentration(0.0) {} ~InputData() {} Vector2 domainSize; //Rectangular boundaries std::vector<std::vector<Vector2>> bodyPointsVec; //point defining body geometries double concentration; //aerial percentage of domain covered by polygons. Settings settings; };
/* Earl Kirkland Shader Development Original Code by Jamie King */ #include <gl\glew.h> #include <iostream> #include "MeOpenGl.h" #include <cassert> #include <glm\glm.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtx\transform.hpp> #include "ShapeGenerator.h" #include <fstream> #include <QtGui\qmouseevent> #include <QtGui\qkeyevent> #include "Camera.h" #include "DebugGuiManager.h" //#define GENERATED_SHAPE using namespace std; using glm::vec3; using glm::vec4; using glm::mat4; //const uint NUM_VERTICES_PER_TRI = 3; //const uint NUM_FLOATS_PER_VERTICE = 9; //const uint VERTEX_BYTE_SIZE = NUM_FLOATS_PER_VERTICE * sizeof(float); GLuint programID; GLuint planeNumIndices; GLuint sphereNumIndices; GLuint torusNumIndices; GLuint numIndices; Camera camera; void MeOpenGl::loadDataPlane() { //ShapeData plane = ShapeGenerator::makePlane(10); //ShapeData shape = ShapeGenerator::makeTorus(50); /* float verts[] = { // Top -1.0f, +1.0f, +1.0f, // 0 +1.0f, +0.0f, +0.0f, +1.0f, // Color +1.0f, +1.0f, +1.0f, // 1 +0.0f, +1.0f, +0.0f, +1.0f, // Color +1.0f, +1.0f, -1.0f, // 2 +0.0f, +0.0f, +1.0f, +1.0f, // Color -1.0f, +1.0f, -1.0f, // 3 +1.0f, +1.0f, +1.0f, +1.0f, // Color // Front -1.0f, +1.0f, -1.0f, // 4 +1.0f, +0.0f, +1.0f, +1.0f, // Color +1.0f, +1.0f, -1.0f, // 5 +0.0f, +0.5f, +0.2f, +1.0f, // Color +1.0f, -1.0f, -1.0f, // 6 +0.8f, +0.6f, +0.4f, +1.0f, // Color -1.0f, -1.0f, -1.0f, // 7 +0.3f, +1.0f, +0.5f, +1.0f, // Color // Right +1.0f, +1.0f, -1.0f, // 8 +0.2f, +0.5f, +0.2f, +1.0f, // Color +1.0f, +1.0f, +1.0f, // 9 +0.9f, +0.3f, +0.7f, +1.0f, // Color +1.0f, -1.0f, +1.0f, // 10 +0.3f, +0.7f, +0.5f, +1.0f, // Color +1.0f, -1.0f, -1.0f, // 11 +0.5f, +0.7f, +0.5f, +1.0f, // Color // Left -1.0f, +1.0f, +1.0f, // 12 +0.7f, +0.8f, +0.2f, +1.0f, // Color -1.0f, +1.0f, -1.0f, // 13 +0.5f, +0.7f, +0.3f, +1.0f, // Color -1.0f, -1.0f, -1.0f, // 14 +0.4f, +0.7f, +0.7f, +1.0f, // Color -1.0f, -1.0f, +1.0f, // 15 +0.2f, +0.5f, +1.0f, +1.0f, // Color // Back +1.0f, +1.0f, +1.0f, // 16 +0.6f, +1.0f, +0.7f, +1.0f, // Color -1.0f, +1.0f, +1.0f, // 17 +0.6f, +0.4f, +0.8f, +1.0f, // Color -1.0f, -1.0f, +1.0f, // 18 +0.2f, +0.8f, +0.7f, +1.0f, // Color +1.0f, -1.0f, +1.0f, // 19 +0.2f, +0.7f, +1.0f, +1.0f, // Color // Bottom +1.0f, -1.0f, -1.0f, // 20 +0.8f, +0.3f, +0.7f, +1.0f, // Color -1.0f, -1.0f, -1.0f, // 21 +0.8f, +0.9f, +0.5f, +1.0f, // Color -1.0f, -1.0f, +1.0f, // 22 +0.5f, +0.8f, +0.5f, +1.0f, // Color +1.0f, -1.0f, +1.0f, // 23 +0.9f, +1.0f, +0.2f, +1.0f, // Color };*/ /* GLushort Indices[] = { //indices are to tell us how the vertices are connected. 0, 1, 2, 0, 2, 3, // Top 4, 5, 6, 4, 6, 7, // Front 8, 9, 10, 8, 10, 11, // Right 12, 13, 14, 12, 14, 15, // Left 16, 17, 18, 16, 18, 19, // Back 20, 22, 21, 20, 23, 22, // Bottom }; */ //Triagle //GLfloat verts[] = { // +0.0f, +1.0f, // +1.0f, +0.0f, +0.0f, // -1.0f, -1.0f, // +0.0f, +1.0f, +0.0f, // +1.0f, -1.0f, // +0.0f, +0.0f, +1.0f, //}; /*GLuint vertexBufferID; glGenBuffers(1, &vertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (char*)(sizeof(float) * 2)); GLshort indices[] = { 0, 1, 2 }; GLuint indexBufferID; glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);*/ /*float verts[] = { -1.0f, -1.0f, +0.0f, +0.0f, +1.0f, -1.0f, +1.0f, +0.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, +0.0f, +1.0f, }; GLushort indices[] = { 0,1,2, 2,3,0 };*/ /*#ifdef GENERATED_SHAPE //ShapeData shape = ShapeGenerator::makePlane(10); //ShapeData shape = ShapeGenerator::makeTorus(100); //ShapeData shape = ShapeGenerator::make2DTriangle(); //ShapeData shape = ShapeGenerator::makeTeapot(); #else*/ ShapeDataPnut shape; std::ifstream input("E:\\GraphicsPad\\brick_wall.bin", std::ios::binary); assert(input.good()); input.read(reinterpret_cast<char*>(&shape.numVerts), sizeof(shape.numVerts)); assert(input.good()); input.read(reinterpret_cast<char*>(&shape.numIndices), sizeof(shape.numIndices)); shape.verts = new VertexPNUT[shape.numVerts]; input.read(reinterpret_cast<char*>(shape.verts), shape.vertexBufferSize()); int sanity = shape.vertexBufferSize(); shape.indices = new ushort[shape.numIndices]; input.read(reinterpret_cast<char*>(shape.indices), shape.vertexBufferSize()); glGenBuffers(1, &vertexBufferID); glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); glBufferData(GL_ARRAY_BUFFER, shape.vertexBufferSize(), shape.verts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, shape.indexBufferSize(), shape.indices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); numIndices = shape.numIndices; shape.cleanUp(); //textures /*glGenBuffers(1, &textureVertexBufferID); glGenBuffers(1, &textureIndexBufferID); glBindBuffer(GL_ARRAY_BUFFER, textureVertexBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, textureIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); numIndices = 6;*/ //torus /*ShapeData torus = ShapeGenerator::makeTorus(50); glGenBuffers(1, &torusVertexBufferID); glGenBuffers(1, &torusIndexBufferID); glBindBuffer(GL_ARRAY_BUFFER, torusVertexBufferID); glBufferData(GL_ARRAY_BUFFER, torus.vertexBufferSize(), torus.verts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, torusIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, torus.indexBufferSize(), torus.indices, GL_STATIC_DRAW); torusNumIndices = torus.numIndices; torus.cleanup(); //shpere ShapeData sphere = ShapeGenerator::makeSphere(50); glGenBuffers(1, &sphereVertexBufferID); glGenBuffers(1, &sphereIndexBufferID); glBindBuffer(GL_ARRAY_BUFFER, sphereVertexBufferID); glBufferData(GL_ARRAY_BUFFER, sphere.vertexBufferSize(), sphere.verts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sphere.indexBufferSize(), sphere.indices, GL_STATIC_DRAW); sphereNumIndices = sphere.numIndices; sphere.cleanup(); //plane ShapeData plane = ShapeGenerator::makePlane(10); glGenBuffers(1, &planeVertexBufferID); glGenBuffers(1, &planeIndexBufferID); glBindBuffer(GL_ARRAY_BUFFER, planeVertexBufferID); glBufferData(GL_ARRAY_BUFFER, plane.vertexBufferSize(), plane.verts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, planeIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane.indexBufferSize(), plane.indices, GL_STATIC_DRAW); planeNumIndices = plane.numIndices; plane.cleanup();*/ //connect(&myTimer, SIGNAL(timeout()), this, SLOT(myUpdate())); //myTimer.start(100); }; bool checkStatus( GLuint objectID, PFNGLGETSHADERIVPROC objectPropertyGetterFunc, PFNGLGETSHADERINFOLOGPROC getInfoLogFunc, GLenum statusType) { GLint status; objectPropertyGetterFunc(objectID, statusType, &status); if (status != GL_TRUE) { GLint infoLogLength; objectPropertyGetterFunc(objectID, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar* buffer = new GLchar[infoLogLength]; GLsizei bufferSize; glGetShaderInfoLog(objectID, infoLogLength, &bufferSize, buffer); cout << buffer << endl; delete[] buffer; return false; } return true; } bool checkShaderStatus(GLuint shaderID) { return checkStatus(shaderID, glGetShaderiv, glGetShaderInfoLog, GL_COMPILE_STATUS); } bool checkProgramStatus(GLuint programID) { return checkStatus(programID, glGetProgramiv, glGetProgramInfoLog, GL_LINK_STATUS); } string readShaderCode(const char* fileName) { ifstream meInput(fileName); if (!meInput.good()) { cout << "File failed to load.... " << fileName; exit(1); } return std::string( std::istreambuf_iterator<char>(meInput), std::istreambuf_iterator<char>()); } void MeOpenGl::installShaders() { GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); const char* adapter[1]; string temp = readShaderCode("VertexShaderCode.glsl"); adapter[0] = temp.c_str(); glShaderSource(vertexShaderID, 1, adapter, 0); temp = readShaderCode("FragmentShaderCode.glsl"); adapter[0] = temp.c_str(); glShaderSource(fragmentShaderID, 1, adapter, 0); glCompileShader(vertexShaderID); glCompileShader(fragmentShaderID); GLint compileStatus; glGetShaderiv(vertexShaderID, GL_COMPILE_STATUS, &compileStatus); if (compileStatus != GL_TRUE) { GLint infoLogLength; glGetShaderiv(vertexShaderID, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar* buffer = new GLchar[infoLogLength]; GLsizei bufferSize; glGetShaderInfoLog(vertexShaderID, infoLogLength, &bufferSize, buffer); cout << buffer << endl; delete[] buffer; } if (!checkShaderStatus(vertexShaderID) || !checkShaderStatus(fragmentShaderID)) return; programID = glCreateProgram(); glAttachShader(programID, vertexShaderID); glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); if (!checkProgramStatus(programID)) return; glUseProgram(programID); glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); } void MeOpenGl::sendDownUniform(float rotationAmount) { //GLuint uniformLocation = glGetUniformLocation(programID, "modelToProjectionMatrix"); /*glm::mat4 translate = glm::translate(0.0f, 0.0f, 0.0f); rotationAmount += 1.0f; //glm::mat4 modelToWorld = glm::scale(0.5f, 1.0f, 1.0f) * glm::mat4 rotate = glm::rotate(0.0f, //angle 1.0f, //x axis 0.0f, //y axis set to 1 if you want to rotation on this axis 0.0f) * //z axis glm::rotate(0.0f, 0.0f, 1.0f, 0.0f);//(rotationAmount, 1.0f, 0.0f, 0.0f) * glm::rotate(rotationAmount, 0.0f, 1.0f, 0.0f); glm::mat4 modelToWorld = translate * rotate; glm::mat4 worldToView = glm::lookAt( glm::vec3(0.0f, 1.0f, 0.0f), //eyePosition glm::vec3(0.0f, 1.0f, -1.0f), //Center glm::vec3(0.0f, 1.0f, 0.0f)); //Up direction glm::mat4 perspective = glm::perspective(60.0f, ((float)width()) / height(), 0.1f, 15.0f); //changed 100.0f to 1|||||5.0f //glm::mat4 modelToProjectionMatrix = modelToWorld * worldToView * viewToProjection; glm::mat4 modelToProjectionMatrix = perspective * camera.getWorldToViewMatrix() *modelToWorld * worldToView;// *worldToView * perspective; //Plane glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); //Torus 1: modelToWorld = glm::translate(-5.0f, 0.0f, 0.0f); modelToProjectionMatrix = perspective* worldToView * modelToWorld; glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]);*/ //Torus 2: //modelToWorld = glm::translate(-2.0f, 0.0f, 0.0f); //GLint location = glGetUniformLocation(programID, "modelToProjectionMatrix"); //glUniformMatrix4fv(location, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); /*GLint ambientLightUniformLocation = glGetUniformLocation(programID, "ambientLight"); glm::vec4 ambientLight(0.1f, 0.1f, 0.1f, 1.0f); glUniform4fv(ambientLightUniformLocation, 1, &ambientLight[0]); GLint lightPositionUniformLocation = glGetUniformLocation(programID, "lightPosition"); glm::vec3 lightPosition(0.0f, 2.0f, 0.0f); glUniform3fv(lightPositionUniformLocation, 1, &lightPosition[0]); GLint eyePositionWorldUniformLocation = glGetUniformLocation(programID, "eyePositionWorld"); glm::vec3 eyePositionWorld = camera.position; glUniform3fv(eyePositionWorldUniformLocation, 1, &eyePositionWorld[0]);*/ //glm::mat4 translate = glm::translate(0.0f, 0.0f, -5.0f); //glm::mat4 rotate = glm::rotate(45.0f, 1.0f, 0.0f) * glm::rotate(45.0f, 1.0f, 0.0f); //rotate 45 degrees around the x, then the Y //disfuse - draw a plane with 4 dot product s on it going up. Then there is light coming in from different angles, //and the cosine of the angle to the vector will show how bright is. //if the angle is coming from 0 and 180 degreens to the cosine, it will hit 0 which is the darkest. //vector is a position off the origin //translate will really mess with your vectors as it stretches them //rotation will change the normals but not translate //next assignment - plain down and drop the taurus orianted up with light hitting the side. Then put more taurus in there, put a camera in there and then put lighting in the fragment shader. } void MeOpenGl::myUpdate() { sendDownUniform(rotationAmount); rotationAmount = rotationAmount + 0.5f; repaint(); } void MeOpenGl::loadTexture() { GLuint textureID; glGenTextures(1, &textureID); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureID); QImage myTexture = QGLWidget::convertToGLFormat(QImage("brick.png", "PNG")); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, myTexture.width(), myTexture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, myTexture.bits()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLint textureUniformLocation = glGetUniformLocation(programID, "meTexture"); glUniform1i(textureUniformLocation, 0); } void MeOpenGl::initializeGL() { QGLWidget::initializeGL(); GLenum errorCode = glewInit(); if (errorCode != GLEW_OK) return; installShaders(); loadDataPlane(); loadTexture(); //loadDataSphere(); //sendDownUniform(); glEnable(GL_DEPTH_TEST); connect(&myTimer, SIGNAL(timeout()), this, SLOT(myUpdate())); myTimer.start(); } void MeOpenGl::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, width(), height()); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); GLuint uniformLocation = glGetUniformLocation(programID, "modelToProjectionMatrix"); GLuint normalUniformLocation = glGetUniformLocation(programID, "normalMatrix"); /*glm::mat4 translate = glm::translate(0.0f, 0.0f, 0.0f); //rotationAmount += 1.0f; //glm::mat4 modelToWorld = glm::scale(0.5f, 1.0f, 1.0f) * glm::mat4 rotate = glm::rotate(0.0f, //angle 1.0f, //x axis 0.0f, //y axis set to 1 if you want to rotation on this axis 0.0f) * //z axis glm::rotate(0.0f, 0.0f, 1.0f, 0.0f);*///(rotationAmount, 1.0f, 0.0f, 0.0f) * glm::rotate(rotationAmount, 0.0f, 1.0f, 0.0f); //glm::mat4 modelToWorld = //glm::rotate(90.0f, glm::vec3(+1.0f, +0.0f, +0.0f)) * //glm::rotate(180.0f, glm::vec3(+1.0f, +1.0f, +0.0f)); // = camera.getWorldToViewMatrix(); // = translate * rotate; glm::mat4 worldToView = camera.getWorldToViewMatrix(); /*glm::lookAt( glm::vec3(0.0f, 1.0f, 0.0f), //eyePosition glm::vec3(0.0f, 1.0f, -1.0f), //Center glm::vec3(0.0f, 1.0f, 0.0f));*/ //Up direction glm::mat4 perspective = glm::perspective(60.0f, ((float)width()) / height(), 0.1f, 100.0f); //changed 100.0f to 1|||||5.0f //glm::mat4 modelToProjectionMatrix = modelToWorld * worldToView * viewToProjection; glm::mat4 modelToProjectionMatrix = perspective * worldToView;// *modelToWorld; // = perspective * camera.getWorldToViewMatrix() *modelToWorld * worldToView;// *worldToView * perspective; glm::mat3 normalMatrix; //Plane glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPNUT), (void*)VertexOffsets::VO_PNUT_POSITION); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPNUT), (void*)VertexOffsets::VO_PNUT_NORMAL); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexPNUT), (void*)VertexOffsets::VO_PNUT_UV); debugGuiManager.update(); glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, 0); //textures /*glBindBuffer(GL_ARRAY_BUFFER, textureVertexBufferID); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); //glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float))); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), //Stride (void*)(2 * sizeof(float)));//offset glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, textureIndexBufferID);*/ //torus /*glBindBuffer(GL_ARRAY_BUFFER, torusVertexBufferID); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), //Stride (void*)(7 * sizeof(float)));//offset glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, torusIndexBufferID); //Torus 1: modelToWorld = glm::translate(3.0f, 0.0f, -5.0f) * glm::rotate(90.0f, 1.0f, 0.0f, 02.0f); modelToProjectionMatrix = perspective* worldToView * modelToWorld; normalMatrix = glm::mat3(modelToWorld); glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glUniformMatrix3fv(normalUniformLocation, 1, GL_FALSE, &normalMatrix[0][0]); glDrawElements(GL_TRIANGLES, torusNumIndices, GL_UNSIGNED_SHORT, 0); //Torus 2: modelToWorld = glm::translate(-3.0f, 0.0f, -5.0f) * glm::rotate(45.0f, 1.0f, 0.0f, 0.0f); modelToProjectionMatrix = perspective* worldToView * modelToWorld; normalMatrix = glm::mat3(modelToWorld); glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glUniformMatrix3fv(normalUniformLocation, 1, GL_FALSE, &normalMatrix[0][0]); glDrawElements(GL_TRIANGLES, torusNumIndices, GL_UNSIGNED_SHORT, 0); //Sphere glBindBuffer(GL_ARRAY_BUFFER, sphereVertexBufferID); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), //Stride (void*)(7 * sizeof(float)));//offset glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndexBufferID); //sphere1 modelToWorld = glm::translate(0.0f, 0.0f, -5.0f) * glm::rotate(90.0f, 1.0f, 0.0f, 02.0f); modelToProjectionMatrix = perspective* worldToView * modelToWorld; normalMatrix = glm::mat3(modelToWorld); glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glUniformMatrix3fv(normalUniformLocation, 1, GL_FALSE, &normalMatrix[0][0]); glDrawElements(GL_TRIANGLES, sphereNumIndices, GL_UNSIGNED_SHORT, 0); //Plane glBindBuffer(GL_ARRAY_BUFFER, planeVertexBufferID); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), //Stride (void*)(7 * sizeof(float)));//offset glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, planeIndexBufferID); //Plane 1: modelToWorld = glm::translate(0.0f, -5.0f, -5.0f) * glm::rotate(0.0f, 1.0f, 0.0f, 02.0f); modelToProjectionMatrix = perspective* worldToView * modelToWorld; normalMatrix = glm::mat3(modelToWorld); glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glUniformMatrix3fv(normalUniformLocation, 1, GL_FALSE, &normalMatrix[0][0]); glDrawElements(GL_TRIANGLES, planeNumIndices, GL_UNSIGNED_SHORT, 0);*/ /*............... glUniformMatrix4v(uniformLocation, 1, GL_FALSE, &modelToProjectionMatrix[0][0]); glUniformMatrix3v(normalUniformLocation, 1, GL_FALSE, &normalMatrix[0][0]); glDraw.... ..............*/ //Torus1 //glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, 0); // there are 6 indices for one side of the cube, 3 for each triabngle /*glm::vec3 lightPositionWorld(0.0f, 2.0f, 0.0f); mat4 modelToProjectionMatrix; mat4 viewToProjectionMatrix = glm::perspective(60.0f, ((float)width()) / height(), 0.1f, 20.0f); mat4 worldToViewMatrix = camera.getWorldToViewMatrix(); mat4 worldToProjectionMatrix = viewToProjectionMatrix * worldToViewMatrix; GLint modelToWorldTransformMatrixUniformLocation = glGetUniformLocation(programID, "modelToWorldMatrix");*/ } void MeOpenGl::mouseMoveEvent(QMouseEvent* e) { camera.mouseUpdate(glm::vec2(e->x(), e->y())); setFocus(); repaint(); } void MeOpenGl::keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Qt::Key::Key_W: camera.moveForward(); break; case Qt::Key::Key_S: camera.moveBackward(); break; case Qt::Key::Key_A: camera.strafeLeft(); break; case Qt::Key::Key_D: camera.strafeRight(); break; case Qt::Key::Key_R: camera.moveUp(); break; case Qt::Key::Key_F: camera.moveDown(); break; } repaint(); }
#include "BuitInShaders.h" const char* defaultVert = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "layout(location = 0) in vec3 vertex_position;" "layout(location = 1) in vec2 in_texture_coordinates;" "out vec2 texture_coordinates;" "uniform vec2 resolution;" "uniform vec4 rect;" "uniform sampler2D basic_texture;" "" "void main ()" "{" " texture_coordinates = in_texture_coordinates;" " if(vertex_position.x < 0.0 && vertex_position.y < 0.0)" " {" " gl_Position.x = ((rect.x / resolution.x) * 2) - 1; " " gl_Position.y = ((rect.y / resolution.y) * 2) - 1; " " texture_coordinates.x = 0; texture_coordinates.y = 0;" " }" " else if(vertex_position.x > 0.0 && vertex_position.y < 0.0)" " {" " gl_Position.x = (((rect.x + rect.z) / resolution.x) * 2) - 1;" " gl_Position.y = ((rect.y / resolution.y) * 2) - 1;" " texture_coordinates.x = 1; texture_coordinates.y = 0;" " }" " else if(vertex_position.x < 0.0 && vertex_position.y > 0.0) " " {" " gl_Position.x = ((rect.x / resolution.x) * 2) - 1;" " gl_Position.y = (((rect.y + rect.w) / resolution.y) * 2) - 1;" " texture_coordinates.x = 0; texture_coordinates.y = 1;" " }" " else if(vertex_position.x > 0.0 && vertex_position.y > 0.0)" " {" " gl_Position.x = (((rect.x + rect.z) / resolution.x) * 2) - 1;" " gl_Position.y = (((rect.y + rect.w) / resolution.y) * 2) - 1;" " texture_coordinates.x = 1; texture_coordinates.y = 1;" " }" "" " gl_Position.y *= -1; gl_Position.z = 1.0; gl_Position.w = 1.0;" "}" ""; const char* defaultFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "in vec2 texture_coordinates;" "uniform sampler2D basic_texture;" "uniform vec2 atlasPos,spriteSize;" "uniform vec4 inColor;" "out vec4 frag_color;" "void main()" "{" " vec4 texel = texture2D(basic_texture, texture_coordinates);" " frag_color = vec4(texel.r * inColor.r, texel.g * inColor.g, texel.b * inColor.b, texel.a * inColor.a);" " if(frag_color.a == 0 || inColor.a == 0)" " frag_color=vec4(0,0,0,0);" "}" ""; const char* defaultAtlassedFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "in vec2 texture_coordinates;" "uniform sampler2D basic_texture;" "uniform vec2 atlasPos,spriteSize;" "uniform vec4 inColor;" "out vec4 frag_color;" "void main()" "{" " vec2 realCoord = atlasPos + spriteSize * texture_coordinates;" " vec4 texel = texture2D(basic_texture, realCoord);" " frag_color = vec4(texel.r * inColor.r, texel.g * inColor.g, texel.b * inColor.b, texel.a * inColor.a);" "}" ""; const char* defaultPostProcessVert = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "layout(location = 0) in vec3 position;" "layout(location = 1) in vec2 textureCoordsIn;" "out vec2 textureCoords;" "uniform vec2 resolution;" "uniform float time;" "uniform float rand;" "uniform vec2 screenRatio;" "" "void main()" "{" " textureCoords = textureCoordsIn;" " gl_Position = vec4(position.x * screenRatio.x, position.y * screenRatio.y, position.z, 1.0);" "}" ""; const char* defaultPostProcessFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "in vec2 textureCoords;" "out vec4 outColor;" "uniform sampler2D textureFramebuffer;" "uniform vec2 resolution;" "uniform float time;" "uniform float rand;" "" "void main()" "{" " vec4 texel = texture(textureFramebuffer, textureCoords);" "outColor = vec4(texel.rgb, 1);" "}" ""; const char* dfPrimitiveRectangleFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "in vec2 texture_coordinates;" "uniform vec4 inColor;" "out vec4 frag_color;" "void main()" "{" " frag_color = vec4(inColor.r, inColor.g, inColor.b, inColor.a);" "}" ""; const char* dfPrimitiveCircleVert = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "layout(location = 0) in vec3 vertex_position;" "layout(location = 1) in vec2 in_texture_coordinates;" "out vec2 texture_coordinates;" "uniform vec2 resolution;" "uniform vec2 pos;" "uniform float radius;" "uniform sampler2D basic_texture;" "" "void main ()" "{" " texture_coordinates = in_texture_coordinates;" " if(vertex_position.x < 0.0 && vertex_position.y < 0.0)" " {" " gl_Position.x = (((pos.x - radius) / resolution.x) * 2) - 1; " " gl_Position.y = (((pos.y - radius) / resolution.y) * 2) - 1; " " texture_coordinates.x = 0; texture_coordinates.y = 0;" " }" " else if(vertex_position.x > 0.0 && vertex_position.y < 0.0)" " {" " gl_Position.x = (((pos.x + radius) / resolution.x) * 2) - 1;" " gl_Position.y = (((pos.y - radius) / resolution.y) * 2) - 1;" " texture_coordinates.x = 1; texture_coordinates.y = 0;" " }" " else if(vertex_position.x < 0.0 && vertex_position.y > 0.0) " " {" " gl_Position.x = (((pos.x - radius) / resolution.x) * 2) - 1;" " gl_Position.y = (((pos.y + radius) / resolution.y) * 2) - 1;" " texture_coordinates.x = 0; texture_coordinates.y = 1;" " }" " else if(vertex_position.x > 0.0 && vertex_position.y > 0.0)" " {" " gl_Position.x = (((pos.x + radius) / resolution.x) * 2) - 1;" " gl_Position.y = (((pos.y + radius) / resolution.y) * 2) - 1;" " texture_coordinates.x = 1; texture_coordinates.y = 1;" " }" "" " gl_Position.y *= -1; gl_Position.z = 1.0; gl_Position.w = 1.0;" "}" ""; const char* dfPrimitiveCircleFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "in vec2 texture_coordinates;" "uniform vec2 resolution;" "uniform vec2 pos;" "uniform float radius;" "uniform vec4 inColor;" "out vec4 frag_color;" "void main()" "{" " frag_color = vec4(inColor.r, inColor.g, inColor.b, inColor.a);" " vec2 textureCoordTransformed = texture_coordinates * resolution;" " float dist = distance(texture_coordinates, vec2(0.5, 0.5));" " if(dist > 0.5)" " {" " frag_color.a = 0;" " }" "}" ""; const char* dfPrimitiveLineVert = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "layout(location = 0) in vec3 position;" "uniform vec4 inColor;" "" "void main()" "{" " gl_Position = vec4(position.x, position.y, position.z, 1.0);" "}" ""; const char* dfPrimitiveLineFrag = "" "#version 130\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_explicit_uniform_location : require\n" "uniform vec4 inColor;" "out vec4 frag_color;" "void main()" "{" " frag_color = vec4(inColor.r, inColor.g, inColor.b, inColor.a);" "}" "";
// // main.cpp // GameProject // // Created by Orin Elmquist on 6/12/18. // Copyright © 2018 Orin Elmquist. All rights reserved. // #include <iostream> #include <stdlib.h> #include <time.h> #include "Game.hpp" //const unsigned int SEED = 143245543; //Seed Error //1529537124 Unconnected part of cave int main() { // unsigned int seed = time(NULL); unsigned int seed = 1529537124; srand(seed); std::cout << seed << std::endl << std::endl; World w; w.buildCave(); std::cout << w << std::endl; w.buildDungeon(); std::cout << w << std::endl; return 0; }
#include <iberbar/Poster/Elements/ElementLabel.h> #include <iberbar/Poster/Font.h> iberbar::Poster::CElementLabel::CElementLabel() : m_font( nullptr ) , m_text( U"" ) , m_textOptions() { } iberbar::Poster::CElementLabel::~CElementLabel() { UNKNOWN_SAFE_RELEASE_NULL( m_font ); } void iberbar::Poster::CElementLabel::RenderSelf( CSurface* target ) { int maxLine = (m_textOptions.maxLine > 0) ? m_textOptions.maxLine : MAXINT32; UFontDrawTextOptions drawOptions; drawOptions.alignHorizental = m_textOptions.alignHorizental; drawOptions.alignVertical = m_textOptions.alignVertical; drawOptions.nWrapType = UFontDrawTextWorkBreak::BreakAll; if ( m_textOptions.maxLine == 1 ) { RenderText_SingleLine( target, m_font, m_text.c_str(), -1, &m_bounding, m_textOptions.foregroundColor, drawOptions ); } else { } } void iberbar::Poster::CElementLabel::SetFont( CFont* font ) { UNKNOWN_SAFE_RELEASE_NULL( m_font ); m_font = font; if ( m_font != nullptr ) { m_font->AddRef(); } }
boolean flag = true; void setup() { pinMode(7,OUTPUT); pinMode(3,INPUT); pinMode(4,INPUT); pinMode(5,INPUT); pinMode(6,OUTPUT); digitalWrite(6,LOW); } void loop() { for ( int x = 0; x < 100; x++){ work(); } //delay(5000);// если нужно убрать паузу, удали это } void work(){ for( int i = 0; i < 5; i++){ //====================================1 if(digitalRead(5) == HIGH){ delayMicroseconds(7600);// 0 до 10 задержка сигнала digitalWrite(6,HIGH); delayMicroseconds(100);// длина импульса 1-2 digitalWrite(6,LOW); while(digitalRead(5) == HIGH); } if(digitalRead(4) == HIGH){ delayMicroseconds(1500);//задержка после щелчка if(digitalRead(3) == HIGH){ digitalWrite(7, HIGH); }else{ digitalWrite(7, LOW); } while(digitalRead(4) == HIGH); } //====================================2 for(int i = 0; i < 3;i++){ while(digitalRead(5) == LOW); if(digitalRead(5) == HIGH){ while(digitalRead(5) == HIGH); } } if(digitalRead(4) == HIGH){ delayMicroseconds(7600);// 0 до 10 задержка сигнала digitalWrite(6,HIGH); delayMicroseconds(100);// длина импульса 1-2 digitalWrite(6,LOW); while(digitalRead(4) == HIGH); } //====================================3 if(digitalRead(5) == HIGH){ delayMicroseconds(1500);//задержка после щелчка if(digitalRead(3) == HIGH){ digitalWrite(7, HIGH); }else{ digitalWrite(7, LOW); } while(digitalRead(5) == HIGH); } for(int i = 0; i < 3;i++){ while(digitalRead(4) == LOW); if(digitalRead(4) == HIGH){ while(digitalRead(4) == HIGH); } } } }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int sharp[1000000] = {0}; int dot[1000000] = {0}; int main() { int n; cin >> n; string s; cin >> s; int sums = 0; for(int i = 0; i < n; i++) { if(s[i] == '#'){ sums++; } sharp[i] = sums; } int sumd = 0; for(int i = n - 1; i >= 0; i--) { if(s[i] == '.'){ sumd++; } dot[i] = sumd; } int ans = 10000000; for(int i = 0; i < n -1; i++) { int tmp = sharp[i] + dot[i + 1]; //printf("%d %d %d %d\n", i, sharp[i], dot[i], sharp[i] + dot[i + 1]); ans = min(ans, tmp); } ans = min(ans, dot[0]); ans = min(ans, sharp[n - 1]); cout << ans << endl; }
#include "Curve.h" struct point { double x,y,z; }; Curve::Curve() { } Curve::~Curve() { } void Curve::init() { this->control_points_pos = { { 0.0, 8.5, -2.0 }, { -3.0, 11.0, 2.3 }, { -6.0, 8.5, -2.5 }, { -4.0, 5.5, 2.8 }, { 1.0, 2.0, -4.0 }, { 4.0, 2.0, 3.0 }, { 7.0, 8.0, -2.0 }, { 3.0, 10.0, 3.7 } }; } void Curve::calculate_curve() { // std::cout << "Run func: calculate_curve." << std::endl; // // point check // int i = 0; // std::cout << "point check (point " << i << "): (" << // control_points_pos[i].x << ", " << // control_points_pos[i].y << ", " << // control_points_pos[i].z << ")" << // std::endl; this->curve_points_pos = { { 0.0, 8.5, -2.0 }, // 0 { -3.0, 11.0, 2.3 }, // 1 { -6.0, 8.5, -2.5 }, // 2 { -4.0, 5.5, 2.8 }, // 3 { 1.0, 2.0, -4.0 }, // 4 { 4.0, 2.0, 3.0 }, // 5 { 7.0, 8.0, -2.0 }, // 6 { 3.0, 10.0, 3.7 } // 7 }; // Apply Catmull-Rom Formulation int num_of_init_points = int( control_points_pos.size() ); for (int i = 0; i < num_of_init_points; i++) { // p.push_back( control_points_pos[i] ); point p0,p1,v0,v1; p0.x = control_points_pos[i].x; p1.x = control_points_pos[(i+1) % num_of_init_points].x; v0.x = tau * ( control_points_pos[(i+1) % num_of_init_points].x - control_points_pos[(i-1+num_of_init_points) % num_of_init_points].x ); v1.x = tau * ( control_points_pos[(i+2) % num_of_init_points].x - control_points_pos[(i-0) % num_of_init_points].x ); // std::cout << i << "th point, ** v0.x: " << v0.x << std::endl; p0.y = control_points_pos[i].y; p1.y = control_points_pos[(i+1) % num_of_init_points].y; v0.y = tau * ( control_points_pos[(i+1) % num_of_init_points].y - control_points_pos[(i-1+num_of_init_points) % num_of_init_points].y ); v1.y = tau * ( control_points_pos[(i+2) % num_of_init_points].y - control_points_pos[(i-0) % num_of_init_points].y ); p0.z = control_points_pos[i].z; p1.z = control_points_pos[(i+1) % num_of_init_points].z; v0.z = tau * ( control_points_pos[(i+1) % num_of_init_points].z - control_points_pos[(i-1+num_of_init_points) % num_of_init_points].z ); v1.z = tau * ( control_points_pos[(i+2) % num_of_init_points].z - control_points_pos[(i-0) % num_of_init_points].z ); // // test tangents // if (i == 0) { // std::cout << "For i = " << i << ", the tangent of x-y plane is:" << std::endl; // std::cout << "v0.x: " << v0.x << std::endl; // std::cout << "v0.y: " << v0.y << std::endl; // } // calculate points between each two given points. double delta = 1.0 / num_points_per_segment; for (int j = 0; j < num_points_per_segment; j++) { double t = j * delta; // std::cout << "t: " << t << std::endl; // test variation of 't' double t1 = 2 * pow(t, 3) + (-3) * pow(t, 2) + 1; double t2 = (-2) * pow(t, 3) + 3 * pow(t, 2); double t3 = 1 * pow(t, 3) + (-2) * pow(t, 2) + t; double t4 = 1 * pow(t, 3) + (-1) * pow(t, 2); p.push_back( { p0.x * t1 + p1.x * t2 + v0.x * t3 + v1.x * t4, p0.y * t1 + p1.y * t2 + v0.y * t3 + v1.y * t4, p0.z * t1 + p1.z * t2 + v0.z * t3 + v1.z * t4 } ); } } // std::cout << "Hermite Curve. Number of points: " << p.size() << std::endl; // check total points' numbers // // check several points // for (int i = 0; i < 10; i+=1) { // std::cout << "Test points " << i << ": (" << p[i].x << ", " << p[i].y << ", " << p[i].z << ")" << std::endl; // } }
/* * Copyright (c) 2014-2019 Detlef Vollmann, vollmann engineering gmbh * * 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 "staticVector.hh" #include "staticVector.tt" #include <string> #include <memory> #include <iostream> using namespace std::literals; using namespace exercise; using std::cout; void foo1() { StaticVector<std::string> v1{ "Hello"s, "C++"s }; auto v2 = v1; cout << "Equal: " << std::boolalpha << (v1 == v2) << '\n'; for (std::string const &s: v2) { cout << s << ' '; } cout << '\n'; try { cout << "Deliberate out of range access: " << v1[v1.size()+1]; } catch (std::out_of_range exception) { cout << "Could not access an out of range index:\n" << exception.what() << "\n"; throw; } } int main() { std::string *sPtr = new std::string("asd"); delete sPtr; cout << *sPtr; // deliberate to have the sanitizer here // try { foo1(); // } catch (std::exception e) { // std::terminate(); // } return 0; }
/* COMMON MISTAKE - next node has a prev too which needs to be taken care of */ #include <iostream> using namespace std; class Node { public: int data; Node *next; Node *prev; }; void push(Node **head_ref, int new_data) { // new node added in front and first node's //prev is always null // could also be written like this /* Node *new_node = new Node(); new_node -> data = new_data; new_node -> next = *head_ref; new_node -> prev = NULL; */ if(*head_ref == NULL) { Node *new_node = new Node(); new_node -> data = new_data; new_node -> next = *head_ref; new_node -> prev = NULL; (*head_ref) = new_node; } else { Node *new_node = new Node(); new_node -> data = new_data; new_node -> next = *head_ref; new_node -> prev = NULL; (*head_ref) -> prev = new_node; (*head_ref) = new_node; } // (*head_ref) = new_node;(possibility) } void insertAfter(Node *prev_node, int value) { if(prev_node == NULL) { cout << "prev node can't be empty use push method instead"; return; } Node *new_node = new Node(); new_node -> next = prev_node -> next; new_node -> prev = prev_node; new_node -> data = value; prev_node -> next = new_node; // most importtant bit if(new_node -> next != NULL) { (new_node -> next) ->prev = new_node; } return; } void addToEnd(Node **head_ref, int value) { Node* new_node = new Node(); new_node -> next = NULL; new_node -> data = value; if(*head_ref == NULL) { new_node -> prev = NULL; *head_ref = new_node; return; } // if ll is not empty Node *itr = *head_ref; while(itr -> next != NULL) { itr = itr -> next; } // itr is at last now itr -> next = new_node; // VV IMPT IN doubly LL new_node -> prev = itr; return; } void printlist(Node *head) { // head is a temp variable // don't use head as a global variable if(head == NULL) { cout << "list is empty"; return; } while(head -> next != NULL) { cout << head -> data << " "; head = head -> next; } // print the last node as well cout << head -> data << endl; return; } void deleteNode(Node **head_ref, Node *key) { if(*head_ref == NULL || key == NULL) { cout << "invalid input"; return; } if(*head_ref == key) { head_ref = key -> next; } // IF IN THE MIDDLE THEN // BOTH IF CONDITIONS RUN if(key->next != NULL) { (key->next)->prev = key -> prev; } // if it is the last node if(key -> prev != NULL) { key->prev->next = key -> next; } free(key); return; } int main() { // create a Node object Node *head = new Node(); // push is in front of the node push(&head,5); push(&head,1); push(&head,2); addToEnd(&head,7); addToEnd(&head,1); addToEnd(&head,6); printlist(head); }
#include <GL/glut.h> #include <GL/GL.h> #include <GL/GLU.h> #include <iostream> #include <string> #include "Client.hpp" using namespace std; class Vector2d { public: double x = 0.0, y = 0.0; }; constexpr auto PORT = 45678; constexpr auto SERVER_IP = "114.29.136.181"; class Game { public: Game() : client(SERVER_IP, PORT) { } void run() { try { client.init(); } catch (const char *error) { cout << error << endl; exit(1); } while (client.checkConnect()) { string msg; cin >> msg; if (msg == "end") break; Sleep(1000); } client.close(); exit(2); } void onRecv(const char *buff, const int &len) { Vector2d pos = *(Vector2d *)(buff); teapotPos.x = pos.x; teapotPos.y = pos.y; } void keyboard(unsigned char key) { switch (key) { case 'w': teapotPos.y += 0.01; break; case 'a': teapotPos.x -= 0.01; break; case 's': teapotPos.y -= 0.01; break; case 'd': teapotPos.x += 0.01; break; default: break; } if (client.checkConnect()) client.send((const char *)&teapotPos, sizeof(teapotPos)); } Client client; Vector2d teapotPos; }; Game game; GLvoid Screen(GLvoid) { glClear(GL_COLOR_BUFFER_BIT); glViewport(0, 0, 300, 300); glBegin(GL_POLYGON); { glColor3f(0.0, 1.0, 0.0); glVertex3f(-0.5f, 0.5f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.0f); glVertex3f(0.5f, -0.5f, 0.0f); glVertex3f(0.5f, 0.5f, 0.0f); } glEnd(); glColor3f(1.0, 0.0, 0.0); glLoadIdentity(); glTranslated(game.teapotPos.x, game.teapotPos.y, 0); glutSolidTeapot(0.5); //glFlush(); glutSwapBuffers(); } GLvoid Keyboard(unsigned char key, int x, int y) { game.keyboard(key); } void timer(int value) { glutPostRedisplay(); glutTimerFunc(10, timer, 0); } #ifdef _DEBUG int main(int argc, char **argv) #else int WINAPI WinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd ) #endif { glutInit(&__argc, __argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(300, 300); glutInitWindowPosition(100, 100); glutCreateWindow("ÀÌÇö"); glClearColor(0.0, 0.0, 0.0, 1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); glutKeyboardFunc(Keyboard); glutDisplayFunc(Screen); glutTimerFunc(0, timer, 0); game.client.setOnRecv([](const char *buff, const int &len) { game.onRecv(buff, len); }); thread gameThread(&Game::run, &game); glutMainLoop(); return 0; }
/* * Program: ImageStitching.cpp * Usage: Start image stitching */ #ifndef IMAGE_STITCHING_H #define IMAGE_STITCHING_H #include <vector> #include <queue> #include "SIFT.h" #include "Utils.h" #include "Matching.h" #include "Warping.h" #include "Blending.h" class Stitcher{ public: Stitcher(vector<CImg<unsigned char>> input); CImg<unsigned char> stitchImages(); // Tool functions int computeMiddle(vector<vector<int>>& indexes); void addFeaturesByHomoegraphy(map<vector<float>, VlSiftKeypoint>& feature, Axis H, float offset_x, float offset_y); void adjustOffset(map<vector<float>, VlSiftKeypoint>& feature, int offset_x, int offset_y); private: vector<CImg<unsigned char>> src; // Features of every images vector<map<vector<float>, VlSiftKeypoint>> features; // Tools Warper wr; Matcher mt; Utils ut; }; #endif
// Copyright (c) 2020 ETH Zurich // // 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) #pragma once #include <pika/config.hpp> #if defined(PIKA_HAVE_STDEXEC) # include <pika/execution_base/stdexec_forward.hpp> #else # include <pika/concepts/concepts.hpp> # include <pika/errors/try_catch_exception_ptr.hpp> # include <pika/execution/algorithms/detail/partial_algorithm.hpp> # include <pika/execution_base/completion_scheduler.hpp> # include <pika/execution_base/receiver.hpp> # include <pika/execution_base/sender.hpp> # include <pika/functional/detail/invoke.hpp> # include <pika/functional/detail/tag_fallback_invoke.hpp> # include <pika/type_support/pack.hpp> # include <exception> # include <type_traits> # include <utility> namespace pika::then_detail { template <typename Receiver, typename F> struct then_receiver_impl { struct then_receiver_type; }; template <typename Receiver, typename F> using then_receiver = typename then_receiver_impl<Receiver, F>::then_receiver_type; template <typename Receiver, typename F> struct then_receiver_impl<Receiver, F>::then_receiver_type { PIKA_NO_UNIQUE_ADDRESS std::decay_t<Receiver> receiver; PIKA_NO_UNIQUE_ADDRESS std::decay_t<F> f; template <typename Error> friend void tag_invoke(pika::execution::experimental::set_error_t, then_receiver_type&& r, Error&& error) noexcept { pika::execution::experimental::set_error( PIKA_MOVE(r.receiver), PIKA_FORWARD(Error, error)); } friend void tag_invoke( pika::execution::experimental::set_stopped_t, then_receiver_type&& r) noexcept { pika::execution::experimental::set_stopped(PIKA_MOVE(r.receiver)); } private: template <typename... Ts> void set_value_helper(Ts&&... ts) noexcept { pika::detail::try_catch_exception_ptr( [&]() { if constexpr (std::is_void_v<std::invoke_result_t<F, Ts...>>) { // Certain versions of GCC with optimizations fail on // the move with an internal compiler error. # if defined(PIKA_GCC_VERSION) && (PIKA_GCC_VERSION < 100000) PIKA_INVOKE(std::move(f), PIKA_FORWARD(Ts, ts)...); # else PIKA_INVOKE(PIKA_MOVE(f), PIKA_FORWARD(Ts, ts)...); # endif pika::execution::experimental::set_value(PIKA_MOVE(receiver)); } else { // Certain versions of GCC with optimizations fail on // the move with an internal compiler error. # if defined(PIKA_GCC_VERSION) && (PIKA_GCC_VERSION < 100000) auto&& result = PIKA_INVOKE(std::move(f), PIKA_FORWARD(Ts, ts)...); # else auto&& result = PIKA_INVOKE(PIKA_MOVE(f), PIKA_FORWARD(Ts, ts)...); # endif pika::execution::experimental::set_value( PIKA_MOVE(receiver), PIKA_MOVE(result)); } }, [&](std::exception_ptr ep) { pika::execution::experimental::set_error(PIKA_MOVE(receiver), PIKA_MOVE(ep)); }); } template <typename... Ts> friend void tag_invoke( pika::execution::experimental::set_value_t, then_receiver_type&& r, Ts&&... ts) noexcept { // GCC 7 fails with an internal compiler error unless the actual // body is in a helper function. r.set_value_helper(PIKA_FORWARD(Ts, ts)...); } }; template <typename Sender, typename F> struct then_sender_impl { struct then_sender_type; }; template <typename Sender, typename F> using then_sender = typename then_sender_impl<Sender, F>::then_sender_type; template <typename Sender, typename F> struct then_sender_impl<Sender, F>::then_sender_type { PIKA_NO_UNIQUE_ADDRESS std::decay_t<Sender> sender; PIKA_NO_UNIQUE_ADDRESS std::decay_t<F> f; template <typename Tuple> struct invoke_result_helper; template <template <typename...> class Tuple, typename... Ts> struct invoke_result_helper<Tuple<Ts...>> { using result_type = std::invoke_result_t<F, Ts...>; using type = std::conditional_t<std::is_void<result_type>::value, Tuple<>, Tuple<result_type>>; }; template <template <typename...> class Tuple, template <typename...> class Variant> using value_types = pika::util::detail::unique_t< pika::util::detail::transform_t<typename pika::execution::experimental::sender_traits< Sender>::template value_types<Tuple, Variant>, invoke_result_helper>>; template <template <typename...> class Variant> using error_types = pika::util::detail::unique_t< pika::util::detail::prepend_t<typename pika::execution::experimental::sender_traits< Sender>::template error_types<Variant>, std::exception_ptr>>; static constexpr bool sends_done = false; template <typename Receiver> friend auto tag_invoke( pika::execution::experimental::connect_t, then_sender_type&& s, Receiver&& receiver) { return pika::execution::experimental::connect(PIKA_MOVE(s.sender), then_receiver<Receiver, F>{PIKA_FORWARD(Receiver, receiver), PIKA_MOVE(s.f)}); } template <typename Receiver> friend auto tag_invoke(pika::execution::experimental::connect_t, then_sender_type const& r, Receiver&& receiver) { return pika::execution::experimental::connect( r.sender, then_receiver<Receiver, F>{PIKA_FORWARD(Receiver, receiver), r.f}); } friend decltype(auto) tag_invoke( pika::execution::experimental::get_env_t, then_sender_type const& s) noexcept { return pika::execution::experimental::get_env(s.sender); } }; } // namespace pika::then_detail namespace pika::execution::experimental { inline constexpr struct then_t final : pika::functional::detail::tag_fallback<then_t> { private: // clang-format off template <typename Sender, typename F, PIKA_CONCEPT_REQUIRES_( is_sender_v<Sender> )> // clang-format on friend constexpr PIKA_FORCEINLINE auto tag_fallback_invoke(then_t, Sender&& sender, F&& f) { return then_detail::then_sender<Sender, F>{ PIKA_FORWARD(Sender, sender), PIKA_FORWARD(F, f)}; } template <typename F> friend constexpr PIKA_FORCEINLINE auto tag_fallback_invoke(then_t, F&& f) { return detail::partial_algorithm<then_t, F>{PIKA_FORWARD(F, f)}; } } then{}; } // namespace pika::execution::experimental #endif
#pragma once #include "data.h" #include "linearregression.h" namespace hdd::gamma { class Gamma { public: Gamma(const Data& data, uint32_t pMax, uint32_t numMoments = MomentsMin()); friend std::ostream& operator<<(std::ostream& os, const Gamma& g); static constexpr uint32_t MomentsMin() { return 2; } static constexpr uint32_t MomentsMax() { return 10; } private: const Data& data_; const uint32_t pmax_; const uint32_t highMoments_; std::vector<valarray_fp> delta_; std::vector<std::vector<valarray_fp>> gamma_; std::vector<std::vector<Regression>> r_; std::vector<valarray_fp> moments_; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_EDIT_COMMON_H #define OP_EDIT_COMMON_H // This header declares functions, variables and types shared between the // various edit control-related files (OpEdit.cpp, OpMultiEdit.cpp, // OpTextCollection.cpp). Definitions appear in OpEdit.cpp. // Recognizes non-ASCII whitespace characters BOOL IsWhitespaceChar(uni_char c); // A CharRecognizer has a method is() that returns TRUE for characters // belonging to a particular class (word character, whitespace, punctuation, // etc.). This determines regions and boundaries for text in edit boxes. An // older solution used function pointers instead of a class hierarchy and // virtual functions, but that caused problems with BREW. class CharRecognizer { public: virtual BOOL is(uni_char c) = 0; }; #define N_CHAR_RECOGNIZERS 3 class WordCharRecognizer : public CharRecognizer { public: virtual BOOL is(uni_char c) { return uni_isalnum(c); } }; class WhitespaceCharRecognizer : public CharRecognizer { public: virtual BOOL is(uni_char c) { return IsWhitespaceChar(c); } }; // Non-whitespace characters that act as word delimiters class WordDelimiterCharRecognizer : public CharRecognizer { public: virtual BOOL is(uni_char c) { return !(uni_isspace(c) || uni_isalnum(c)); } }; // Returns a CharRecognizer that will recognize characters belonging to the // same class as 'c'. See the implementation for instructions on how to add a // new character class. CharRecognizer *GetCharTypeRecognizer(uni_char c); // Returns the delta from start to the beginning of the word in the specified // direction INT32 SeekWord(const uni_char* str, INT32 start, INT32 step, INT32 max_len); // These functions find the edges of regions consisting of characters // belonging to the same class (where two characters are of the same class if // a sequence of such characters should be considered a unit when // double-clicking, ctrl-stepping, etc.). They return the position of the // next/previous character in a different class, or the start or end of the // line if no such character is found. If 'stay_within_region' is true, // PrevCharRegion will return the position of the first character in the // region instead of the character preceding it. INT32 NextCharRegion(const uni_char* str, INT32 start, INT32 max_len = 1000000); INT32 PrevCharRegion(const uni_char* str, INT32 start, BOOL stay_within_region); /** The direction of a selection */ enum SELECTION_DIRECTION { SELECTION_DIRECTION_FORWARD, ///< Forward selection, meaning the caret is at the front of the selection. SELECTION_DIRECTION_BACKWARD, ///< Backward selection, meaning the caret is at the back of the selection. SELECTION_DIRECTION_NONE ///< No selection direction, meaning the direction of the selection haven't been determined yet. }; #ifdef RANGESELECT_FROM_EDGE #define SELECTION_DIRECTION_DEFAULT SELECTION_DIRECTION_NONE ///< The default selection direction. #else #define SELECTION_DIRECTION_DEFAULT SELECTION_DIRECTION_FORWARD ///< The default selection direction. #endif // RANGESELECT_FROM_EDGE #endif // OP_EDIT_COMMON_H
#include<stdio.h> main() { char str[1000]; int i,num=0,word=0; char c; printf("input a string:\n"); gets(str); for(i=0;((c=str[i])!='\0');i++) if(c==' ') word=0; else if(word==0) { word=1; num++; } printf("there are %d words in this string.",num); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 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" #ifdef SECMAN_USERCONSENT #include "modules/security_manager/src/security_persistence.h" ChoicePersistenceType ToChoicePersistence(OpPermissionListener::PermissionCallback::PersistenceType persistence) { switch(persistence) { case OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_NONE: return PERSISTENCE_NONE; case OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_RUNTIME: return PERSISTENCE_RUNTIME; case OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_SESSION: return PERSISTENCE_SESSION; case OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_ALWAYS: return PERSISTENCE_FULL; } OP_ASSERT(!"Unknown persistence value"); return PERSISTENCE_NONE; } OpPermissionListener::PermissionCallback::PersistenceType ToPermissionListenerPersistence(ChoicePersistenceType persistence) { switch (persistence) { case PERSISTENCE_RUNTIME: return OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_RUNTIME; case PERSISTENCE_SESSION: return OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_SESSION; case PERSISTENCE_FULL: return OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_ALWAYS; default: OP_ASSERT(!"Unknown persistence value"); case PERSISTENCE_NONE: return OpPermissionListener::PermissionCallback::PERSISTENCE_TYPE_NONE; } } BOOL3 ToBool3(UserConsentType consent) { return static_cast<BOOL3>(consent); } UserConsentType ToUserConsentType(BOOL3 is_allowed) { return static_cast<UserConsentType>(is_allowed); } #endif // SECMAN_USERCONSENT
#pragma once #ifndef functions #define functions #include <vector> std::vector<float> posFromLightHouse(float gamma, float theta); std::vector<float> equationSystem(float a, float b, float c, float ap, float bp, float cp); float Gamma(float scanning_G_D, float period); float Theta(float scanning_B_H, float period); std::vector<float> controLimit(std::vector<float> XYZ, float width, float heigth, float depth); #endif
#include <CQNascom.h> #include <CNascom.h> #include <CQZ80Dbg.h> #include <CArgs.h> #include <CQApp.h> #include <CQImageUtil.h> #include <CQUtil.h> #include <CQUtilEvent.h> #include <CQUtilRGBA.h> #include <CImageLib.h> #include <QWidget> #include <QPainter> #include <QTimer> int main(int argc, char **argv) { CQApp app(argc, argv); CArgs cargs("-v:f (verbose) " "-dump:f (enable dump) " "-bin:f (input file is binary) " "-snapshot:f (input file is snapshot) " "-icount:f (output instruction counts on exit) " "-invert:f (invert screen colors) " "-scale:i=1 (scale factor) " "-debug:f (debug) " "-chars:s (file containg charset image - 128x256 xpm) " ); cargs.parse(&argc, argv); bool verbose = cargs.getBooleanArg("-v"); bool dump = cargs.getBooleanArg("-dump"); bool bin = cargs.getBooleanArg("-bin"); bool snapshot = cargs.getBooleanArg("-snapshot"); //bool icount = cargs.getBooleanArg("-icount"); bool invert = cargs.getBooleanArg("-invert"); int scale = cargs.getIntegerArg("-scale"); bool debug = cargs.getBooleanArg("-debug"); std::string chars = cargs.getStringArg ("-chars"); CNascom *nascom = new CNascom; CZ80 *z80 = nascom->getZ80(); z80->setVerbose(verbose); z80->setDump(dump); nascom->setInvert(invert); nascom->setScale (scale ); //------ int border = 4*scale; int w = scale*nascom->getScreenPixelWidth () + 2*border; int h = scale*nascom->getScreenPixelHeight() + 2*border; CQNascom *qnascom = new CQNascom(nascom, w, h); //qnascom->setWindowTitle("Nascom II Emulator"); z80->setScreen(qnascom); //------ for (int i = 1; i < argc; ++i) { if (bin) z80->loadBin(argv[i]); else if (snapshot) z80->loadSnapshot(argv[i]); else z80->load(argv[i]); } if (! snapshot) z80->setPC(0); if (chars != "") nascom->loadChars(chars); qnascom->show(); //------ if (debug) qnascom->addDebug(); //------ if (! debug) qnascom->exec(); return app.exec(); } //------ CQNascom:: CQNascom(CNascom *nascom, int w, int h) : CZ80Screen(*nascom->getZ80()), nascom_(nascom), border_(0) { setFocusPolicy(Qt::StrongFocus); border_ = 4*nascom->getScale(); resize(w, h); } CQNascom:: ~CQNascom() { } void CQNascom:: exec() { timer_ = new QTimer; connect(timer_, SIGNAL(timeout()), this, SLOT(timeOut())); timer_->start(1); } CQZ80Dbg * CQNascom:: addDebug() { if (! dbg_) { dbg_ = new CQZ80Dbg(nascom_->getZ80()); dbg_->init(); QFont fixedFont("Courier New", 16); dbg_->setFixedFont(fixedFont); } dbg_->show(); dbg_->raise(); return dbg_; } void CQNascom:: screenMemChanged(ushort start, ushort len) { #if 0 renderer->startDoubleBuffer(); int x, y; ushort pos1 = pos; ushort pos2 = pos + len - 1; for (ushort pos = pos1; pos <= pos2; ++pos) if (nascom->getScreenPos(pos, &x, &y)) { uchar c = z80.getByte(pos); int px = scale*nascom->getCharWidth ()*x + border; int py = scale*nascom->getCharHeight()*y + border; renderer->drawImage(px, py, getCharImage(c)); } renderer->endDoubleBuffer(); #endif if (nascom_->onScreen(start, len)) update(); } void CQNascom:: redraw() { update(); } void CQNascom:: paintEvent(QPaintEvent *) { //renderer->startDoubleBuffer(); QPainter painter(this); CQNascomRenderer nrenderer(this, &painter); nascom_->draw(&nrenderer, border_); //renderer->endDoubleBuffer(); } void CQNascom:: keyPressEvent(QKeyEvent *e) { CKeyEvent *kevent = CQUtil::convertEvent(e); CKeyType type = kevent->getType(); CZ80 *z80 = nascom_->getZ80(); if (type == CKEY_TYPE_Escape) exit(0); else if (type == CKEY_TYPE_F1) z80->saveSnapshot(); else if (type == CKEY_TYPE_F2) z80->resetOpCounts(); else z80->keyPress(*kevent); } void CQNascom:: keyReleaseEvent(QKeyEvent *e) { CKeyEvent *kevent = CQUtil::convertEvent(e); CKeyType type = kevent->getType(); if (type == CKEY_TYPE_Escape || type == CKEY_TYPE_F1 || type == CKEY_TYPE_F2) return; CZ80 *z80 = nascom_->getZ80(); z80->keyRelease(*kevent); } void CQNascom:: timeOut() { doSteps(); } void CQNascom:: doSteps() { CZ80 *z80 = nascom_->getZ80(); for (uint i = 0; i < 1000; ++i) z80->step(); } //------------ void CQNascomRenderer:: clear(const CRGBA &bg) { painter_->fillRect(qnascom_->rect(), QBrush(CQUtil::rgbaToColor(bg))); } void CQNascomRenderer:: drawImage(int x, int y, CImagePtr image) { painter_->drawImage(x, y, CQImageUtil::toQImage(image)); }
// Created by: Peter KURNEV // 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 BOPDS_CoupleOfPaveBlocks_HeaderFile #define BOPDS_CoupleOfPaveBlocks_HeaderFile #include <BOPDS_PaveBlock.hxx> /** * The Class BOPDS_CoupleOfPaveBlocks is to store * the information about two pave blocks * and some satellite information * */ //======================================================================= //class : BOPDS_CoupleOfPaveBlocks //purpose : //======================================================================= class BOPDS_CoupleOfPaveBlocks { public: /** * Constructor */ BOPDS_CoupleOfPaveBlocks() : myIndexInterf(-1), myIndex(-1), myTolerance(0) {} // /** * Constructor * @param thePB1 * first pave block * @param thePB2 * secondt pave block */ BOPDS_CoupleOfPaveBlocks(const Handle(BOPDS_PaveBlock)& thePB1, const Handle(BOPDS_PaveBlock)& thePB2) : myIndexInterf(-1), myIndex(-1), myTolerance(0) { SetPaveBlocks(thePB1, thePB2); } // /** * Destructor */ ~BOPDS_CoupleOfPaveBlocks() { } // /** * Sets an index * @param theIndex * index */ void SetIndex(const Standard_Integer theIndex) { myIndex=theIndex; } // /** * Returns the index * @return * index */ Standard_Integer Index()const { return myIndex; } // /** * Sets an index of an interference * @param theIndex * index of an interference */ void SetIndexInterf(const Standard_Integer theIndex) { myIndexInterf=theIndex; } // /** * Returns the index of an interference * @return * index of an interference */ Standard_Integer IndexInterf()const { return myIndexInterf; } // /** * Sets pave blocks * @param thePB1 * first pave block * @param thePB2 * secondt pave block */ void SetPaveBlocks(const Handle(BOPDS_PaveBlock)& thePB1, const Handle(BOPDS_PaveBlock)& thePB2) { myPB[0]=thePB1; myPB[1]=thePB2; } // /** * Returns pave blocks * @param thePB1 * the first pave block * @param thePB2 * the second pave block */ void PaveBlocks(Handle(BOPDS_PaveBlock)& thePB1, Handle(BOPDS_PaveBlock)& thePB2) const { thePB1=myPB[0]; thePB2=myPB[1]; } // /** * Sets the first pave block * @param thePB * the first pave block */ void SetPaveBlock1(const Handle(BOPDS_PaveBlock)& thePB) { myPB[0]=thePB; } /** * Returns the first pave block * @return * the first pave block */ const Handle(BOPDS_PaveBlock)& PaveBlock1()const { return myPB[0]; } // /** * Sets the second pave block * @param thePB * the second pave block */ void SetPaveBlock2(const Handle(BOPDS_PaveBlock)& thePB) { myPB[1]=thePB; } // /** * Returns the second pave block * @return * the second pave block */ const Handle(BOPDS_PaveBlock)& PaveBlock2()const { return myPB[1]; } /** * Sets the tolerance associated with this couple */ void SetTolerance(const Standard_Real theTol) { myTolerance = theTol; } // /** * Returns the tolerance associated with this couple */ Standard_Real Tolerance()const { return myTolerance; } protected: Standard_Integer myIndexInterf; Standard_Integer myIndex; Handle(BOPDS_PaveBlock) myPB[2]; Standard_Real myTolerance; }; // #endif
#include <iostream> #include <vector> #include <map> #include <cmath> #include <cstdlib> #include "common.h" using namespace std; /** * Day 10 - Monitoring Station * */ class Asteroid { public: unsigned int x = 0; unsigned int y = 0; unsigned int nrOfViews = 0; double angle; unsigned int distance; bool alive = true; Asteroid(unsigned int x, unsigned int y) : x(x), y(y) { } }; /** * I'm sure there is a more elegant and efficient way to calculate a 2*PI / 360° * angle of a directed line.... but for now that is the safe way. * * Also, I could use Radiants, but I can better imagine Degree angles in my head, * therefore the calcs: */ double calcAngle(Asteroid *from, Asteroid *to) { int dx = abs((int)from->x - (int)to->x); int dy = abs((int)from->y - (int)to->y); // 0°: to is directly north from: if (dx == 0 && to->y < from->y) return 0.0; // 90°: to is horizontal right of from: if (dy == 0 && to->x > from->x) return 90.0; // 180°: to is directly south from from: if (dx == 0 && to->y > from->y) return 180.0; // 270°: to is directly west from from: if (dy == 0 && to->x < from->x) return 270.0; double slope = (double)dy / double(dx); // top right quadrant: if (to->x > from->x && to->y < from->y) { return 90 - atan(slope) * 180 / M_PI; } // bottom right quadrant: if (to->x > from->x && to->y > from->y) { return 90 + atan(slope) * 180 / M_PI; } // bottom left quadrant: if (to->x < from->x && to->y > from->y) { return 270 - atan(slope) * 180 / M_PI; } // top left quadrant: if (to->x < from->x && to->y < from->y) { return 270 + atan(slope) * 180 / M_PI; } cerr << "You should never reach this far!" << endl; exit(1); return 0.0; } int calcDistance(Asteroid *from, Asteroid *to) { return abs((int)from->x - (int)to->x) + abs((int)from->y - (int)to->y); } /** * Idea: A line is a triangle of an x and y axis. y is a fn of x: * yd and yd is the distance in x/y values from one asteroid to the other, * then is an y for each x on that line: * * y = f(x) -> x * (yd / xd) */ bool hasLineOfSight(Asteroid *a, Asteroid *b, vector<vector<char>> &field) { Asteroid *left = a->x <= b->x ? a : b; Asteroid *right = a->x <= b->x ? b : a; int dx = right->x - left->x; int dy = right->y - left->y; double slope = dx > 0 ? (double)dy / (double)dx : 0; double y = 0; double tmp; unsigned int testX, testY; // cout << "Test distances: x:" << dx << ", y: " << dy << endl; if (dx > 0) { // non-vertical line for (unsigned int x = 1; x < dx; ++x) { y = (double)x * slope; // cout << "Test x:y:slope " << x << ":" << y << ":" << slope << endl; // check for an exact (whole number) y: if (modf(y, &tmp) == 0) { testX = x + left->x; testY = (int)y + left->y; // cout << "Test x:y:slope " << testX << ":" << testY << ":" << slope << ":" << field[testY][testX]<< endl; // cout << "1: x: " << testX << "y: " << testX << endl; if (field[testY][testX] == '#') { return false; } } } } else { // vertical line, just check y line for (unsigned int y = min(left->y, right->y) + 1; y < max(left->y, right->y); ++y) { if (field[y][left->x] == '#') { return false; } } } return true; } Asteroid *findNearest(vector<Asteroid *> &list) { Asteroid *nearest = nullptr; for (auto a : list) { if (a->alive) { if (nearest == nullptr || nearest->distance > a->distance) { nearest = a; } } } return nearest; } int main(int argc, char *args[]) { if (argc < 2) { cerr << "Error: give input file on command line" << endl; exit(1); } // Read input file: vector<string> fileData; readData<string>(args[1], '\n', fileData); // field is the asteroid field, field[y][x] unsigned int width = fileData[0].length(); unsigned int height = fileData.size(); vector<vector<char>> field; vector<Asteroid *> asteroids; // read in field: for (vector<string>::size_type y = 0; y < height; ++y) { vector<char> line; for (string::size_type x = 0; x < width; ++x) { line.push_back(fileData[y][x]); if (fileData[y][x] == '#') { asteroids.push_back(new Asteroid(x, y)); } } field.push_back(line); } // cout << "List of asteroids:" << endl; // int counter = 0; // for (auto a : asteroids) // { // cout << counter++ << ": " << a->x << ":" << a->y << endl; // } // cout << "Asteroid field:" << endl; // for (vector<string>::size_type y = 0; y < height; ++y) // { // for (string::size_type x = 0; x < width; ++x) // { // cout << field[y][x]; // } // cout << endl; // } /** * Calculate the number of sights for each asteroid: * check every other asteroid if it is in the actual's line of sight. * If so, increates sight counter on both asteroids. * Repeat for every asteroid for all of its companions */ for (unsigned int aI = 0; aI < asteroids.size(); ++aI) { for (unsigned int bI = aI + 1; bI < asteroids.size(); ++bI) { if (hasLineOfSight(asteroids[aI], asteroids[bI], field)) { (asteroids[aI])->nrOfViews++; (asteroids[bI])->nrOfViews++; } } } // Find the one with the most counts: unsigned int maxSights = 0; Asteroid *bestAsteroid = nullptr; for (auto a : asteroids) { if (a->nrOfViews > maxSights) { maxSights = a->nrOfViews; bestAsteroid = a; } } cout << "Solution 1: Best asteroid is " << bestAsteroid->x << ":" << bestAsteroid->y << " with " << bestAsteroid->nrOfViews << " sights." << endl; // Solution 2 /** * Brain dump: * 1. Calculate the angle and distance of the line from the best asteroid to all other asteroids, save it on the asteroid * 2. create a sorted list of all (unique) angles * 3. create a map of angles -> list of asteroids * 4. loop through the list of angles, take the nearest asteroid per angle, destroy it, count it * 5. loop until 200 asteroids are destroyed. */ map<double, vector<Asteroid *>> angleMap; vector<double> angleList; // Calculate angle and distance to the best-placed asteroid from Solution 1: // Store the angle and distance values on each asteroid: // At the same time, create a list with all angles found, // and store each asteroid in an angle -> [asteroid] map, // to process them later: for (auto a : asteroids) { if (a != bestAsteroid) { a->distance = calcDistance(bestAsteroid, a); a->angle = calcAngle(bestAsteroid, a); if (angleMap.find(a->angle) == angleMap.end()) { angleMap[a->angle] = vector<Asteroid *>(); angleList.push_back(a->angle); } angleMap[a->angle].push_back(a); } } // Sort angle list, so that they can be processed from smallest to largest: sort(angleList.begin(), angleList.end()); int asteroidCounter = 0; unsigned int angleIndex = 0; double actAngle = 0; Asteroid *act = nullptr; // Destroy asteroids, one by one (or, angle by angle, while destroying one per angle/round) while (asteroidCounter < 200) { actAngle = angleList[angleIndex]; act = findNearest(angleMap[actAngle]); if (act != nullptr) { act->alive = false; asteroidCounter++; } angleIndex = (angleIndex + 1) % angleList.size(); } cout << "Asteroid " << asteroidCounter << "found: " << act->x << ":" << act->y << endl; cout << "Solution 2: " << (act->x * 100 + act->y) << endl; }
// // Created by Alejandro Ibarra on 2019-03-07. // #include "Node.h"
// // include: convert.h // // last update: '18.xx.xx // author: matchey // // memo: // #ifndef PERFECT_VELODYNE_CONVERT_H #define PERFECT_VELODYNE_CONVERT_H #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <dynamic_reconfigure/server.h> #include <perfect_velodyne/CloudNodeConfig.h> #include "perfect_velodyne/rawdata.h" namespace perfect_velodyne { class ConvertWithNormal { bool flag_pub_org; void callback(perfect_velodyne::CloudNodeConfig &config, uint32_t level); void processScan(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg); ///Pointer to dynamic reconfigure service srv_ boost::shared_ptr<dynamic_reconfigure::Server<perfect_velodyne:: CloudNodeConfig> > srv_; boost::shared_ptr<perfect_velodyne::RawDataWithNormal> data_; ros::Subscriber velodyne_scan_; ros::Publisher output_; ros::Publisher output_org_; /// configuration parameters typedef struct { int npackets; ///< number of packets to combine } Config; Config config_; public: ConvertWithNormal(ros::NodeHandle node, ros::NodeHandle private_nh); ~ConvertWithNormal() {} }; } // namespace perfect_velodyne #endif
/** * \file hello_world.cpp the hello_world example for expatpp library * * See LICENSE for copyright information. */ #include <iostream> #include "expatpp.hpp" using std::cout; using std::endl; /** a parser delegate which extracts the character data from an xml element*/ class element_delegate : public xmlpp::abstract_delegate { public: std::string fullname; std::string characterData; void onStartElement( const XML_Char *fullname, const XML_Char **atts) override { this->fullname = fullname; } void onCharacterData(const char *pBuf, int len) override { characterData.append(pBuf,len); } }; int main(int argc,char** argv) { // prepare xml input, const char* xml = "<p>hello world!</p>"; // use the delegate to extract character data from input string element_delegate d; // parse xml input using delegate d's callbacks xmlpp::parser::result res = xmlpp::parser::parseString(xml,d); switch(res) { case xmlpp::parser::result::OK: // and output the extracted data in case of successful parsing cout << "element " << d.fullName << endl << " contains this text: "<< d.characterData << endl; return EXIT_SUCCESS; default: cout << "error " << static_cast<int>(res) << " on parsing " << endl; return -static_cast<int>(res); } }
#include "Sphere.h" #include <OgreEntity.h> #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreMeshManager.h> #ifndef __Room_h_ #define __Room_h_ class Room { public: int roomHeight; int roomLength; int roomWidth; int xOffset; int yOffset; int zOffset; Room(); Room(Ogre::SceneManager *newManager); Room(int xyz, Ogre::SceneManager *newManager); Room(int x, int y, int z, Ogre::SceneManager *newManager); void checkCollide(Sphere* ball); void checkCollide(Sphere* ball, Sphere* ball2); private: Ogre::Entity* groundEntity; Ogre::Entity* wallEntity; Ogre::SceneNode* wallNode; Ogre::Entity* wallEntity2; Ogre::SceneNode* wallNode2; Ogre::Entity* wallEntity3; Ogre::SceneNode* wallNode3; Ogre::Entity* wallEntity4; Ogre::SceneNode* wallNode4; Ogre::Entity* roofEntity; Ogre::SceneNode* roofNode; Ogre::SceneManager *roomManager; void buildRoom(); }; #endif // #ifndef __Room_h_
#pragma once #include <eotiolib/memory.hpp> #include <eotiolib/stdlib.hpp> #include <vector> namespace eotio { using std::vector; typedef std::vector<char> bytes; } /// namespace eotio
#include <iostream> #include <string> #include <vector> #include <cstring> #include "Trigger.h" #include "../rapidxml/rapidxml.hpp" #include "../rapidxml/rapidxml_utils.hpp" #include "../rapidxml/rapidxml_print.hpp" using namespace std; using namespace rapidxml; Trigger::Trigger(xml_node<> * triggerTag){ xml_node<> * triggerElement = NULL; for(triggerElement = triggerTag->first_node(); triggerElement; triggerElement = triggerElement->next_sibling()){ if(strcmp(triggerElement->name(),"type") == 0){ type = triggerElement->value(); } if(strcmp(triggerElement->name(),"print") == 0){ print = triggerElement->value(); } if(strcmp(triggerElement->name(),"command") == 0){ command = triggerElement->value(); } if(strcmp(triggerElement->name(),"action") == 0){ action.push_back(triggerElement->value()); } if(strcmp(triggerElement->name(),"condition") == 0){ xml_node<> * conditionElements = NULL; for(conditionElements = triggerElement->first_node(); conditionElements; conditionElements= conditionElements->next_sibling()){ if(strcmp(conditionElements->name(),"object") == 0){ condition.object = conditionElements->value(); } if(strcmp(conditionElements->name(),"status") == 0){ condition.status = conditionElements->value(); } if(strcmp(conditionElements->name(),"has") == 0){ condition.has = conditionElements->value(); } if(strcmp(conditionElements->name(),"owner") == 0){ condition.owner = conditionElements->value(); } } } } } void Trigger::setType(string type){ this->type = type; } string Trigger::getType(){ return type; } void Trigger::setPrint(string print){ this->print = print; } string Trigger::getPrint(){ return print; } void Trigger::setCommand(string command){ this->command = command; } string Trigger::getCommand(){ return command; } void Trigger::setAction(string action){ (this->action).push_back(action); } vector<string> Trigger::getAction(){ return action; } void Trigger::setCondition(string object, string status, string has, string owner){ Condition condition; condition.object = object; condition.status = status; condition.has = has; condition.owner = owner; this->condition = condition; } Condition Trigger::getCondition(){ return condition; }
// // talkcases.cpp // AutoCaller // // Created by Micheal Chen on 2017/8/2. // // #include "talkcases.hpp" #include "YouMeHttpRequest.hpp" #include "YMRenderTexture.h" #include "YouMeTalk.h" void TalkCasesController::init() { SetServerMode(SERVER_MODE_TEST); IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); //engine->setTCPMode(1); engine->init(this, TALK_APPKEY, TALK_APPSECRET, RTC_CN_SERVER, ""); } TalkCasesController::TalkCasesController() { m_robotuser = YoumeUtil::getRandUserName(); //::initfile(); YoumeUtil::clear_sdk_log_file(); // const char * appkey = "YOUME5BE427937AF216E88E0F84C0EF148BD29B691556"; // const char * appsecret = "y1sepDnrmgatu/G8rx1nIKglCclvuA5tAvC0vXwlfZKOvPZfaUYOTkfAdUUtbziW8Z4HrsgpJtmV/RqhacllbXD3abvuXIBlrknqP+Bith9OHazsC1X96b3Inii6J7Und0/KaGf3xEzWx/t1E1SbdrbmBJ01D1mwn50O"; } TalkCasesController::~TalkCasesController() { if (_run_thread.joinable()) _run_thread.join(); } void TalkCasesController::onPcmData(int channelNum, int samplingRateHz, int bytesPerSample, void *data, int dataSizeInByte) { } void TalkCasesController::onRequestRestAPI(int requestID, const YouMeErrorCode &iErrorCode, const char* strQuery, const char* strResult) { } void TalkCasesController::onBroadcast(const YouMeBroadcast bc, const char *channel, const char *param1, const char *param2, const char *strContent) { } void TalkCasesController::OnCustomDataNotify(const void *pData, int iDataLen, unsigned long long ulTimeSpan) { log("recv data : %s", (char *)pData); log("time stamp : %lld", ulTimeSpan); log("data len: %d", iDataLen); } /** void TalkCasesController::frameRender(int renderId, int nWidth, int nHeight, int nRotationDegree, int nBufSize, const void *buf) { cocos2d::log("call frame rander"); } **/ //talk callback //这里是talk的回调函数 void TalkCasesController::onEvent(const YouMeEvent event, const YouMeErrorCode error, const char *channel, const char *param) { cocos2d::log("Callback onevent !"); //cocos2d::log("channel is %s", channel); switch (event) { case YOUME_EVENT_INIT_OK: { EXPECT_EQ("初始化成功", "初始化成功回调", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_JOIN_OK:{ EXPECT_EQ("加入房间成功", "YOUME_EVENT_JOIN_OK", error, YOUME_SUCCESS); YouMeErrorCode code = IYouMeVoiceEngine::getInstance()->startCapture(); if (code != YOUME_SUCCESS) { cocos2d::log("采集失败"); } m_cv.notify_one(); break; } case YOUME_EVENT_JOIN_FAILED: { EXPECT_EQ("加入房间失败;", "回调:YOUME_EVENT_JOIN_FAILED", error, YOUME_SUCCESS); //if (error == YOUME_SUCCESS) m_cv.notify_one(); } break; case YOUME_EVENT_RESUMED: { EXPECT_EQ("恢复通话回调", "回调:YOUME_EVENT_RESUMED", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_LEAVED_ALL: { EXPECT_EQ("离开所有房间回调;", "回调:YOUME_EVENT_LEAVED_ALL", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_BGM_FAILED: { EXPECT_EQ("背景音乐播放失败", "回调:YOUME_EVENT_BGM_FAILED", error, YOUME_ERROR_STOP_FAILED); m_cv.notify_one(); } break; case YOUME_EVENT_MIC_CTR_ON: break; case YOUME_EVENT_LEAVED_ONE: { EXPECT_EQ("离开一个房间", "回调:YOUME_EVENT_LEAVED_ONE", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_PAUSED: { EXPECT_EQ("停止通话回调", "回调:YOUME_EVENT_PAUSED", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_BGM_STOPPED: { EXPECT_EQ("停止播放背景音乐回调", "YOUME_EVENT_BGM_STOPPED", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_INIT_FAILED: { EXPECT_EQ("初始化失败回调", "回调:YOUME_EVENT_INIT_FAILED", error, YOUME_SUCCESS); } break; case YOUME_EVENT_MIC_CTR_OFF: { EXPECT_EQ("麦克风被其他用户关闭", "回调:YOUME_EVENT_MIC_CTR_OFF", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_RECONNECTED: { cocos2d::log("断网重连成功"); m_cv.notify_one(); } break; case YOUME_EVENT_MY_MIC_LEVEL: break; case YOUME_EVENT_OTHERS_MIC_ON: { EXPECT_EQ("其他用户麦克风打开", "回调:YOUME_EVENT_OTHERS_MIC_ON", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_RECONNECTING: { EXPECT_EQ("网络在重连", "回调: YOUME_EVENT_RECONNECTING", error, YOUME_SUCCESS); m_cv.notify_one(); break; } case YOUME_EVENT_SPEAK_SUCCESS: { EXPECT_EQ("切换对指定频道讲话成功", "回调:YOUME_EVENT_SPEAK_SUCCESS", error, YOUME_SUCCESS); cocos2d::log("[Youme Test]Callback: switch channel to speak success!"); m_cv.notify_one(); } break; case YOUME_EVENT_SPEAK_FAILED:{ cocos2d::log("[Youme Test]Callback: switch channel to speak failed!"); EXPECT_EQ("切换对指定频道讲话失败", "回调:YOUME_EVENT_SPEAK_FAILED", error, YOUME_SUCCESS); m_cv.notify_one(); break; } case YOUME_EVENT_OTHERS_MIC_OFF:{ EXPECT_EQ("其他用户麦克风关闭", "回调:YOUME_EVENT_OTHERS_MIC_OFF", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_SPEAKER_CTR_ON: { cocos2d::log("My speaker is open by other users"); } break; case YOUME_EVENT_LISTEN_OTHER_ON: { } break; case YOUME_EVENT_OTHERS_VOICE_ON: cocos2d::log("Other listener is no mute. They cann talk...."); break; case YOUME_EVENT_SPEAKER_CTR_OFF: { cocos2d::log("My speaker is closed by other users"); } break; case YOUME_EVENT_LISTEN_OTHER_OFF: cocos2d::log("Other lisener is off:"); break; case YOUME_EVENT_OTHERS_VOICE_OFF: cocos2d::log("Other lisener is mute: "); break; case YOUME_EVENT_OTHERS_SPEAKER_ON: { cocos2d::log("Others speaker opened! [[====]]"); m_cv.notify_one(); } break; case YOUME_EVENT_OTHERS_SPEAKER_OFF: cocos2d::log("Others speaker closed! [[====]]"); break; case YOUME_EVENT_SEND_MESSAGE_RESULT: { EXPECT_EQ("发送文本消息结果通知", "回调: YOUME_EVENT_SEND_MESSAGE_RESULT", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_MESSAGE_NOTIFY: { EXPECT_EQ("收到文本消息通知", "回调: YOUME_EVENT_MESSAGE_NOTIFY", error, YOUME_SUCCESS); m_cv.notify_one(); break; } case YOUME_EVENT_INVITEMIC_SETOPT_OK: { //主播身份才能连麦设置成功 EXPECT_EQ("连麦设置成功,回调", "回调:YOUME_EVENT_INVITEMIC_SETOPT_OK", error, YOUME_SUCCESS); cocos2d::log("连麦设置成功了"); m_cv.notify_one(); break; } case YOUME_EVENT_INVITEMIC_SETOPT_FAILED: { EXPECT_EQ("连麦设置失败", "回调:YOUME_EVENT_INVITEMIC_SETOPT_FAILED", error, YOUME_SUCCESS); cocos2d::log("连麦设置失败了"); m_cv.notify_one(); break; } case YOUME_EVENT_GRABMIC_START_OK: //33 { EXPECT_EQ("抢麦活动开始", "回调:YOUME_EVENT_GRABMIC_START_OK", error, YOUME_SUCCESS); cocos2d::log("抢麦活动开始"); m_cv.notify_one(); break; } case YOUME_EVENT_GRABMIC_STOP_OK: { EXPECT_EQ("抢麦活动停止", "回调:YOUME_EVENT_GRABMIC_STOP_OK", error, YOUME_SUCCESS); cocos2d::log("抢麦活动停止"); m_cv.notify_one(); break; } case YOUME_EVENT_INVITEMIC_REQUEST_OK: { EXPECT_EQ("请求连麦成功", "回调:YOUME_EVENT_INVITEMIC_REQUEST_OK", error, YOUME_SUCCESS); cocos2d::log("请求连麦成功"); m_cv.notify_one(); break; } case YOUME_EVENT_GRABMIC_STOP_FAILED: { EXPECT_EQ("请求连麦失败", "回调:YOUME_EVENT_GRABMIC_STOP_FAILED", error, YOUME_SUCCESS); cocos2d::log("请求连麦失败"); m_cv.notify_one(); break; } case YOUME_EVENT_GRABMIC_REQUEST_WAIT: { EXPECT_EQ("进入抢麦等待队列(权重模式)", "回调:YOUME_EVENT_GRABMIC_REQUEST_WAIT", error, YOUME_SUCCESS); } break; case YOUME_EVENT_INVITEMIC_RESPONSE_OK: { cocos2d::log("响应连麦成功"); } break; case YOUME_EVENT_INVITEMIC_RESPONSE_FAILED: { cocos2d::log("响应连麦失败"); } break; case YOUME_EVENT_INVITEMIC_STOP_OK: { cocos2d::log("停止连麦成功"); m_cv.notify_one(); } break; case YOUME_EVENT_INVITEMIC_STOP_FAILED: { cocos2d::log("停止连麦失败"); EXPECT_EQ("停止连麦失败", "回调:YOUME_EVENT_INVITEMIC_STOP_FAILED", error, YOUME_SUCCESS); m_cv.notify_one(); break; } case YOUME_EVENT_INVITEMIC_CAN_TALK: { cocos2d::log("双方可以通话了"); EXPECT_EQ("双方可以通话了,回调", "回调:YOUME_EVENT_INVITEMIC_CAN_TALK", error, YOUME_SUCCESS); m_cv.notify_one(); break; } case YOUME_EVENT_INVITEMIC_CANNOT_TALK : { cocos2d::log("双方不能通话了"); EXPECT_EQ("通话停止回调", "回调:YOUME_EVENT_INVITEMIC_CANNOT_TALK", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_INVITEMIC_NOTIFY_CALL: { cocos2d::log("有人请求与你连麦"); EXPECT_EQ("有人请求与你连麦", "回调:YOUME_EVENT_INVITEMIC_NOTIFY_CALL", error, YOUME_SUCCESS); } break; case YOUME_EVENT_INVITEMIC_NOTIFY_ANSWER: { cocos2d::log("对方对你的连麦请求作出了响应"); EXPECT_EQ("对方对你的连麦请求作出了响应", "回调:YOUME_EVENT_INVITEMIC_NOTIFY_CALL", error, YOUME_SUCCESS); } break; case YOUME_EVENT_INVITEMIC_NOTIFY_CANCEL: { cocos2d::log("连麦过程中,对方结束了连麦或者连麦时间到"); EXPECT_EQ("连麦过程中,对方结束了连麦或者连麦时间到", "回调:YOUME_EVENT_INVITEMIC_NOTIFY_CANCEL", error, YOUME_SUCCESS); break; } case YOUME_EVENT_GRABMIC_NOTIFY_START: { cocos2d::log("抢麦活动开始"); EXPECT_EQ("抢麦活动开始", "回调:YOUME_EVENT_GRABMIC_NOTIFY_START", error, YOUME_SUCCESS); } break; case YOUME_EVENT_GRABMIC_NOTIFY_STOP: { cocos2d::log("抢麦活动结束"); EXPECT_EQ("抢麦活动结束", "回调:YOUME_EVENT_GRABMIC_NOTIFY_STOP", error, YOUME_SUCCESS); } break; case YOUME_EVENT_LOCAL_SPEAKER_OFF: { cocos2d::log("我方扬声器关闭"); EXPECT_EQ("我方扬声器关闭", "回调:YOUME_EVENT_LOCAL_SPEAKER_OFF", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_LOCAL_SPEAKER_ON: { cocos2d::log("我方扬声器打开"); EXPECT_EQ("我方扬声器打开", "回调:YOUME_EVENT_LOCAL_SPEAKER_ON", error, YOUME_SUCCESS); m_cv.notify_one(); } break; case YOUME_EVENT_OTHERS_VIDEO_INPUT_START: { cocos2d::log("其他用户视频输入开始"); EXPECT_EQ("其他用户视频输入开始", "回调:YOUME_EVENT_OTHERS_VIDEO_INPUT_START", error, YOUME_SUCCESS); } break; case YOUME_EVENT_OTHERS_VIDEO_INPUT_STOP: { cocos2d::log("其他用户输入停止"); EXPECT_EQ("其他用户视频输入开始", "回调:YOUME_EVENT_OTHERS_VIDEO_INPUT_STOP", error, YOUME_SUCCESS); break; } case YOUME_EVENT_MEDIA_DATA_ROAD_PASS: { cocos2d::log("音视频数据通路连通"); EXPECT_EQ("音视频数据通路连通", "回调:YOUME_EVENT_MEDIA_DATA_ROAD_PASS", error, YOUME_SUCCESS); break; } case YOUME_EVENT_MEDIA_DATA_ROAD_BLOCK: { cocos2d::log("音视频数据通路不通"); EXPECT_EQ("音视频数据通路不通", "回调:YOUME_EVENT_MEDIA_DATA_ROAD_BLOCK", error, YOUME_SUCCESS); break; } case YOUME_EVENT_MASK_VIDEO_FOR_USER: { //屏蔽了某某的视屏 cocos2d::log("屏蔽了某某的视屏"); EXPECT_EQ("屏蔽了某用户的视频", "回调:YOUME_EVENT_RESUME_VIDEO_FOR_USER", error, YOUME_SUCCESS); break; } case YOUME_EVENT_RESUME_VIDEO_FOR_USER: { //恢复了某用户的视频 cocos2d::log("恢复了某用户的视频"); EXPECT_EQ("恢复了某用户的视频", "回调:YOUME_EVENT_RESUME_VIDEO_FOR_USER", error, YOUME_SUCCESS); break; } case YOUME_EVENT_OTHERS_VIDEO_SHUT_DOWN: { cocos2d::log("视频断开"); EXPECT_EQ("视频断开回调", "回调:YOUME_EVENT_OTHERS_VIDEO_SHUT_DOWN", error, YOUME_SUCCESS); break; } case YOUME_EVENT_OTHERS_VIDEO_ON: { //其他用户的视频流打开 cocos2d::log("其他用户的视频流打开"); EXPECT_EQ("其他用户的视频流打开", "回调:YOUME_EVENT_OTHERS_VIDEO_ON",0, 0); break; } default: break; } } void TalkCasesController::actionUninit() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->unInit(); EXPECT_EQ("反初始化", "unInit", code, YOUME_SUCCESS); } void TalkCasesController::startTest() { _run_thread = std::thread(&TalkCasesController::testThreadFunc, this); _run_thread.detach(); } void TalkCasesController::testTalkMode() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); //自由通话模式 { std::unique_lock<std::mutex> lk(m_mutex); actionJoinSingleRoom(); m_cv.wait_for(lk, std::chrono::seconds(10)); //设置用户角色 YouMeErrorCode code = engine->setUserRole(YOUME_USER_TALKER_FREE); EXPECT_EQ("设置用户说话时的角色", "setUserRole", code, YOUME_SUCCESS); EXPECT_EQ("获取用户说话时的角色", "getUserRole", engine->getUserRole(), YOUME_USER_TALKER_FREE) ; } // 扬声器控制 { //关闭扬声器 IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); std::unique_lock<std::mutex> lk(m_mutex); engine->setSpeakerMute(true); std::chrono::seconds(5); m_cv.wait_for(lk, std::chrono::seconds(5)); bool status1 = engine->getSpeakerMute(); //获取扬声器状态 EXPECT_EQ("获取静音状态,关闭扬声器", "getSpeakerMute", status1, true); //lk.unlock(); } { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); std::unique_lock<std::mutex> lk2(m_mutex); engine->setSpeakerMute(false); //打开扬声器 m_cv.wait_for(lk2, std::chrono::seconds(10)); std::this_thread::sleep_for(std::chrono::seconds(10)); bool status2 = engine->getSpeakerMute(); //获取扬声器状态 EXPECT_EQ("设置静音状态,打开扬声器", "getSpeakerMute", status2, false); } //输出到扬声器 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->setOutputToSpeaker(false); EXPECT_EQ("设置是否输出到扬声器:否", "setOutputToSpeaker", code, YOUME_SUCCESS); YouMeErrorCode code1 = engine->setOutputToSpeaker(true); EXPECT_EQ("设置是否输出到扬声器:是", "setOutputToSpeaker", code1, YOUME_SUCCESS); } //麦克风控制 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); engine->setMicrophoneMute(true); //std::this_thread::sleep_for(std::chrono::seconds(5)); EXPECT_EQ("麦克风控制:关闭麦克风", "setMicrophoneMute", engine->getMicrophoneMute(), true); engine->setMicrophoneMute(false); //打开麦克风 std::this_thread::sleep_for(std::chrono::seconds(10)); EXPECT_EQ("麦克风控制:打开麦克风", "setMicrophoneMute", engine->getMicrophoneMute(), false); } //音量控制 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->playBackgroundMusic(cocos2d::FileUtils::getInstance()->fullPathForFilename("nekomimi.mp3").c_str(), true); if (code == YOUME_SUCCESS) { for (int i = 0; i < 5; ++i) { engine->setVolume(i + 5); std::this_thread::sleep_for(std::chrono::microseconds(50)); } } engine->setVolume(0); EXPECT_EQ("音量控制:设置音量为0,持续5s", "setVolume", (int)engine->getVolume(), 0); std::this_thread::sleep_for(std::chrono::seconds(5)); engine->setVolume(100); EXPECT_EQ("音量控制:设置音量为100,持续5s", "setVolume", (int)engine->getVolume(), 100); std::this_thread::sleep_for(std::chrono::seconds(5)); engine->setVolume(45); EXPECT_EQ("音量控制:设置音量为45,持续5s", "setVolume", (int)engine->getVolume(), 45); std::this_thread::sleep_for(std::chrono::seconds(5)); } //混响控制 { // YouMeErrorCode code1 = engine->playBackgroundMusic(cocos2d::FileUtils::getInstance()->fullPathForFilename("mangetunoyoruniodore.mp3").c_str(), true); //EXPECT_EQ("播放背景音乐", "playBackgroundMusic", code1, YOUME_SUCCESS); for (int i = 0; i < 3; ++i) { YouMeErrorCode code = engine->setReverbEnabled(false); EXPECT_EQ("混响控制:打开混响","setReverbEnabled", code, YOUME_SUCCESS); std::this_thread::sleep_for(std::chrono::seconds(15)); YouMeErrorCode code2 = engine->setReverbEnabled(true); EXPECT_EQ("混响控制:打开混响", "setReverbEnabled", code2, YOUME_SUCCESS); } } { IYouMeVoiceEngine* engine =IYouMeVoiceEngine::getInstance(); engine->setAutoSendStatus(true); EXPECT_EQ("设置是否通知其他人自己的开关麦克风和扬声器的状态:是", "setAutoSendStatus", 0, 0); std::this_thread::sleep_for(std::chrono::seconds(3)); engine->setAutoSendStatus(false); EXPECT_EQ("设置是否通知其他人自己的开关麦克风和扬声器的状态:否", "setAutoSendStatus", 0, 0); } //网络 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); engine->setUseMobileNetworkEnabled(true); EXPECT_EQ("启用移动网络", "setUseMobileNetworkEnabled", 0, 0); std::this_thread::sleep_for(std::chrono::seconds(3)); engine->setUseMobileNetworkEnabled(false); EXPECT_EQ("禁用移动网络", "setUseMobileNetworkEnabled", 0, 0); } //通话控制 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code = engine->pauseChannel(); EXPECT_EQ("通话控制:暂停通话", "pauseChannel", code, YOUME_SUCCESS); cocos2d::log("Pause Wait for callback..."); m_cv.wait_for(lk, std::chrono::seconds(10)); } // 恢复通话 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code = engine->resumeChannel(); EXPECT_EQ("通话控制:恢复通话", "resumeChannel", code, YOUME_SUCCESS); cocos2d::log("Resume Wait for callback..."); m_cv.wait_for(lk, std::chrono::seconds(10)); } //背景音乐播放 // { // IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); // std::unique_lock<std::mutex> lk(m_mutex); // // YouMeErrorCode code = engine->playBackgroundMusic(cocos2d::FileUtils::getInstance()->fullPathForFilename("mangetunoyoruniodore.mp3").c_str(), // true); // engine->setVolume(10); // EXPECT_EQ("背景音乐播放", "playBackgroundMusic", code, YOUME_SUCCESS); // cocos2d::log("playBackgroundMusic Wait for callback..."); // m_cv.wait_for(lk, std::chrono::seconds(10)); // // std::this_thread::sleep_for(std::chrono::seconds(15)); // YouMeErrorCode stopcode = engine->stopBackgroundMusic(); // EXPECT_EQ("停止背景音乐播放", "stopBackgroundMusic", stopcode, YOUME_SUCCESS); // } //监听设置 // { // IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); // YouMeErrorCode code = engine->setHeadsetMonitorOn(true); // EXPECT_EQ("监听控制:打开监听", "setHeadsetMonitorOn", code, YOUME_SUCCESS); // // std::this_thread::sleep_for(std::chrono::seconds(15)); // YouMeErrorCode code1 = engine->setHeadsetMonitorOn(false); // EXPECT_EQ("监听控制:关闭监听", "setHeadsetMonitorOn", code1, YOUME_SUCCESS); // } //控制别人的麦克风 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->setOtherMicMute("1234", true); EXPECT_EQ("控制他人麦克风,让用户静音", "setHeadsetMonitorOn", code, YOUME_SUCCESS); std::unique_lock<std::mutex> lk(m_mutex); cocos2d::log("setOtherMicMute Wait for callback..."); m_cv.wait_for(lk, std::chrono::seconds(5)); } { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code1 = engine->setOtherMicMute("1234", false); EXPECT_EQ("控制他人麦克风,取消用户静音", "setHeadsetMonitorOn", code1, YOUME_SUCCESS); std::unique_lock<std::mutex> lk1(m_mutex); cocos2d::log("setOtherMicMute Wait for callback..."); m_cv.wait_for(lk1, std::chrono::seconds(5)); } //广播 { //YouMeErrorCode sendMessage( const char* pChannelID, const char* pContent, int* requestID ); int reqNumber; YouMeErrorCode code = engine->sendMessage(TALK_CHAT_ROOM, "Test Test Test Test Test", &reqNumber); EXPECT_EQ("发出广播消息", "sendMessage", code, YOUME_SUCCESS); } { //判断用户是否在频道内 bool b = engine->isInChannel(TALK_CHAT_ROOM); log("return code is %d", b); EXPECT_EQ("判断用户是否在一个频道内", "isInChannel", b, true); bool b2 = engine->isInChannel("1234567890"); EXPECT_EQ("判断用户是否在一个频道内", "isInChannel", b2, false); std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code1 = engine->joinChannelSingleMode(m_robotuser.c_str(), "1234567890", YOUME_USER_TALKER_FREE); if (code1 == YOUME_SUCCESS) { m_cv.wait_for(lk, std::chrono::seconds(10)); } bool b3 = engine->isInChannel("1234567890"); EXPECT_EQ("判断用户是否在一个频道", "isInChannel", b3, true); engine->leaveChannelMultiMode("1234567890"); } //查频道用户列表 /** { std::unique_lock<std::mutex> lk(m_mutex); //YouMeErrorCode getChannelUserList( const char* channelID, int maxCount, bool notifyMemChange ); YouMeErrorCode code = engine->getChannelUserList(TALK_CHAT_ROOM, -1, true); EXPECT_EQ("查询频道用户列表:全部","getChannelUserList", code, YOUME_SUCCESS); //m_cv.wait_for(lk, std::chrono::seconds(10)); //lk.unlock(); //std::unique_lock<std::mutex> lk1(m_mutex); YouMeErrorCode code1 = engine->getChannelUserList(TALK_CHAT_ROOM, 10, true); EXPECT_EQ("查询频道用户列表:10个用户, 其他用户进出房间时通知", "getChannelUserList", code1, YOUME_SUCCESS); YouMeErrorCode code2 = engine->getChannelUserList(TALK_CHAT_ROOM, 10, false); EXPECT_EQ("查询频道用户列表:10个用户, 其他用户进出房间时不通知", "GetChannelUserList", code2, YOUME_SUCCESS); } */ //踢人 { // std::unique_lock<std::mutex> lk(m_mutex); // YouMeErrorCode code = engine->kickOtherFromChannel(USER_ID_B, TALK_CHAT_ROOM, 10); // if (code == YOUME_SUCCESS) { // EXPECT_EQ("[KickOtherFromChannel call]", code, YOUME_SUCCESS); //机器人造出来后再恢复 // m_cv.wait_for(lk, std::chrono::seconds(10)); // } } } void TalkCasesController::testHostMode() { //主播通话模式 主播 IYouMeVoiceEngine *engine = YouMeTalk::getInstance()->getInf(); engine->setNotifyCallback(this); engine->setVideoCallback(this); engine->setPcmCallback(this); engine->setRestApiCallback(this); engine->setAVStatisticCallback(this); engine->setRecvCustomDataCallback(this); { engine->unInit(); std::unique_lock<std::mutex> lk(m_mutex); actionInit(); m_cv.wait_for(lk, std::chrono::seconds(10)); } engine->setTCPMode(1); { std::unique_lock<std::mutex> lk(m_mutex); actionJoinRoomZhubo(); IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->joinChannelSingleMode(m_robotuser.c_str(), "1234", YOUME_USER_TALKER_FREE); EXPECT_EQ("以主播模式加入单个房间", "joinChannelSingleMode", code, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); YouMeErrorCode code1 = engine->startCapture(); EXPECT_EQ("开启摄像头", "startCapture", code1, YOUME_SUCCESS); } //视频测试 //主播模式,主播端 { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code3 = engine->inputCustomData(nullptr, 1000, 1529063275); EXPECT_EQ("向房间输入自定义数据,传入nullptr值", "inputCustomData", code3, YOUME_ERROR_INVALID_PARAM); YouMeErrorCode code1 = engine->inputCustomData(nullptr, 1025, 1529063275); EXPECT_EQ("向房间输入自定义数据, 自定义数据超出1024个字节", "inputCustomData", code1, YOUME_ERROR_INVALID_PARAM); char * data = (char*) malloc(1025); memset(data, 'a', 1025); YouMeErrorCode code2 = engine->inputCustomData(data, 1024, 1529063278L); EXPECT_EQ("输入自定义数据, 输入正确的参数", "inputCustomData", code2, YOUME_SUCCESS); free(data); } /*抢麦放麦*/ return; { //抢麦相关设置 //std::unique_lock<std::mutex> lk(m_mutex); //暂时看不出有回调 YouMeErrorCode code = engine->setGrabMicOption(TALK_CHAT_ROOM, 1, 10, 30, 3); // // 1先到先得 // EXPECT_EQ("抢麦设置", "setGrabMicOption", code, YOUME_SUCCESS); } { std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code = engine->startGrabMicAction(TALK_CHAT_ROOM, "Begin to grab mic action"); EXPECT_EQ("开始抢麦活动", "startGrabMicAction", code, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); } { std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code = engine->stopGrabMicAction(TALK_CHAT_ROOM, "Begin to grab mic action"); EXPECT_EQ("停止抢麦活动", "stopGrabMicAction", code, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); } { //engine->setVideoNoFrameTimeout(1); YouMeErrorCode code1 = engine->requestGrabMic(TALK_CHAT_ROOM, 5, true, "请求连麦"); EXPECT_EQ("发起抢麦请求, 抢麦成功后是自动开启麦克风权限", "startGrabMicAction", code1, YOUME_SUCCESS); YouMeErrorCode code2 = engine->releaseGrabMic(TALK_CHAT_ROOM); EXPECT_EQ("释放麦", "releaseGrabMic", code2, YOUME_SUCCESS); YouMeErrorCode code3 = engine->requestGrabMic(TALK_CHAT_ROOM, 3, false, "请求连麦"); EXPECT_EQ("发起抢麦请求, 抢麦成功后是不自动开启麦克风权限", "startGrabMicAction", code3, YOUME_SUCCESS); } { std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code3 = engine->setInviteMicOption("", 50, 20); EXPECT_EQ("主播连麦设置,参数为空", "setInviteMicOption", code3, YOUME_SUCCESS); YouMeErrorCode code1 = engine->setInviteMicOption(TALK_CHAT_ROOM, 100, 100); EXPECT_EQ("主播连麦设置", "setInviteMicOption", code1, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); lk.unlock(); YouMeErrorCode code2 = engine->setInviteMicOption(TALK_CHAT_ROOM, -1, -1); EXPECT_EQ("主播连麦设置,waitTimeout=-1, maxTalkTime=-1", "setInviteMicOption", code2, YOUME_SUCCESS); } { std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code1 = engine->requestInviteMic("", "", ""); EXPECT_EQ("主播与用户发起连麦请求,房间等参数为空值", "requestInviteMic", code1, YOUME_ERROR_INVALID_PARAM); YouMeErrorCode code2 = engine->requestInviteMic(TALK_CHAT_ROOM, TALK_USER_A, "content"); EXPECT_EQ("主播与用户发起连麦请求,房间等参数不为空值", "requestInviteMic", code2, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); } { std::unique_lock<std::mutex> lk(m_mutex); YouMeErrorCode code1 = engine->responseInviteMic(TALK_USER_A, true, "responese"); EXPECT_EQ("主播应答连麦请求,参数为true,同意连麦", "responseInviteMic", code1, YOUME_SUCCESS); std::this_thread::sleep_for(std::chrono::seconds(5));//实际测试可以加长一点 YouMeErrorCode code2 = engine->stopInviteMic(); EXPECT_EQ("停止连麦请求", "stopInviteMic", code2, YOUME_SUCCESS); m_cv.wait_for(lk, std::chrono::seconds(10)); } } void TalkCasesController::testFreeVideoMode() { IYouMeVoiceEngine *engine = YouMeTalk::getInstance()->getInf(); int renderId = engine->createRender(m_robotuser.c_str()); if (renderId >= 0){ EXPECT_EQ("创建渲染", "createRender", 0, 0); } int r1 = engine->deleteRender(renderId); EXPECT_EQ("删除渲染", "deleteRender", r1, 0); engine->createRender(m_robotuser.c_str());//重新创建渲染 YouMeErrorCode code1 = engine->openBeautify(true); EXPECT_EQ("美颜开关,默认是关闭美颜", "openBeautify", code1, YOUME_SUCCESS); YouMeErrorCode code2 = engine->beautifyChanged(0.5); EXPECT_EQ("美颜强度参数设置", "beautifyChanged", code2, YOUME_SUCCESS); YouMeErrorCode code3 = engine->stretchFace(true); EXPECT_EQ("瘦脸开关", "stretchFace", code3, YOUME_SUCCESS); YouMeErrorCode code4 = engine->setExternalFilterEnabled(true); EXPECT_EQ("打开/关闭 外部扩展滤镜回调", "setExternalFilterEnabled", code4, YOUME_SUCCESS); YouMeErrorCode code5 = engine->setVideoFrameRawCbEnabled(true); EXPECT_EQ("设置视频数据回调方式", "setVideoFrameRawCbEnabled", code5, YOUME_SUCCESS); } void TalkCasesController::actionInputData() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); engine->setRecvCustomDataCallback(this); // YouMeErrorCode code4 = engine->joinChannelSingleMode(m_robotuser.c_str(), "1234", YOUME_USER_TALKER_FREE); // // std::this_thread::sleep_for(std::chrono::seconds(5)); // YouMeErrorCode code3 = engine->inputCustomData(nullptr, 1000, 1529063275); // EXPECT_EQ("向房间输入自定义数据,传入nulltr值", "inputCustomData", code3, YOUME_ERROR_INVALID_PARAM); // YouMeErrorCode code1 = engine->inputCustomData(nullptr, 1025, 1529063275); // EXPECT_EQ("向房间输入自定义数据, 自定义数据超出1024个字节", "inputCustomData", code1, YOUME_ERROR_INVALID_PARAM); char * data = (char*) malloc(1025); memset(data, 'a', 1025); for (int i = 0; i < 5; ++i) { YouMeErrorCode code = engine->inputCustomData(data, 20, 1529063278L); std::this_thread::sleep_for(std::chrono::seconds(1)); } //EXPECT_EQ("输入自定义数据, 输入正确的参数", "inputCustomData", code2, // YOUME_SUCCESS); free(data); } void TalkCasesController::runTests() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); engine->setPcmCallback(this); engine->setVideoCallback(this); engine->setNotifyCallback(this); engine->setRestApiCallback(this); engine->setAVStatisticCallback(this); engine->setCaptureFrontCameraEnable(true); engine->setRecvCustomDataCallback(this); initfile(); actionUninit(); // { // std::unique_lock<std::mutex> lk(m_mutex); // actionInit(); // //cocos2d::log("Wait for callback..."); // m_cv.wait_for(lk, std::chrono::seconds(10)); // EXPECT_EQ("是否已经初始化成功", "isInited", engine->isInited(), true); // } { engine->unInit(); actionInit(); { //进入房间前参数设置 YouMeErrorCode code1 = engine->setVBR(true); EXPECT_EQ("设置视频编码是否采用VBR动态码率方式", "setVBR", code1, YOUME_SUCCESS); YouMeErrorCode code2 = engine->setVBRForSecond(true); EXPECT_EQ("设置小流视频编码是否采用VBR动态码率方式", "setVBRForSecond", code2, YOUME_SUCCESS); engine->setVideoHardwareCodeEnable(false); bool code3 = engine->getVideoHardwareCodeEnable(); if (code3 = false){ EXPECT_EQ("设置视频数据是否同意开启硬编硬解", "setVideoHardwareCodeEnable", 0, 0); EXPECT_EQ("获取视频数据是否同意开启硬编硬解", "getVideoHardwareCodeEnable", 0, 0); } engine->setVideoHardwareCodeEnable(true);//恢复默认值 bool code4 = engine->getUseGL(); if (code4 = true){ EXPECT_EQ("获取android下是否启用GL", "getUseGL", 0, 0); } } actionJoinRoomZhubo(); engine->setExternalInputMode(true); //engine->setExternalInputMode(false); //SDK内部采集模式 //EXPECT_EQ("设置视频输入模式:SDK内部采集模式", "setExternalInputMode", code1, YOUME_SUCCESSS); YouMeErrorCode code1 = engine->setVideoFps(15.0);//帧率 EXPECT_EQ("设置帧率", "setVideoFps", code1, YOUME_SUCCESS); engine->setSpeakerMute(false); YouMeErrorCode code2 = engine->setVideoNetResolutionForSecond(720, 160); EXPECT_EQ("设置视频网络传输过程的分辨率,低分辨率", "setVideoNetResolutionForSecond", code2, YOUME_SUCCESS); YouMeErrorCode code3 = engine->setExternalInputSampleRate(SAMPLE_RATE_16, SAMPLE_RATE_8); EXPECT_EQ("设置外部输入模式的语音采样率", "setExternalInputSampleRate", code3, YOUME_SUCCESS); engine->setAudioQuality(HIGH_QUALITY); YouMeErrorCode code4 = engine->startCapture(); EXPECT_EQ("开始camera capture", "startCapture", code4, YOUME_SUCCESS); } { YouMeErrorCode code1 = engine->resetCamera(); EXPECT_EQ("权限检测结束后重置摄像头", "resetCamera", code1, YOUME_SUCCESS); } { //摄像头控制 YouMeErrorCode code1 = engine->switchCamera(); EXPECT_EQ("切换摄像头", "switchCamera", code1, YOUME_SUCCESS); for (int i = 0; i < 10; ++i) { engine->switchCamera(); } } { //是否设置前置摄像头 YouMeErrorCode code = engine->setCaptureFrontCameraEnable(true); EXPECT_EQ("设置前置摄像头true", "setCaptureFrontCameraEnable", code, YOUME_SUCCESS); } { engine->setVideoCodeBitrate(100, 0); engine->setAudioQuality(LOW_QUALITY); engine->setAudioQuality(HIGH_QUALITY); } { unsigned int sxmalv = engine->getCurrentVideoCodeBitrate(); cocos2d::log("The video code bit rate is %d", sxmalv); } testFreeVideoMode(); testTalkMode(); testHostMode(); endfile(); cocos2d::log("Finished!"); } void TalkCasesController::onVideoFrameCallback(std::string userId, void *data, int len, int width, int height, int fmt, uint64_t timestamp) { cocos2d::log("12221"); cocos2d::log("%s, %s, %d, %d, %d, %d, %lld", userId.c_str(), data, len, width, height, fmt, timestamp); } void TalkCasesController::onAudioFrameMixedCallback(void* data, int len, uint64_t timestamp) { cocos2d::log("%s %d %lld", data, len, timestamp); //cocos2d::log(); } void TalkCasesController::sendemail() { IYouMeVoiceEngine *engine = IYouMeVoiceEngine::getInstance(); std::string strVer = YoumeUtil::verNumToString(engine->getSDKVersion()); std::string extentsion = cocos2d::StringUtils::format("Vedio_SDK_%s", strVer.c_str()); YouMeHttpRequest::sendFile("http://106.75.7.162:8890/sendreport", YoumeUtil::getReportFilename(), extentsion.c_str()); // YouMeHttpRequest::sendFile("http://106.75.7.162:8998/sendreport", // YoumeUtil::getReportFilename(), // extentsion.c_str()); } void TalkCasesController::actionInit() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->init(this, TALK_APPKEY, TALK_APPSECRET, RTC_CN_SERVER, ""); EXPECT_EQ("初始化Talk引擎", "init", code, YOUME_SUCCESS); std::this_thread::sleep_for(std::chrono::seconds(5)); } void TalkCasesController::actionJoinSingleRoom() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->joinChannelSingleMode(m_robotuser.c_str(), TALK_CHAT_ROOM, YOUME_USER_TALKER_FREE); EXPECT_EQ("以自由角色、单频道模式加入房间", "joinChannelSingleMode", code, YOUME_SUCCESS); } void TalkCasesController::actionJoinMultiRoom() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->joinChannelMultiMode(m_robotuser.c_str(), TALK_CHAT_ROOM , YOUME_USER_TALKER_FREE); EXPECT_EQ("加入多房间", "joinChannelMultiMode", code, YOUME_SUCCESS); } void TalkCasesController::actionLeaveMultiMode() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->leaveChannelMultiMode(TALK_CHAT_ROOM); EXPECT_EQ("离开某个房间", "leaveChannelMultiMode", code, YOUME_SUCCESS); } void TalkCasesController::actionLeaveSingleChannel() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->leaveChannelAll(); EXPECT_EQ("离开房间", "leaveChannelAll", code, YOUME_SUCCESS); } void TalkCasesController::actionJoinRoomZhubo() { IYouMeVoiceEngine* engine = IYouMeVoiceEngine::getInstance(); YouMeErrorCode code = engine->joinChannelSingleMode(m_robotuser.c_str(), TALK_CHAT_ROOM, YOUME_USER_HOST); EXPECT_EQ("以主播模式加入单个房间", "joinChannelSingleMode", code, YOUME_SUCCESS); } void TalkCasesController::testThreadFunc() { runTests(); sendemail(); }
#pragma once #ifndef _PRODUC_CLASS_ #define _PRODUC_CLASS_ #include <iostream> #include <vector> #include "Base.h" using namespace std; //产生式类 class Produc { private: //产生式字符串 string str; //产生式左侧 string left; //产生式推导符 string arrow; //产生式右侧符号集 vector<string> right; public: string getStr(); string getLeft(); string getArrow(); vector<string> getRight(); Produc(string str, string left, string arrow, vector<string> right); ~Produc(); //通过解析字符串生成产生式对象 static Produc identify(vector<string> &symbols, string arrow, string str); ////通过符号表解析字符串为字符串列表 //static vector<string> analyzestr(const vector<string>& symbols, vector<string>& strs, string str); }; #endif
// Copyright 2020 Erik Teichmann <kontakt.teichmann@gmail.com> #include <vector> #include "test/catch.hpp" #include "test/harmonic_oscillator_ode.hpp" #include "include/sam/analysis/period.hpp" #include "include/sam/system/rk4_system.hpp" TEST_CASE("single harmonic oscillator") { // omega = 1 -> T = 2*pi sam::PeriodParameters params; double omega = 1; unsigned int N = 1; unsigned int dimension = 2; double dt = 0.01; std::vector<double> initial({1., 0.}); sam::RK4System<HarmonicOscillatorODE> system(N, dimension, omega); system.SetPosition(initial); double T = CalculatePeriod(system, dt, [](std::vector<double> x) { return x[1] > 0; }, params); REQUIRE(T == Approx(2.*M_PI).margin(1e-5)); } TEST_CASE("two uncoupled harmonic oscillators") { // omega = 1 -> T = 2*pi sam::PeriodParameters params; std::vector<double> omega({1, 2}); double coupling = 0; unsigned int N = 2; unsigned int dimension = 2; double dt = 0.01; std::vector<double> initial({1., 0., 1., 0.}); sam::RK4System<CoupledHarmonicOscillatorODE> system(N, dimension, omega[0], omega[1], coupling); system.SetPosition(initial); SECTION("first oscillator") { double T = sam::CalculatePeriod(system, dt, [](std::vector<double> x) { return x[1] > 0; }, params); REQUIRE(T == Approx(2.*M_PI).margin(1e-5)); } SECTION("second oscillator") { params.n_osc = 1; double T = sam::CalculatePeriod(system, dt, [](std::vector<double> x) { return x[3] > 0; }, params); REQUIRE(T == Approx(M_PI).margin(1e-5)); } }
// C++ code // void setup() { pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); } void loop() { for(int i =2; i<=9; i++){ digitalWrite(i, HIGH); delay(200); digitalWrite(i, LOW); } }
#pragma once namespace console { typedef void (* ConsoleCommandArgs)(int argc, char* argv[], void* user); typedef void (* ConsoleCommand)(char* cmd, char* cmdline, void* user); typedef void (* ConsoleCommandNoArgs)(); void toggle_int(char* cmd, char* cmdline, void* user); void init(); void print(const char* format, ...); bool processCmd(const char* cmd); bool executeJS(char* script); bool executeCommand(char *cmd); void addCommand(char* name, ConsoleCommand command, void* userdef = NULL); void addCommand(char* name, ConsoleCommandArgs command, void* userdef = NULL); void addCommand(char* name, ConsoleCommandNoArgs command, void* userdef = NULL); void delCommand(char* name); void listCommands(); bool isCommand(char* name); };
/* * Program Name: * Color_Transform.h * Class Name: * Color_Transformer * Input: Source image one to provide color, source image two to sccept color * Output: Processed image after color transformation * Usage: * ./Image_Equalizater srcImgOne srcImgTwo */ #ifndef COLOR_TRANSFORM_H #define COLOR_TRANSFORM_H #include <iostream> #include <vector> #include "CImg.h" using namespace std; using namespace cimg_library; class Color_Transformer{ public: Color_Transformer(CImg<float>& src1, CImg<float>& src2); // Color channels transform tool functions void RGBtoLab(); void LabToRGB(); // Start-up void Color_Transform(); private: CImg<float> colorImg; // The source image provides color CImg<float> srcImg; // The source image provides source background CImg<float> destImg; // Final image after processed }; #endif
#include "Region.h" Region::Region(double xl, double xr, double yl, double yr) : a11(xl), a12(xr), a21(yl), a22(yr) { } Region::Region() : a11(0), a12(1), a21(0), a22(1) { } Region::~Region() { } double Region::maximum_norm() { double delta_x = fabs(this->a12) + fabs(this->a11); double delta_y = fabs(this->a22) + fabs(this->a21); return delta_x > delta_y ? delta_x : delta_y; } const Region Region::operator*(const Region &region) const { return Region(this->a11 * region.a11 + this->a12 * region.a21, this->a11 * region.a12 + this->a12 * region.a22, this->a21 * region.a11 + this->a22 * region.a21, this->a21 * region.a12 + this->a22 * region.a22); } vec2d Region::measure_m() { vec2d result; result.x = this->a12 - this->a11; result.y = this->a22 - this->a21; return result; } const Region Region::operator-(const vec2d &vec) const { return Region(this->a11 - vec.x, this->a12 - vec.x, this->a21 - vec.y, this->a22 - vec.y); } bool Region::is_contained_in(const Region &region) { if (this->a11 >= region.a11 && this->a12 <= region.a12 && this->a21 >= region.a21 && this->a22 <= region.a22) { return true; } return false; } bool Region::is_empty_for_intersection(const Region &region) { if ((this->a11 > region.a12 || this->a12 < region.a11) || (this->a21 > region.a22 || this->a22 < region.a21)) { return true; } return false; } Region Region::inverse_mat() { double delta = a11* a22 - a12*a21; return Region(a22/delta, -a12/delta, -a21/delta, a11/delta); } bool Region::is_reversible(){ double delta = a11* a22 - a12*a21; if(fabs(delta) <1e-10){ return false; } return true; }
// Fill out your copyright notice in the Description page of Project Settings. #include "UE4Coop.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, UE4Coop, "UE4Coop" );
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "GlPanel.h" #include "CaptureWindow.h" std::unique_ptr<GlPanel> GlPanel::Create(StatsMode stats_mode) { return std::make_unique<CaptureWindow>(stats_mode); } GlPanel::GlPanel() { m_WindowOffset[0] = 0; m_WindowOffset[1] = 0; m_MainWindowWidth = 0; m_MainWindowHeight = 0; m_NeedsRedraw = true; } void GlPanel::Initialize() {} void GlPanel::Resize(int /*a_Width*/, int /*a_Height*/) {} void GlPanel::Render(int /*a_Width*/, int /*a_Height*/) {}
#include "Ball.h" Ball::Ball() { posX = OX + ((FWIDTH - size) / 2); posY = OY + FHEIGHT - size * 2; horStep = 10; vertStep = -10; } int Ball::X() { return posX; } int Ball::Y() { return posY; } void Ball::Move(Blocks* blocks, Player player) { //столкновение со стенами и блоками if (horStep > 0) { if (posY >= OY + blocks->Height() * N && posX <= OX + FWIDTH - size - horStep) posX += horStep; else { int i = ((posY +size/2- OY) / blocks->Height()); int j = (posX - OX) / blocks->Width(); if (posX <= OX + blocks->Width() * (j+1) - size - horStep) { posX += horStep; } else { if ((blocks->value((j + 1), i) != 0) && j < 6) { posX = OX + blocks->Width() * (j+1)-size; horStep *= -1; } else { if (posX <= OX + FWIDTH - size - horStep) posX += horStep; else { posX = OX + FWIDTH - size; horStep *= -1; } } } } /*if (posX <= OX + FWIDTH - horStep - size) { posX += horStep; } else { posX = OX + FWIDTH - size; horStep *= -1; }*/ } else { if (posY >= OY + blocks->Height() * N - vertStep && posX >= OX - horStep) posX += horStep; else { int i = ((posY +size/2- OY) / blocks->Height()); int j = (posX - OX) / blocks->Width(); if (posX >= OX + blocks->Width() * (j)-horStep && j>0) { posX += horStep; } else { if ((blocks->value((j - 1), i) != 0) && j>0) { posX = OX + blocks->Width() * j; horStep *= -1; } else { if (posX >= OX - horStep) posX += horStep; else { posX = OX; horStep *= -1; } } } } /*if (posX >= OX - horStep) posX += horStep; else { posX = OX; horStep *= -1; }*/ } if (vertStep > 0) { if (posY <= OY + FHEIGHT - vertStep - size - player.plHeight()) posY += vertStep; else { int delta = posX - player.X(); if ((delta <= player.plWidth() - size / 4) && delta >= -(3 * size / 4)) { posY = FHEIGHT - size; vertStep *= -1; if (delta <= -size / 2 && horStep > 0) horStep *= -1; if (delta >= player.plWidth() - size / 2 && horStep < 0) horStep *= -1; } else { posY += vertStep; } } } else { if (posY >= OY + blocks->Height() * N - vertStep) posY += vertStep; else { int i = ((posY + size / 2 - OY) / blocks->Height()); int j = (posX + size / 2 - OX) / blocks->Width(); if (posY >= OY + blocks->Height() * i - vertStep) { posY += vertStep; } else { if ((blocks->value(j, i-1) != 0) && i > 0) { posY = OY + blocks->Height() * i; blocks->decrease(j, i-1); vertStep *= -1; } else { if (posY >= OY - vertStep) posY += vertStep; else { posY = OY; vertStep *= -1; } } } } } } void Ball::Reset() { posX = OX + ((FWIDTH - size) / 2); posY = OY + FHEIGHT - size * 2; horStep = 10; vertStep = -10; }
/** * * * [RU] * * Даны значения температуры, наблюдавшиеся в течение N подряд идущих дней. Найдите номера дней (в нумерации с нуля) со значением температуры * выше среднего арифметического за все N дней. * * Гарантируется, что среднее арифметическое значений температуры является целым числом. * * Формат ввода * Вводится число N, затем N неотрицательных целых чисел — значения температуры в 0-й, 1-й, ... (N−1)-й день. * * Формат вывода * Первое число K — количество дней, значение температуры в которых выше среднего арифметического. Затем K целых чисел — номера этих дней. * * ---------------------------------------------------- * * [EN] * * The temperature values observed for N consecutive days are given. Find the number * of days (numbered from zero) with a temperature value higher than the arithmetic * average for all N days. * * It is guaranteed that the arithmetic mean of the temperature values is an integer. * * Input format * Enter the number N, then N non-negative integers — the temperature values on the 0th, 1st, ... (N-1) th day. * * Output format * The first number K is the number of days when the temperature value is higher * than the arithmetic average. Then K integers are the numbers of these days. * * Example * * Input : * 5 * 7 6 3 0 9 * * Output: * 3 * 0 1 4 * * */ #include <iostream> #include <vector> using namespace std; int VectorSum(vector<int> vect) { int sum = 0; for (int s : vect) { sum += s; } return sum; } void PrintIntVector(vector<int> v, string separator = " ") { for (int s : v) { cout << s << separator; } } int main() { // Test int n; cin >> n; vector<int> temperatures(n); for (int i = 0; i < n; i++) { cin >> temperatures[i]; } int arithmeticMean = VectorSum(temperatures) / n; vector<int> days = {}; for (int i = 0; i < temperatures.size(); i++) { if (temperatures[i] > arithmeticMean) { days.push_back(i); } } cout << days.size() << endl; PrintIntVector(days); return 0; }
/* SegaCDI - Sega Dreamcast cdi image validator. FlatMemoryIterator.h - Custom iterator to iterate through a collection of objects in a continous block of memory. Dec 20th, 2015 - Initial creation. */ #pragma once #include "../stdafx.h" #include <iterator> template<class T> class FlatMemoryIterator : std::iterator<std::input_iterator_tag, T> { T* m_Begin; T* m_Current; T* m_End; std::size_t m_Count; public: FlatMemoryIterator(T* p_Object, std::size_t p_Count) : m_Begin(p_Object), m_Current(p_Object) { // Initialize fields. this->m_End = p_Object + p_Count; this->m_Count = p_count; } FlatMemoryIterator(const FlatMemoryIterator& p_Iterator) : m_Begin(p_Iterator.m_Begin), m_Current(p_Iterator.m_Current), m_End(p_Iterator.m_End), m_Count(p_Iterator.m_Count) { } // Pre-Increment FlatMemoryIterator& operator++() { ++m_Current; return this; } // Post-Increment FlatMemoryIterator operator++(int) { FlatMemoryIterator s_TempObject(*this); ++m_Current; return s_TempObject; } bool operator==(const FlatMemoryIterator& p_Object) { return (m_Begin == p_Object.m_Begin && m_Current == p_Object.m_Current && m_End == p_Object.m_End); } bool operator!=(const FlatMemoryIterator& p_Object) { return (m_Begin != p_Object.m_Begin || m_Current != p_Object.m_Current || m_End != p_Object.m_End); } T& operator*() { return *m_Current; } std::size_t size() { return this->m_Count; } T* begin() { return this->m_Begin; } T* current() { return this->m_Current; } T* end() { return this->m_End; } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 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 "platforms/mac/util/AppleEventUtils.h" #include "adjunct/quick/Application.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "adjunct/quick_toolkit/widgets/OpWorkspace.h" #include "adjunct/quick/models/DesktopWindowCollection.h" #include "platforms/mac/util/CTextConverter.h" #include "platforms/mac/quick_support/CocoaQuickSupport.h" #include "platforms/mac/pi/CocoaOpWindow.h" #include "platforms/mac/File/FileUtils_Mac.h" OpVector<DesktopWindow> topWindowList; OpINT32Vector topRefList; OpVector<DesktopWindow> docWindowList; OpINT32Vector docRefList; void CloseEveryWindow() { g_application->GetDesktopWindowCollection().GentleClose(); } unsigned int GetExportIDForDesktopWindow(DesktopWindow* win, Boolean toplevel) { long index; static int top_unique = 1; static int doc_unique = 1; if (toplevel) { index = topWindowList.Find(win); if (index < 0) { index = topWindowList.GetCount(); topWindowList.Insert(index, win); topRefList.Insert(index, top_unique++); } return topRefList.Get(index); } else { index = docWindowList.Find(win); if (index < 0) { index = docWindowList.GetCount(); docWindowList.Insert(index, win); docRefList.Insert(index, doc_unique++); } return docRefList.Get(index); } } DesktopWindow* GetDesktopWindowForExportID(unsigned int export_id, Boolean toplevel) { DesktopWindowCollection& collection = g_application->GetDesktopWindowCollection(); if (toplevel) { for (DesktopWindowCollectionItem* item = collection.GetFirstToplevel(); item; item = item->GetSiblingItem()) { DesktopWindow* window = item->GetDesktopWindow(); if (window && GetExportIDForDesktopWindow(window, toplevel) == export_id) return window; } } else { OpVector<DesktopWindow> windows; OpStatus::Ignore(collection.GetDesktopWindows(OpTypedObject::WINDOW_TYPE_DOCUMENT, windows)); for (unsigned i = 0; i < windows.GetCount(); i++) { DesktopWindow* window = windows.Get(i); if (GetExportIDForDesktopWindow(window, toplevel) == export_id) return window; } } return NULL; } void InformDesktopWindowCreated(DesktopWindow* new_win) { if (new_win) { if (!new_win->GetParentWorkspace()) GetExportIDForDesktopWindow(new_win, true); if (new_win->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT) GetExportIDForDesktopWindow(new_win, false); } } void InformDesktopWindowRemoved(DesktopWindow* dead_win) { long index = topWindowList.Find(dead_win); if (index >= 0) { topWindowList.Remove(index); topRefList.Remove(index); } index = docWindowList.Find(dead_win); if (index >= 0) { docWindowList.Remove(index); docRefList.Remove(index); } } #pragma mark - // A proper object descriptor has 4 parts: // - What class it is // - How it is being identified (in our case an ID number, specified by formUniqueID) // - The identification itself // - The parent of the object OSErr CreateAEDescFromID(unsigned int id_num, DescType object_type, AEDesc* item_desc) { AEDesc item_record; unsigned int form = formUniqueID; OSStatus err; err = AECreateList(NULL, 0, true, &item_record); if (err == noErr) { AERecord * record = &item_record; err = AEPutKeyPtr(record, keyAEDesiredClass, cType, &object_type, sizeof(object_type)); err |= AEPutKeyPtr(record, keyAEContainer, typeNull, NULL, 0); // No parent err |= AEPutKeyPtr(record, keyAEKeyForm, cEnumeration, &form, sizeof(form)); err |= AEPutKeyPtr(record, keyAEKeyData, typeUInt32, &id_num, sizeof(id_num)); if (err == noErr) { err = AECoerceDesc(record, typeObjectSpecifier, item_desc); } AEDisposeDesc(&item_record); } return err; } // NOTE: AELists have 1-based indexes OSErr AddIDToAEList(unsigned int id_num, long index, DescType object_type, AEDescList* list) { AEDesc item_desc; AECreateDesc(typeNull, NULL, 0, &item_desc); OSStatus err = CreateAEDescFromID(id_num, object_type, &item_desc); if (noErr == err) { err = AEPutDesc(list, index, &item_desc); AEDisposeDesc(&item_desc); } return err; } OSErr CreateAEListFromIDs(unsigned int* id_nums, long count, DescType object_type, AEDescList* list) { int i; OSStatus err; err = AECreateList(NULL, 0, false, list); for (i = 0; i < count && err == noErr; i++) { err = AddIDToAEList(id_nums[i], i+1, object_type, list); } return err; } #pragma mark - int GetWindowCount(Boolean toplevel, BrowserDesktopWindow* container) { if (toplevel) return g_application->GetDesktopWindowCollection().GetToplevelCount(); else if (container) return container->GetModelItem().CountDescendants(OpTypedObject::WINDOW_TYPE_DOCUMENT); return g_application->GetDesktopWindowCollection().GetCount(OpTypedObject::WINDOW_TYPE_DOCUMENT); } int GetTopLevelWindowNumber(DesktopWindow* window) { DesktopWindowCollection& windows = g_application->GetDesktopWindowCollection(); int win_num = 0; int this_index = 1; for (void* theWin = GetNSWindowWithNumber(win_num++); theWin; theWin = GetNSWindowWithNumber(win_num++)) { for (DesktopWindowCollectionItem* item = windows.GetFirstToplevel(); item; item = item->GetSiblingItem()) { DesktopWindow* win = item->GetDesktopWindow(); CocoaOpWindow* opwin = (CocoaOpWindow*)(win ? win->GetOpWindow() : NULL); if (opwin && (opwin->IsSameWindow(theWin))) { if (win == window) return this_index; this_index++; } } } return 0; } Boolean SetTopLevelWindowNumber(DesktopWindow* window, int number) { // IMPLEMENTME: rearrange window return false; } // Main code to find a window from it's z-order number. DesktopWindow* GetNumberedWindow(int number, Boolean toplevel, BrowserDesktopWindow* container) { int count; count = GetWindowCount(toplevel, container); if (number < 0) number = count + number; else number -= 1; if (number < 0 || number >= count) { return NULL; } int this_index = 0; if (container) { OpWorkspace* workspace = container->GetWorkspace(); DesktopWindow* sub_win; int sub_count; if (workspace) { sub_count = workspace->GetDesktopWindowCount(); for (int j = 0; j < sub_count; j++) { sub_win = workspace->GetDesktopWindowFromStack(j); if (sub_win && sub_win->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT) { if (this_index == number) return sub_win; this_index++; } } } return NULL; } DesktopWindowCollection& windows = g_application->GetDesktopWindowCollection(); int win_num = 0; void* theWin; while ((theWin = GetNSWindowWithNumber(win_num++))) { for (DesktopWindowCollectionItem* item = windows.GetFirstToplevel(); item; item = item->GetSiblingItem()) { DesktopWindow* win = item->GetDesktopWindow(); if (win) { CocoaOpWindow* opwin = (CocoaOpWindow*)win->GetOpWindow(); if (opwin && (opwin->IsSameWindow(theWin))) { // It is a desktop window. Great! if (toplevel || win->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT) { if (this_index == number) return win; this_index++; } else if (win->GetType() == OpTypedObject::WINDOW_TYPE_BROWSER) { OpWorkspace* workspace = win->GetWorkspace(); DesktopWindow* sub_win; int sub_count; if (workspace) { sub_count = workspace->GetDesktopWindowCount(); for (int j = 0; j < sub_count; j++) { sub_win = workspace->GetDesktopWindowFromStack(j); if (sub_win && sub_win->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT) { if (this_index == number) return sub_win; this_index++; } } } } } } } } return NULL; } DesktopWindow* GetOrdinalWindow(DescType ordinal, Boolean toplevel, BrowserDesktopWindow* container) { int index = -1; int count = 0; if (ordinal == kAEMiddle || ordinal == kAEAny) { count = GetWindowCount(toplevel, container); } switch (ordinal) { case kAEFirst: index = 1; break; case kAELast: index = -1; break; case kAEMiddle: if (count == 0) return NULL; index = (count+1) / 2; break; case kAEAny: if (count == 0) return NULL; index = (random() % count) + 1; break; default: return NULL; } return GetNumberedWindow(index, toplevel, container); } DesktopWindow* GetNamedWindow(const uni_char* name, Boolean toplevel, BrowserDesktopWindow* container) { DesktopWindowCollection& windows = g_application->GetDesktopWindowCollection(); if (toplevel) { for (DesktopWindowCollectionItem* item = windows.GetFirstToplevel(); item; item = item->GetSiblingItem()) { DesktopWindow* win = item->GetDesktopWindow(); if (win && uni_strcmp(win->GetTitle(), name) == 0) { return win; } } } else { OpVector<DesktopWindow> document_windows; g_application->GetDesktopWindowCollection().GetDesktopWindows(OpTypedObject::WINDOW_TYPE_DOCUMENT, document_windows); for (unsigned int i = 0; i < document_windows.GetCount(); i++) { DesktopWindow* win = document_windows.Get(i); if (uni_strcmp(win->GetTitle(), name) == 0) { return win; } } } return NULL; } DesktopWindow* GetWindowFromAEDesc(const AEDesc *inDesc) { DescType data_desc; MacSize data_size; DescType get_type; SInt32 get_index; DescType get_form; Boolean toplevel; OSStatus err; DesktopWindow* win = NULL; err = AEGetKeyPtr(inDesc, keyAEDesiredClass, cType, &data_desc, &get_type, sizeof(get_type), &data_size); if (noErr == err && (get_type == cWindow || get_type == cDocument)) { // OK, looks like the request for a window, let's look closer. toplevel = (get_type == cWindow); err = AEGetKeyPtr(inDesc, keyAEKeyForm, cEnumeration, &data_desc, &get_form, sizeof(get_form), &data_size); if (err == noErr) { err = AESizeOfKeyDesc(inDesc, keyAEKeyData, &data_desc, &data_size); if (err == noErr) { if ((get_form == formUniqueID) && (data_desc == cLongInteger) && (data_size == 4)) { err = AEGetKeyPtr(inDesc, keyAEKeyData, cLongInteger, &data_desc, &get_index, sizeof(get_index), &data_size); if (err == noErr) win = GetDesktopWindowForExportID(get_index, toplevel); } else if ((get_form == formAbsolutePosition) && (data_desc == cLongInteger) && (data_size == 4)) { err = AEGetKeyPtr(inDesc, keyAEKeyData, cLongInteger, &data_desc, &get_index, sizeof(get_index), &data_size); if (err == noErr) win = GetNumberedWindow(get_index, toplevel, NULL); } else if ((get_form == formAbsolutePosition) && (data_desc == typeAbsoluteOrdinal) && (data_size == 4)) { err = AEGetKeyPtr(inDesc, keyAEKeyData, typeAbsoluteOrdinal, &data_desc, &get_index, sizeof(get_index), &data_size); if (err == noErr) win = GetOrdinalWindow(get_index, toplevel, NULL); } else if ((get_form == formName) && (data_desc == typeUnicodeText || data_desc == typeChar)) { uni_char* uniName = GetNewStringFromObjectAndKey(inDesc, keyAEKeyData); if (uniName) { win = GetNamedWindow(uniName, toplevel, NULL); delete [] uniName; } } } } } return win; } #pragma mark - OSErr CreateDescForWindow(DesktopWindow* win, Boolean toplevel, AEDesc* item_desc) { DescType data_desc = toplevel ? (DescType)cWindow : (DescType)cDocument; if (win) return CreateAEDescFromID(GetExportIDForDesktopWindow(win, toplevel), data_desc, item_desc); return paramErr; } // "get window n" // if n is positive, get the nth window from the front // if n is negative, -1 is the last window, -2 is second-to-last and so on OSErr CreateDescForNumberedWindow(int number, Boolean toplevel, BrowserDesktopWindow* container, AEDesc* item_desc) { DescType data_desc = toplevel ? (DescType)cWindow : (DescType)cDocument; DesktopWindow* win = GetNumberedWindow(number, toplevel, container); if (win) return CreateAEDescFromID(GetExportIDForDesktopWindow(win, toplevel), data_desc, item_desc); return paramErr; } // "get first window" // "get last window" // "get middle window" // "get some window" // "get windows" OSErr CreateDescForOrdinalWindow(DescType ordinal, Boolean toplevel, BrowserDesktopWindow* container, AEDesc* item_desc) { DescType data_desc = toplevel ? (DescType)cWindow : (DescType)cDocument; OSStatus err; DesktopWindow* win; if (ordinal == kAEAll) { // Special case. GetOrdinalWindow can only return one window. int count = 1; err = AECreateList(NULL, 0, false, item_desc); while (err == noErr && (win = GetNumberedWindow(count, toplevel, container))) { err = AddIDToAEList(GetExportIDForDesktopWindow(win, toplevel), count, data_desc, item_desc); count++; } return err; } win = GetOrdinalWindow(ordinal, toplevel, container); if (win) return CreateAEDescFromID(GetExportIDForDesktopWindow(win, toplevel), data_desc, item_desc); return paramErr; } // "get window \"Foo\"" OSErr CreateDescForNamedWindow(const uni_char* name, Boolean toplevel, BrowserDesktopWindow* container, AEDesc* item_desc) { DescType data_desc = toplevel ? (DescType)cWindow : (DescType)cDocument; DesktopWindow* win = GetNamedWindow(name, toplevel, container); if (win) return CreateAEDescFromID(GetExportIDForDesktopWindow(win, toplevel), data_desc, item_desc); return paramErr; } #pragma mark - uni_char* GetNewStringFromObjectAndKey(const AEDescList* desc, AEKeyword keyword) { uni_char* uniText = NULL; DescType data_desc; MacSize data_size; OSStatus err; err = AESizeOfKeyDesc(desc, keyword, &data_desc, &data_size); if ((err == noErr) && (data_desc == typeUnicodeText || data_desc == typeChar)) { if (data_desc == typeUnicodeText) { uniText = new uni_char[data_size/2 + 1]; err = AEGetKeyPtr(desc, keyword, data_desc, &data_desc, uniText, data_size, &data_size); uniText[data_size/2] = 0; if (err != noErr) { delete [] uniText; uniText = NULL; } } else if (data_desc == typeChar) { char* macText = new char[data_size + 1]; if (macText) { err = AEGetKeyPtr(desc, keyword, data_desc, &data_desc, macText, data_size, &data_size); if (err == noErr) { macText[data_size] = 0; uniText = new uni_char[data_size + 1]; gTextConverter->ConvertStringFromMacC(macText, uniText, data_size+1); if (gTextConverter->GotConversionError()) { delete [] uniText; uniText = NULL; } } delete [] macText; } } } return uniText; } DesktopWindow* GetWindowFromObjectAndKey(const AEDescList* desc, AEKeyword keyword) { DescType data_desc; MacSize data_size; OSErr err; DesktopWindow* win = NULL; err = AESizeOfKeyDesc(desc, keyword, &data_desc, &data_size); if (err == noErr) { if (data_desc == cLongInteger) { // window ID int winID = 0; err = AEGetKeyPtr(desc, keyword, cLongInteger, &data_desc, &winID, sizeof(winID), &data_size); if (err == noErr) { if (winID == -1) win = g_application->GetActiveDesktopWindow(FALSE); else win = GetDesktopWindowForExportID(winID, true); } } else if (data_desc == typeObjectSpecifier) { // window object AEDesc winObject; err = AEGetKeyDesc(desc, keyword, typeObjectSpecifier, &winObject); if (err == noErr) { win = GetWindowFromAEDesc(&winObject); AEDisposeDesc(&winObject); } } else if (data_desc == typeUnicodeText || data_desc == typeChar) { // window name uni_char* name = GetNewStringFromObjectAndKey(desc, keyword); if (name) { win = GetNamedWindow(name, true, NULL); delete [] name; } } } else { win = g_application->GetActiveDesktopWindow(FALSE); } return win; } Boolean GetFileFromObjectAndKey(const AEDescList* desc, AEKeyword keyword, FSRef* file, Boolean create) { DescType data_desc; MacSize data_size; OSErr err; err = AESizeOfKeyDesc(desc, keyword, &data_desc, &data_size); if (err == noErr) { if (data_desc == typeObjectSpecifier) { // file object... AEDesc fileObject; err = AEGetKeyDesc(desc, keyword, typeObjectSpecifier, &fileObject); if (err == noErr) { Boolean ok = GetFileFromObjectAndKey(&fileObject, keyAEKeyData, file, create); AEDisposeDesc(&fileObject); return ok; } } else if (data_desc == typeChar && data_size <= 255) { // file path... FSRef spec; Str255 path; err = AEGetKeyPtr(desc, keyword, typeChar, &data_desc, &path[1], 255, &data_size); path[0] = data_size; if (err == noErr) { FSRef folderRef; OpString unicode_path; unicode_path.SetL((const char*)path); err = FSFindFolder(kLocalDomain, kVolumeRootFolderType, kDontCreateFolder, &folderRef); // FIXME: ismailp - test rhoroughly err = FSMakeFSRefUnicode(&folderRef, unicode_path.Length(), (const UniChar*)unicode_path.CStr(), kTextEncodingUnknown, &spec); //FSMakeFSSpec(0, 0, path, &spec); if (create && (err == noErr || err == fnfErr)) { if (noErr == err) { FSDeleteObject(&spec); } err = FSCreateFileUnicode(&spec, 0, NULL, kFSCatInfoNone, NULL, file, NULL); } } } else if (data_desc == typeAlias) { // file alias... Handle alias = NewHandle(data_size); FSRef spec; HLock(alias); err = AEGetKeyPtr(desc, keyword, typeAlias, &data_desc, *alias, data_size, &data_size); if (err == noErr) { Boolean changed; err = FSResolveAlias(NULL, (AliasHandle)alias, &spec, &changed); if (create && (err == noErr || err == fnfErr)) { if (noErr == err) { FSDeleteObject(&spec); } err = FSCreateFileUnicode(&spec, 0, NULL, kFSCatInfoNone, NULL, file, NULL); //FSpCreate(&spec, '\?\?\?\?', '\?\?\?\?', NULL); } } DisposeHandle(alias); } else { err = paramErr; } } return (err == noErr); } uni_char* GetNewStringFromListAndIndex(const AEDescList* desc, long index) { uni_char* uniText = NULL; DescType data_desc; MacSize data_size; OSStatus err; AEKeyword keyword; err = AESizeOfNthItem(desc, index, &data_desc, &data_size); if ((err == noErr) && (data_desc == typeUnicodeText || data_desc == typeChar)) { if (data_desc == typeUnicodeText) { uniText = new uni_char[data_size/2 + 1]; err = AEGetNthPtr(desc, index, data_desc, &keyword, &data_desc, uniText, data_size, &data_size); uniText[data_size/2] = 0; if (err != noErr) { delete [] uniText; uniText = NULL; } } else if (data_desc == typeChar) { char* macText = new char[data_size + 1]; if (macText) { err = AEGetNthPtr(desc, index, data_desc, &keyword, &data_desc, macText, data_size, &data_size); if (err == noErr) { macText[data_size] = 0; uniText = new uni_char[data_size + 1]; gTextConverter->ConvertStringFromMacC(macText, uniText, data_size+1); if (gTextConverter->GotConversionError()) { delete [] uniText; uniText = NULL; } } delete [] macText; } } } return uniText; } #pragma mark - #ifdef _MAC_DEBUG // Just walk through the event. FILE* logfile = NULL; void ObjectTraverse(const AEDescList *object) { static int recurse=0; long count; AEKeyword keyword; DescType data_desc; MacSize data_size; char buffer[1024]; OSStatus err; if (noErr == AECountItems(object, &count)) { for (int i = 1; i <= count; i++) // AERecord starts at index 1 { err = AESizeOfNthItem(object, i, &data_desc, &data_size); if (noErr == err) { err = AEGetNthPtr(object, i, data_desc, &keyword, &data_desc, buffer, 1024, &data_size); if (logfile) { long r; for (r = 0; r < recurse; r++) fprintf(logfile," "); fprintf(logfile,"key:'%c%c%c%c' desc:'%c%c%c%c' size: %ld", FCC_TO_CHARS(keyword), FCC_TO_CHARS(data_desc), data_size); if (err == noErr) { if (data_size == 4) { int val = *((int*) buffer); if ((data_desc == typeSInt32) || (data_desc == typeUInt32)) fprintf(logfile," value: %d", val); if ((data_desc == typeSInt32) || (data_desc == typeUInt32)) fprintf(logfile," value:'%c%c%c%c'", FCC_TO_CHARS(val)); } } fprintf(logfile,"\r"); } if ((err == noErr) && ((data_desc == cObjectSpecifier) || (data_desc == cAEList) || (data_desc == typeAERecord))) { AEDesc obj2; err = AEGetNthDesc(object, i, data_desc, &keyword, &obj2); if (err == noErr) { recurse++; ObjectTraverse(&obj2); recurse--; } } } } } } #endif
#ifndef OwnDot_HPP #define OwnDot_HPP #include <QObject> // Object source comes with a .moc include class OwnDotPrivate; class OwnDot : public QObject { Q_OBJECT public: OwnDot(); ~OwnDot(); private: OwnDotPrivate* const d; }; #endif
#ifndef DISPLAYRENDER_H #define DISPLAYRENDER_H #include <Arduino.h> #include "Display.h" #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #if defined(__AVR_ATtiny85__) if (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif class DisplayRender { public: Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_RING_ALL_PIX, LED_PIN, NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel pixelsRow0 = Adafruit_NeoPixel(NUM_RING_ALL_PIX, RING_LED_PIN_ROW_01, NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel pixelsRow1 = Adafruit_NeoPixel(NUM_RING_ALL_PIX, RING_LED_PIN_ROW_02, NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel pixelsRow2 = Adafruit_NeoPixel(NUM_RING_ALL_PIX, RING_LED_PIN_ROW_03, NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel pixelsRow3 = Adafruit_NeoPixel(NUM_RING_ALL_PIX, RING_LED_PIN_ROW_04, NEO_GRB + NEO_KHZ800); byte pos[CONFIG_MAP_SIZE]; int color[CONFIG_MAP_SIZE]; char type[CONFIG_MAP_SIZE]; Display display_map; DisplayRender(Display); void openSingle(int num, uint32_t RGB); void openSingleRGB(int num, byte r, byte g, byte b); void openSingle4x4(byte r, int num, uint32_t RGB); void setDisplay(Display dis) { display_map = dis; } void updateMap(); void updateMap4x4(); void displayBegin4x4() { pixelsRow0.begin(); pixelsRow1.begin(); pixelsRow2.begin(); pixelsRow3.begin(); } void displayBegin() { pixels.begin(); } }; #endif
#include <vector> struct point { float x; float y; float z; }; struct face { int vtx[3]; }; struct model { std::vector< face > vertexIndices, normalIndices; std::vector< point > obj_points; std::vector< point > normals; }; //-------- Functions -------------------------------- void Render(); // The function responsible for drawing everything in the // OpenGL context associated to a window. void Resize(int w, int h); // Handle the window size changes and define the world coordinate // system and projection type void Setup(); // Set up the OpenGL state machine and create a light source void Idle(); void ReadFile(model*); //Function for reading a model file void DisplayModel(model); // Function for displaying a model void Keyboard(unsigned char key,int x,int y); // Function for handling keyboard events. void Mouse(int button,int state,int x,int y); // Function for handling mouse events void DisplaySun(); void DisplayStars(); void displayPlanet(model, double, double, double, float);
#include <stdio.h> #include <math.h> #include <fstream> #include <iomanip> using namespace std; double mans_exp ( double x ){ double a , S ,R; int k=0; a = (1+x)*pow(x,k)/(1.); S = a; while(k<=1000) { k++; R = x/k; a = a*R; S = S+a; // printf("%.2f %.2f %.2f\n",x,a,S); if(k == 999) { printf("lietotajafunkcija pirmspēdeja vertība − y=mans_exp %.2f =%.2f \n" ,x , S); } // printf("%8.4f\t%8.2f\n" , a , S); // printf("%.2f\t%8.2f\t%8.2f\n" ,x , a , S); } return S; } int main(){ double x,y,yy; printf("(1+x)*exp(x) aprekinasana: \n"); printf("Lūdzu ievadiet argumentu x = "); scanf("%lf",&x); y = (1+x)*exp(x); printf(""); printf(" 1000 \n"); printf(" _________ \n"); printf(" \\ k \n"); printf(" \\ (1 + x) * x \n"); printf(" (1+x)*exp(x) = > __________________ \n"); printf(" / \n"); printf(" /_________ k! \n"); printf(" k=0 \n"); printf(" \n"); printf(" \n"); printf(" x \n"); printf(" Rekurences reizinatajs: ____________ \n"); printf(" \n"); printf(" k \n"); printf("standarta funkcija− y= %.2f =%.2f \n" ,x , y ); printf("lietotajafunkcija − y=mans_exp %.2f =%.2f \n" ,x , mans_exp(x) ); ofstream mansout("mani_dati.txt"); ofstream out("dati.txt"); for(int i = -20;i<=20;i++) { // mansout << i << " "<< mans_exp(i) << endl; // out << i << " "<< (1+i)*exp(i) << endl; } mansout.close(); out.close(); return 0; }
/* * Copyright (c) 2017 Ensign Energy Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Ensign Energy Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Ensign Energy Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Ensign Energy Incorporated. */ #ifndef __AUTOTUNER_CONFIGURATION_REQUEST_PUBLISHER_H__ #define __AUTOTUNER_CONFIGURATION_REQUEST_PUBLISHER_H__ #include "publisher.h" #include "base_data_types.h" #include "autotuner_configuration.h" #include "autotuner_configurationSupport.h" namespace CAutoTunerConfigurationRequestPublisher { class CModelStateRequestPublisher : public TPublisher< AutoTunerConfiguration::ModelStateRequest > { public: CModelStateRequestPublisher(); ~CModelStateRequestPublisher(); bool Create(int32_t domain); bool Initialize(); bool PublishSample(); // Topic getters void SetPipeInnerDiameter(double pipeInnerDiameter); void SetPipeOuterDiameter(double pipeOuterDiameter); void SetSlopeFilter(double slopeFilter); void SetTauMax(double tauMax); void SetTauMin(double tauMin); void SetTauMultiplier(double tauMultiplier); void SetMaxDeviation(double maxDeviation); void SetMinInterval(double minInterval); }; class CWobTuningRequestPublisher : public TPublisher< AutoTunerConfiguration::WobTuningRequest > { public: CWobTuningRequestPublisher(); ~CWobTuningRequestPublisher(); bool Create(int32_t domain); bool Initialize(); bool PublishSample(); // Topic getters void SetWobFilter(double wobFilter); void SetWobD(double wobD); void SetWobF(double wobF); void SetWobEps(double wobEps); void SetWobEpsManual(bool wobEpsManual); void SetWobKcMin(double wobKcMin); void SetWobKcMax(double wobKcMax); void SetWobTiMin(double wobTiMin); void SetWobTiMax(double wobTiMax); }; class CDiffpTuningRequestPublisher : public TPublisher< AutoTunerConfiguration::DiffpTuningRequest > { public: CDiffpTuningRequestPublisher(); ~CDiffpTuningRequestPublisher(); bool Create(int32_t domain); bool Initialize(); bool PublishSample(); // Topic getters void SetDiffpFilter(double diffPFilter); void SetDiffpD(double diffPD); void SetDiffpF(double diffPF); void SetDiffpEps(double diffPEps); void SetDiffpEpsManual(bool diffPEpsManual); void SetDiffpKcMin(double diffPKcMin); void SetDiffpKcMax(double diffPKcMax); void SetDiffpTiMin(double diffPTiMin); void SetDiffpTiMax(double diffPTiMax); }; class CTorqueTuningRequestPublisher : public TPublisher< AutoTunerConfiguration::TorqueTuningRequest > { public: CTorqueTuningRequestPublisher(); ~CTorqueTuningRequestPublisher(); bool Create(int32_t domain); bool Initialize(); bool PublishSample(); // Topic getters void SetTorqueFilter(double torqueFilter); void SetTorqueD(double torqueD); void SetTorqueF(double torqueF); void SetTorqueEps(double torqueEps); void SetTorqueEpsManual(bool torqueEpsManual); void SetTorqueKcMin(double torqueKcMin); void SetTorqueKcMax(double torqueKcMax); void SetTorqueTiMin(double torqueTiMin); void SetTorqueTiMax(double torqueTiMax); }; }; #endif // __AUTOTUNER_CONFIGURATION_REQUEST_PUBLISHER_H__
// // Created by 史浩 on 2020-01-12. // #include "GLLooper.h" GLLooper::GLLooper() { mRender=new GLRender(); } GLLooper::~GLLooper() { delete mRender; mRender=0; } void GLLooper::handleMessage(LooperMessage *msg) { if(mRender==NULL){ return; } switch (msg->what){ case kMsgSurfaceCreated: mRender->surfaceCreated((ANativeWindow *)(msg->obj)); break; case kMsgSurfaceChanged: mRender->surfaceChanged(msg->arg1,msg->arg2); break; case kMsgSurfaceDestroyed: mRender->surfaceDestroyed(); break; case kMsgUpdateTexImage: mRender->updateTexImage((msg->obj), msg->arg1, msg->arg2); break; } }
#pragma once #include "window.h" #include "fps.h" #include "scene_controller.h" class GameInst { Window window; FPS fps; SceneController scenes; bool running = true; bool resetResources = false; public: GameInst(const GameInst&) = delete; GameInst& operator=(const GameInst&) = delete; static GameInst& GetInstance(); void Run(); FPSInfo FPS(); SceneController& GetSceneController(); Window& GetWindow(); private: GameInst() = default; ~GameInst() = default; void Load(); void Update(); void Clear(); void Draw(); void Render(); void Reload(); }; GameInst& Game();
#include<opencv.hpp> #include<iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { cout << "OpenCV Version: " << CV_VERSION << endl; Mat image; image = imread("images/photo.jpg"); if (!image.data) { printf("No image data \n"); return -1; } Mat gray_image; cvtColor(image, gray_image, COLOR_BGR2GRAY); imwrite("images/gray_image.jpg", gray_image); imshow("Image", image); imshow("Gray Image", gray_image); Point2f p(5, 1); cout << "Point(2D) = " << p << endl << endl; double t = (double)getTickCount(); t = ((double)getTickCount() - t) / getTickFrequency(); cout << "Time pass in seconds is :" << t << endl; waitKey(0); return 0; }
/* * 根据某个数值val将单链表分为两部分,一部分大于val,另一部分小于val */ #include <bits/stdc++.h> using namespace std; struct ListNode{ int data; ListNode *next; ListNode(int x):data(x),next(NULL){} }; class Solution{ public: ListNode* list_partition(ListNode *head,int val){ if(head == NULL){ return head; } ListNode *smallPtr = NULL; ListNode *smallHead = NULL; ListNode *largePtr = NULL; ListNode *largeHead = NULL; while(head){ ListNode *nextNode = head->next; head->next = NULL; if(head->data < val){ if(smallHead == NULL){ smallHead = head; smallPtr = smallHead; }else{ smallPtr->next = head; smallPtr = smallPtr->next; } }else{ if(largeHead == NULL){ largeHead = head; largePtr = largeHead; }else{ largePtr->next = head; largePtr = largePtr->next; } } head = nextNode; } if(smallHead != NULL){ smallPtr->next = largeHead; } return smallHead == NULL ? largeHead:smallHead; } }; int main(){ return 0; }
#include "StdAfx.h" #include "View2.h" #include "KEGIESDoc.h" #include "KEGIESView.h" #include "MainFrm.h" #include "GL\glut.h" #ifdef _DEBUG #define new DEBUG_NEW #endif IMPLEMENT_DYNCREATE(View2, CView) BEGIN_MESSAGE_MAP(View2, CView) // ON_WM_CREATE() ON_WM_KEYDOWN() ON_WM_SIZE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_TIMER() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_MOUSEWHEEL() END_MESSAGE_MAP() View2::View2(void) { } View2::~View2() { } void View2::InitGL() { COpenGL Initgl; //Init Initgl.SetHWND(m_hWnd); Initgl.SetupPixelFormat(); base=Initgl.base; m_hDC=Initgl.m_hDC; m_hRC=Initgl.m_hRC; m_Cam1 = AppSetting::loadcamera(); } void View2::OnDraw(CDC* pDC) { CKEGIESDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: wglMakeCurrent(m_hDC,m_hRC); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(1,1,1, 1); DrawView(); SwapBuffers(m_hDC); } void View2::DrawView() { CKEGIESDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; glPushMatrix(); UpdateView(); SetupView(); //drawAxis(true, &m_Cam1); pDoc->m_doc->draw2(m_displayMode); glPopMatrix(); glPopAttrib(); } BOOL View2::PreCreateWindow(CREATESTRUCT& cs) { return CView::PreCreateWindow(cs); } #ifdef _DEBUG void View2::AssertValid() const { CView::AssertValid(); } void View2::Dump(CDumpContext& dc) const { CView::Dump(dc); } CKEGIESDoc* View2::GetDocument() const // { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CKEGIESDoc))); return (CKEGIESDoc*)m_pDocument; } #endif //_DEBUG int View2::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; SetTimer(TIMER_UPDATE_VIEW,10,NULL); return 0; } void View2::OnInitialUpdate() { CView::OnInitialUpdate(); LEFT_DOWN=false; RIGHT_DOWN=false; InitGL(); } void View2::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); CSize size(cx,cy); m_WindowHeight=size.cy; m_WindowWidth=size.cx; } void View2::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { char lsChar; lsChar = char(nChar); CKEGIESDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); pDoc->m_doc->receiveKey(lsChar); if (nChar >= 48 && nChar <= 57 ) { m_displayMode[nChar - 48] = ! m_displayMode[nChar - 48]; } CView::OnKeyDown(nChar, nRepCnt, nFlags); } void View2::OnTimer(UINT_PTR nIDEvent) { if (nIDEvent == TIMER_UPDATE_VIEW) { InvalidateRect(NULL, FALSE); } CView::OnTimer(nIDEvent); } void View2::OnLButtonDown(UINT nFlags, CPoint point) { LEFT_DOWN=true; m_PreMousePos.x = point.x; m_PreMousePos.y = -point.y; CView::OnLButtonDown(nFlags, point); } void View2::OnLButtonUp(UINT nFlags, CPoint point) { LEFT_DOWN=false; CView::OnLButtonUp(nFlags, point); } void View2::OnRButtonDown(UINT nFlags, CPoint point) { RIGHT_DOWN=true; m_PreMousePos.x = point.x; m_PreMousePos.y = -point.y; CView::OnRButtonDown(nFlags, point); } void View2::OnRButtonUp(UINT nFlags, CPoint point) { RIGHT_DOWN=false; CView::OnRButtonUp(nFlags, point); } void View2::OnMouseMove(UINT nFlags, CPoint point) { m_MousePos.x=point.x; m_MousePos.y=-point.y; m_DMousePos=m_MousePos-m_PreMousePos; if(LEFT_DOWN) { m_Cam1.RotCamPos(m_DMousePos); } else if(RIGHT_DOWN) { m_Cam1.MoveCamPos(m_DMousePos); } m_PreMousePos=m_MousePos; CView::OnMouseMove(nFlags, point); } BOOL View2::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { vec3d temp; m_Cam1.m_Distance-=zDelta*m_Cam1.m_Distance*0.001; m_Cam1.RotCamPos(temp); return CView::OnMouseWheel(nFlags, zDelta, pt); } void View2::drawAxis(bool atOrigin, CCamera* cam) { glPushMatrix(); float lenght = 0.5*cam->m_Distance; if(!atOrigin) { float textPosX = -0.5*(m_WindowWidth/m_WindowHeight)*cam->m_Distance/1.4; float textPosY = -0.5*cam->m_Distance/1.4; float textPosZ = 0.0*cam->m_Distance; vec3d textPos = vec3d(textPosX,textPosY,textPosZ); matrix rotateM = cam->m_RotMatrix; textPos = rotateM.mulVector(textPos); glTranslatef(cam->m_Center.x, cam->m_Center.y,cam->m_Center.z); glTranslatef(textPos.x,textPos.y,textPos.z); lenght = 0.05*cam->m_Distance; } //Axis glBegin(GL_LINES); glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glVertex3f(lenght, 0, 0); glColor3f(0, 1, 0); glVertex3f(0, 0, 0); glVertex3f(0, lenght, 0); glColor3f(0, 0, 1); glVertex3f(0, 0, 0); glVertex3f(0, 0, lenght); glEnd(); glPopMatrix(); } void View2::SetupView() { // GLfloat diffuseLight[] = {0.4f,0.4f,0.4f,1.0f}; // GLfloat ambientLight[] = {0.2f,0.2f,0.2f,1.0f}; // GLfloat specular[] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat diffuseLight[] = { 0.2f, 0.2f, 0.2f, 1.0f }; GLfloat ambientLight[] = { 0.4f, 0.4f, 0.4f, 1.0f }; GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat position[] = { m_Cam1.m_Pos.x, m_Cam1.m_Pos.y, m_Cam1.m_Pos.z, 0.0 }; glEnable(GL_DEPTH_TEST); // glEnable(GL_CULL_FACE); // // glDisable(GL_DEPTH_TEST); // glBlendFunc(GL_SRC_ALPHA, GL_ONE); // glEnable(GL_BLEND); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_LIGHTING); glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight); glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0); glFrontFace(GL_CW); glShadeModel(GL_SMOOTH); //glShadeModel(GL_FLAT); glPolygonMode(GL_FRONT, GL_FILL); } void View2::UpdateView() { int _w = m_WindowWidth; int _h = m_WindowHeight; glViewport(0,0,_w,_h); float fovy=45; float aspect=float(_w)/float(_h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, aspect, 1, 10000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_Cam1.m_Pos.x,m_Cam1.m_Pos.y,m_Cam1.m_Pos.z, m_Cam1.m_Center.x,m_Cam1.m_Center.y,m_Cam1.m_Center.z, m_Cam1.m_Up.x,m_Cam1.m_Up.y,m_Cam1.m_Up.z); }
#pragma once #include "IBehavior.h" #include <vector> namespace Hourglass { class Parallel : public IBehavior { public: virtual void LoadFromXML( tinyxml2::XMLElement* data ); void AddBehavior( IBehavior* behavior ); void Clear() { m_NumChildren = 0; } virtual void DestroyDerived(); virtual bool IsRunningChild() const; virtual void Start(); virtual Result Run( Entity* entity ); virtual void Reset(); virtual void SetPolicy( IBehavior::Result policy ) { m_Policy = policy; }; /** * Make a copy of this component */ virtual IBehavior* MakeCopy() const; private: static const int32_t s_kNoRunningChild = -1; static const int32_t s_kMaxInParallel = 32; uint32_t m_FlagsRunningChildren; uint32_t m_NumChildren = 0; int32_t m_Policy; IBehavior* m_ChildBehaviors[s_kMaxInParallel]; }; }
/* 有这样一道智力题:“某商店规定:三个空汽水瓶可以换一瓶汽水。 小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是5瓶, 方法如下:先用9个空瓶子换3瓶汽水,喝掉3瓶满的,喝完以后4个空瓶子,用3个再换一瓶,喝掉这瓶满的,这时候剩2个空瓶子。然后你让老板先借给你一瓶汽水,喝掉这瓶满的,喝完以后用3个空瓶子换一瓶满的还给老板。 如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝? */ #include "iostream" using namespace std; int main(){ int num; int temp; int amount; while(cin >> num && num != 0){ temp = num; amount = 0; while(temp > 2){ amount += temp / 3; temp = temp % 3 + temp / 3; } if(temp == 2){ cout << amount + 1 << endl; }else{ cout << amount << endl; } } return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int inf = 1e9 + 7; int a[110],sum[110],f[110][110]; int query(int l,int r) { return (sum[r] - sum[l-1] + 100)%100; } int main() { int t,n; scanf("%d",&t); while (t--) { memset(sum,0,sizeof(sum)); scanf("%d",&n); for (int i = 1;i <= n; i++) { scanf("%d",&a[i]); sum[i] = (sum[i-1] + a[i])%100; f[i][i] = 0; } for (int len = 1;len < n; len++) for (int i = 1;i + len <= n; i++) { int j = i + len; f[i][j] = inf; for (int k = i;k < j; k++) f[i][j] = min(f[i][j],f[i][k]+f[k+1][j]+query(i,k)*query(k+1,j)); } printf("%d\n",f[1][n]); } return 0; }
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef FILE_HPP_ #define FILE_HPP_ #include "../hal/Dev.hpp" #include "../var/String.hpp" #ifdef fileno #undef fileno #endif namespace sys { /*! \brief File Class * \details This class is used to file access. It uses the POSIX functions open(), read(), write(), close(), etc. You * can always call these functions directly or use the standard C library to access files (fopen(), fread(), fwrite()-- * these use more memory than this class or the POSIX functions). * * Here is an example of using this class: * * \code * #include <stfy/Sys.hpp> * #include <stfy/Var.hpp> * * * int main(int argc, char * argv[]){ * File f; * String str; * * //create a new file and write a string to it * f.create("/home/myfile.txt"); * str = "Hello New File!\n"; * f.write(str.c_str(), str.size()); * f.close(); * * //Now open the file we just closed * f.open("/home/myfile.txt"); * str = ""; * f.read(str.data(), str.capacity()); * f.close(); * * //This is what was read from the file * printf("The String is %s\n", str.c_str()); * * File::remove("/home/myfile.txt"); //delete the file * return 0; * } * * \endcode * */ class File : public hal::Dev { public: File(); /*! \details Delete a file */ static int remove(const char * name, link_transport_mdriver_t * driver = 0); /*! \details Get file stat data * * @param name The path to the file * @param st A pointer to the stat structure * */ static int stat(const char * name, struct link_stat * st, link_transport_mdriver_t * driver = 0); /*! \details Get the size of the file */ static ssize_t size(const char * name, link_transport_mdriver_t * driver = 0); /*! \details This opens a file. If the object already has a file open, the open * file will be closed first. * * @param name The filename to open * @param access The access ie RDWR * @param perms Permission settings * @return Zero on success */ int open(const char * name, int access, int perms); using Dev::open; /*! \details Open file for read/write */ inline int open_readwrite(const char * name){ return open(name, RDWR); } /*! \details Open a read only file */ inline int open_readonly(const char * name){ return open(name, READONLY); } /*! \details Open a file for appending */ inline int open_append(const char * name){ return open(name, APPEND | CREATE | WRITEONLY); } /*! \details Create a new file (using the open() method) */ int create(const char * name, bool overwrite = true, int perms = 0666); /*! \details Return the file size */ ssize_t size() const; private: }; }; #endif /* FILE_HPP_ */
// // Created by Guillaume Doucet on 2020-10-07. // #ifndef EX2_ECBOPERATIONMODE_H #define EX2_ECBOPERATIONMODE_H #include <string> #include "Base/OperationModeBase.h" class ECBOperationMode : protected OperationModeBase { public: std::string encryptDecrypt(const std::string& targetText, const std::string& key); private: static std::string encryptDecryptInternal(const std::string& text, const std::string& key); }; #endif //EX2_ECBOPERATIONMODE_H
#include <stdio.h> #include <stdlib.h> long long potencia(int base, int expoente); int main() { int r; long long x; scanf("%d", &r); x = potencia(3,r); printf("%lli\n", x); return 0; } long long potencia(int base, int expoente){ long long retorno = base; if(expoente == 0){ return 1; } for(int i=0;i<expoente-1; i++){ retorno = retorno * base; } return retorno; }
#include <core/Godot.hpp> #include <utils.h> #include "gdnative_setup.h" #include "gast_loader.h" #include "gast_node.h" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *options) { godot::Godot::gdnative_init(options); } void GDN_EXPORT godot_gdnative_singleton() {} void GDN_EXPORT godot_nativescript_init(void *handle) { godot::Godot::nativescript_init(handle); godot::register_class<gast::GastLoader>(); godot::register_class<gast::GastNode>(); } void GDN_EXPORT godot_nativescript_terminate(void *handle) { godot::Godot::nativescript_terminate(handle); } void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *options) { godot::Godot::gdnative_terminate(options); }
#include "SubOwnDot.hpp" #include "SubOwnDot_p.hpp" namespace InIncludes { class SubOwnDotLocal : public QObject { Q_OBJECT public: SubOwnDotLocal(); ~SubOwnDotLocal(); }; SubOwnDotLocal::SubOwnDotLocal() { } SubOwnDotLocal::~SubOwnDotLocal() { } SubOwnDotPrivate::SubOwnDotPrivate() { } SubOwnDotPrivate::~SubOwnDotPrivate() { } SubOwnDot::SubOwnDot() { SubOwnDotPrivate privateObj; SubOwnDotLocal localObj; } SubOwnDot::~SubOwnDot() { } } // End of namespace // For the local QObject #include "SubOwnDot.moc"