int main(int argc, char **argv) { #ifdef CONSOLE_APPLICATION QApplication app(argc, argv, QApplication::Tty); #else QApplication app(argc, argv); #endif #ifdef DO_QWS_DEBUGGING qt_show_painter_debug_output = false; #endif DeviceType type = WidgetType; bool checkers_background = true; QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied; QLocale::setDefault(QLocale::c()); QStringList files; bool interactive = false; bool printdlg = false; bool highres = false; bool show_cmp = false; int width = 800, height = 800; int scaledWidth = width, scaledHeight = height; qreal scalefactor = 1.0; bool verboseMode = false; #ifndef QT_NO_OPENGL QGLFormat f = QGLFormat::defaultFormat(); f.setSampleBuffers(true); f.setStencil(true); f.setAlpha(true); f.setAlphaBufferSize(8); QGLFormat::setDefaultFormat(f); #endif char *arg; for (int i=1; i<argc; ++i) { arg = argv[i]; if (*arg == '-') { QString option = QString(arg + 1).toLower(); if (option == "widget") type = WidgetType; else if (option == "bitmap") type = BitmapType; else if (option == "pixmap") type = PixmapType; else if (option == "image") type = ImageType; else if (option == "imageformat") { Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value"); QString format = QString(argv[++i]).toLower(); imageFormat = QImage::Format_Invalid; static const int formatCount = sizeof(imageFormats) / sizeof(imageFormats[0]); for (int ff = 0; ff < formatCount; ++ff) { if (QLatin1String(imageFormats[ff].name) == format) { imageFormat = imageFormats[ff].format; break; } } if (imageFormat == QImage::Format_Invalid) { printf("Invalid image format. Available formats are:\n"); for (int ff = 0; ff < formatCount; ++ff) printf("\t%s\n", imageFormats[ff].name); return -1; } } else if (option == "imagemono") type = ImageMonoType; else if (option == "imagewidget") type = ImageWidgetType; #ifndef QT_NO_OPENGL else if (option == "opengl") type = OpenGLType; else if (option == "glbuffer") type = OpenGLBufferType; #endif #ifdef USE_CUSTOM_DEVICE else if (option == "customdevice") type = CustomDeviceType; else if (option == "customwidget") type = CustomWidgetType; #endif else if (option == "pdf") type = PdfType; else if (option == "ps") type = PsType; else if (option == "picture") type = PictureType; else if (option == "printer") type = PrinterType; else if (option == "highres") { type = PrinterType; highres = true; } else if (option == "printdialog") { type = PrinterType; printdlg = true; } else if (option == "grab") type = GrabType; else if (option == "i") interactive = true; else if (option == "v") verboseMode = true; else if (option == "commands") { displayCommands(); return 0; } else if (option == "w") { Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value"); width = atoi(argv[++i]); } else if (option == "h") { Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value"); height = atoi(argv[++i]); } else if (option == "scalefactor") { Q_ASSERT_X(i + 1 < argc, "main", "-scalefactor must be followed by a value"); scalefactor = atof(argv[++i]); } else if (option == "cmp") { show_cmp = true; } else if (option == "bg-white") { checkers_background = false; } } else { #if defined (Q_WS_WIN) QString input = QString::fromLocal8Bit(argv[i]); if (input.indexOf('*') >= 0) { QFileInfo info(input); QDir dir = info.dir(); QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName())); for (int ii=0; ii<infos.size(); ++ii) files.append(infos.at(ii).absoluteFilePath()); } else { files.append(input); } #else files.append(QString(argv[i])); #endif } } scaledWidth = width * scalefactor; scaledHeight = height * scalefactor; PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); QWidget *activeWidget = 0; if (interactive) { runInteractive(); if (!files.isEmpty()) interactive_widget->load(files.at(0)); } else if (files.isEmpty()) { printHelp(); return 0; } else { for (int j=0; j<files.size(); ++j) { const QString &fileName = files.at(j); QStringList content; QFile file(fileName); QFileInfo fileinfo(file); if (file.open(QIODevice::ReadOnly)) { QTextStream textFile(&file); QString script = textFile.readAll(); content = script.split("\n", QString::SkipEmptyParts); } else { printf("failed to read file: '%s'\n", qPrintable(fileinfo.absoluteFilePath())); continue; } pcmd.setContents(content); if (show_cmp) { QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png"; qDebug() << pmFile << QFileInfo(pmFile).exists(); QPixmap pixmap(pmFile); if (!pixmap.isNull()) { QLabel *label = createLabel(); label->setWindowTitle("VERIFY: " + pmFile); label->setPixmap(pixmap); label->show(); } } switch (type) { case WidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLBufferType: { QWindow win; win.setSurfaceType(QSurface::OpenGLSurface); win.create(); QOpenGLFramebufferObjectFormat fmt; fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); fmt.setSamples(4); QOpenGLContext ctx; ctx.create(); ctx.makeCurrent(&win); QOpenGLFramebufferObject fbo(width, height, fmt); fbo.bind(); QOpenGLPaintDevice pdev(width, height); QPainter pt(&pdev); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = fbo.toImage(); QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case OpenGLType: { OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>(files.at(j)); qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: case OpenGLBufferType: { printf("OpenGL type not supported in this Qt build\n"); break; } #endif #ifdef USE_CUSTOM_DEVICE case CustomDeviceType: { CustomPaintDevice custom(width, height); QPainter pt; pt.begin(&custom); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage *img = custom.image(); if (img) { QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(*img)); label->resize(label->sizeHint()); label->show(); activeWidget = label; img->save("custom_output_pixmap.png", "PNG"); } else { custom.save("custom_output_pixmap.png", "PNG"); } break; } case CustomWidgetType: { OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>; cWidget->setVerboseMode(verboseMode); cWidget->setType(type); cWidget->setCheckersBackground(checkers_background); cWidget->m_filename = files.at(j); cWidget->setWindowTitle(fileinfo.filePath()); cWidget->m_commands = content; cWidget->resize(width, height); cWidget->show(); activeWidget = cWidget; break; } #endif case PixmapType: { QPixmap pixmap(scaledWidth, scaledHeight); pixmap.setDevicePixelRatio(scalefactor); pixmap.fill(Qt::white); QPainter pt(&pixmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); pixmap.save("output_pixmap.png", "PNG"); break; } case BitmapType: { QBitmap bitmap(scaledWidth, scaledHeight); bitmap.setDevicePixelRatio(scalefactor); QPainter pt(&bitmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); bitmap.save("output_bitmap.png", "PNG"); QLabel *label = createLabel(); label->setPixmap(bitmap); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case ImageMonoType: case ImageType: { qDebug() << "Creating image"; QImage image(scaledWidth, scaledHeight, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); image.setDevicePixelRatio(scalefactor); image.fill(0); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG"); image.setDevicePixelRatio(1.0); // reset scale factor: display "large" image. #ifndef CONSOLE_APPLICATION QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; #endif break; } case PictureType: { QPicture pic; QPainter pt(&pic); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(0); pt.begin(&image); pt.drawPicture(0, 0, pic); pt.end(); QLabel *label = createLabel(); label->setWindowTitle(fileinfo.absolutePath()); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case PrinterType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QString file = QString(files.at(j)).replace(".", "_") + ".ps"; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); if (printdlg) { QPrintDialog printDialog(&p, 0); if (printDialog.exec() != QDialog::Accepted) break; } else { p.setOutputFileName(file); } QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); if (!printdlg) { printf("wrote file: %s\n", qPrintable(file)); } Q_ASSERT(!p.paintingActive()); #endif break; } case PsType: case PdfType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); const QString file = input.baseName() + QLatin1Char('_') + input.suffix() + QStringLiteral(".pdf"); p.setOutputFormat(QPrinter::PdfFormat); p.setOutputFileName(file); p.setPageSize(QPrinter::A4); QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); printf("write file: %s\n", qPrintable(file)); #endif break; } case GrabType: { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::white).rgb()); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image1(width, height, QImage::Format_RGB32); image1.fill(QColor(Qt::white).rgb()); QPainter pt1(&image1); pt1.drawImage(QPointF(0, 0), image); pt1.end(); QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png"; image1.save(filename, "PNG"); printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename)); break; } default: break; } } } #ifndef CONSOLE_APPLICATION if (activeWidget || interactive) { QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); app.exec(); } delete activeWidget; #endif delete interactive_widget; return 0; }
void CCompareResultsDlg::OnItemChanging(NMHDR *pNMHDR, LRESULT *pLResult) { *pLResult = FALSE; // Allow change NMLISTVIEW *pNMLV = reinterpret_cast<NMLISTVIEW *>(pNMHDR); int irow = pNMLV->iItem; // Check if state unchanged - unchanged == not interested if ((pNMLV->uChanged & LVIF_STATE) != LVIF_STATE) return; // Has the selected state changed? // Was selected and now not or Wasn't selected and still isn't - ignore if (((pNMLV->uOldState & LVIS_SELECTED)!= 0 && (pNMLV->uNewState & LVIS_SELECTED) == 0) || ((pNMLV->uOldState & LVIS_SELECTED) == 0 && (pNMLV->uNewState & LVIS_SELECTED) == 0)) { return; } DWORD_PTR dwItemData = m_LCResults.GetItemData(irow); st_CompareData *pst_data = GetCompareData(dwItemData); ASSERT(pst_data != NULL); CPoint pt(GetMessagePos()); m_LCResults.ScreenToClient(&pt); LVHITTESTINFO hti = {0}; hti.pt = pt; int iItem = m_LCResults.SubItemHitTest(&hti); // Ignore any clicks not on an item if (iItem == -1 || hti.flags & (LVHT_NOWHERE | LVHT_ABOVE | LVHT_BELOW | LVHT_TORIGHT | LVHT_TOLEFT)) { return; } if ((GetKeyState(VK_CONTROL) & 0x8000)) { // Control key pressed - multi-select /* Since we only allow multi-select for Copy or Synchronise from Compare DB to the original Db, we won't allow if row entry is not in the Compare DB ... pst_data->indatabase == CURRENT We also won't allow if entry is in the original DB and protected. ... pst_data->bIsProtected0 or if the first of the multiple selection was not in the Compare DB ... m_bFirstInCompare or if user changes column ... m_LCResults.GetColumn() == pNMLV->iSubItem No point if original is R-O or if already equal to original ... !m_bOriginalDBReadOnly || pst_data->indatabase == IDENTICAL */ if (pst_data->indatabase == CURRENT || pst_data->indatabase == IDENTICAL || pst_data->bIsProtected0 || !m_bFirstInCompare || m_bOriginalDBReadOnly || m_LCResults.GetColumn() != hti.iSubItem) { *pLResult = TRUE; // Deny change return; } } else { // Single-select or first selection m_bFirstInCompare = pst_data->indatabase != CURRENT; // Not in Current DB only } }
LRESULT CCEGLView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { BOOL bProcessed = FALSE; //CCLog("wParam:%d", wParam); switch (message) { case WM_MOUSEWHEEL: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_pDelegate) { POINT point = { (short)LOWORD(lParam), (short)HIWORD(lParam) }; ScreenToClient(m_hWnd, &point); DPoint pt(point.x, point.y); pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); float zDelta = (short)HIWORD(wParam); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { m_bCaptured = true; SetCapture(m_hWnd); CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::middleMouseEvent); handleScrollWheel(pt.x, pt.y, 0, zDelta, event); event->release(); } } break; case WM_MOUSEMOVE: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (MK_LBUTTON == wParam && m_bCaptured) { POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)}; DPoint pt(point.x, point.y); int id = 0; pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::leftMouseEvent); handleTouchesMove(1, &id, &pt.x, &pt.y, event); event->release(); event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::movedMouseEvent); handleMouseMoved(pt.x, pt.y, event); event->release(); } break; case WM_MBUTTONDOWN: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_pDelegate && MK_MBUTTON == wParam) { POINT point = { (short)LOWORD(lParam), (short)HIWORD(lParam) }; DPoint pt(point.x, point.y); pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { m_bCaptured = true; SetCapture(m_hWnd); int id = 0; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::middleMouseEvent); handleOtherMouseDown(1, &id, &pt.x, &pt.y, event); event->release(); } } break; case WM_MBUTTONUP: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_pDelegate) { POINT point = { (short)LOWORD(lParam), (short)HIWORD(lParam) }; DPoint pt(point.x, point.y); pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { m_bCaptured = true; SetCapture(m_hWnd); int id = 0; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::middleMouseEvent); handleOtherMouseUp(1,&id, &pt.x, &pt.y, event); event->release(); } } break; case WM_LBUTTONDOWN: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_pDelegate && MK_LBUTTON == wParam) { POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)}; DPoint pt(point.x, point.y); pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { m_bCaptured = true; SetCapture(m_hWnd); int id = 0; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::leftMouseEvent); handleTouchesBegin(1, &id, &pt.x, &pt.y, event); event->release(); } } break; case WM_LBUTTONUP: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_bCaptured) { POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)}; DPoint pt(point.x, point.y); int id = 0; pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::leftMouseEvent); handleTouchesEnd(1, &id, &pt.x, &pt.y, event); event->release(); ReleaseCapture(); m_bCaptured = false; } break; case WM_RBUTTONDOWN: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_pDelegate && MK_RBUTTON == wParam) { POINT point = { (short)LOWORD(lParam), (short)HIWORD(lParam) }; DPoint pt(point.x, point.y); pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { m_bCaptured = true; SetCapture(m_hWnd); int id = 0; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::rightMouseEvent); handleTouchesBegin(1, &id, &pt.x, &pt.y, event); event->release(); } } break; case WM_RBUTTONUP: #if(_MSC_VER >= 1600) // Don't process message generated by Windows Touch if (m_bSupportTouch && (s_pfGetMessageExtraInfoFunction() & MOUSEEVENTF_FROMTOUCH) == MOUSEEVENTF_FROMTOUCH) break; #endif /* #if(_MSC_VER >= 1600) */ if (m_bCaptured) { POINT point = { (short)LOWORD(lParam), (short)HIWORD(lParam) }; DPoint pt(point.x, point.y); int id = 0; pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::rightMouseEvent); handleTouchesEnd(1, &id, &pt.x, &pt.y, event); event->release(); ReleaseCapture(); m_bCaptured = false; } break; #if(_MSC_VER >= 1600) case WM_TOUCH: { BOOL bHandled = FALSE; UINT cInputs = LOWORD(wParam); PTOUCHINPUT pInputs = new TOUCHINPUT[cInputs]; if (pInputs) { if (s_pfGetTouchInputInfoFunction((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) { for (UINT i=0; i < cInputs; i++) { TOUCHINPUT ti = pInputs[i]; POINT input; input.x = TOUCH_COORD_TO_PIXEL(ti.x); input.y = TOUCH_COORD_TO_PIXEL(ti.y); ScreenToClient(m_hWnd, &input); DPoint pt(input.x, input.y); DPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y); if (m_obViewPortRect.equals(DRectZero) || m_obViewPortRect.containsPoint(tmp)) { pt.x /= m_fFrameZoomFactor; pt.y /= m_fFrameZoomFactor; CrossApp::CAEvent* event = new CrossApp::CAEvent(); event->setEventType(CrossApp::EventType::leftMouseEvent); if (ti.dwFlags & TOUCHEVENTF_DOWN) handleTouchesBegin(1, reinterpret_cast<int*>(&ti.dwID), &pt.x, &pt.y, event); else if (ti.dwFlags & TOUCHEVENTF_MOVE) handleTouchesMove(1, reinterpret_cast<int*>(&ti.dwID), &pt.x, &pt.y, event); else if (ti.dwFlags & TOUCHEVENTF_UP) handleTouchesEnd(1, reinterpret_cast<int*>(&ti.dwID), &pt.x, &pt.y, event); event->release(); } } bHandled = TRUE; } delete [] pInputs; } if (bHandled) { s_pfCloseTouchInputHandleFunction((HTOUCHINPUT)lParam); } } break; #endif /* #if(_MSC_VER >= 1600) */ case WM_SIZE: { static int oldWidth = 0, oldHeight = 0, windowState = 0; switch (wParam) { case SIZE_RESTORED: { if (windowState == 2) { CCApplication::sharedApplication()->applicationWillEnterForeground(); } else if (windowState == 1) { this->setFrameSize(oldWidth, oldHeight); CCApplication::sharedApplication()->applicationDidExitFullScreen(); } windowState = 0; } break; case SIZE_MAXIMIZED: { if (windowState == 2) { CCApplication::sharedApplication()->applicationWillEnterForeground(); } else if (windowState == 0) { oldWidth = m_obScreenSize.width * 2; oldHeight = m_obScreenSize.height * 2; RECT rt; SystemParametersInfo(SPI_GETWORKAREA, 0, &rt, 0); // 获得工作区大小 int w = (rt.right - rt.left) * 2; int h = (rt.bottom - rt.top - 24) * 2; this->setFrameSize(w, h); CCApplication::sharedApplication()->applicationDidToggleFullScreen(); } windowState = 1; } break; case SIZE_MINIMIZED: { CCApplication::sharedApplication()->applicationDidEnterBackground(); windowState = 2; } break; } } break; case WM_KEYDOWN: switch (wParam) { case VK_F1: if (GetKeyState(VK_LSHIFT) < 0 || GetKeyState(VK_RSHIFT) < 0 || GetKeyState(VK_SHIFT) < 0) CAApplication::getApplication()->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked); break; case VK_F2: if (GetKeyState(VK_LSHIFT) < 0 || GetKeyState(VK_RSHIFT) < 0 || GetKeyState(VK_SHIFT) < 0) CAApplication::getApplication()->getKeypadDispatcher()->dispatchKeypadMSG(kTypeMenuClicked); break; case VK_ESCAPE: CAApplication::getApplication()->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked); break; case VK_LEFT: CAIMEDispatcher::sharedDispatcher()->dispatchCursorMoveBackward(); break; case VK_RIGHT: CAIMEDispatcher::sharedDispatcher()->dispatchCursorMoveForward(); break; case VK_UP: CAIMEDispatcher::sharedDispatcher()->dispatchCursorMoveUp(); break; case VK_DOWN: CAIMEDispatcher::sharedDispatcher()->dispatchCursorMoveDown(); break; case 'C': case 'X': if (GetKeyState(VK_CONTROL) < 0) { if (wParam == 'C') { CAIMEDispatcher::sharedDispatcher()->dispatchCopyToClipboard(); } else { CAIMEDispatcher::sharedDispatcher()->dispatchCutToClipboard(); } } break; case 'V': if (GetKeyState(VK_CONTROL) < 0) { CAIMEDispatcher::sharedDispatcher()->dispatchPasteFromClipboard(); } break; case 'A': if (GetKeyState(VK_CONTROL) < 0) { CAIMEDispatcher::sharedDispatcher()->dispatchSelectAll(); } break; default: break; } if ( m_lpfnAccelerometerKeyHook!=NULL ) { (*m_lpfnAccelerometerKeyHook)( message,wParam,lParam ); } break; case WM_KEYUP: if ( m_lpfnAccelerometerKeyHook!=NULL ) { (*m_lpfnAccelerometerKeyHook)( message,wParam,lParam ); } break; case WM_CHAR: { if (wParam < 0x20) { if (VK_BACK == wParam) { CAIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); } else if (VK_RETURN == wParam) { CAIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1); } else if (VK_TAB == wParam) { // tab input } else if (VK_ESCAPE == wParam) { // ESC input //CCDirector::sharedDirector()->end(); } } else if (wParam < 128) { // ascii char CAIMEDispatcher::sharedDispatcher()->dispatchInsertText((const char *)&wParam, 1); } else { char szUtf8[8] = {0}; int nLen = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)&wParam, 1, szUtf8, sizeof(szUtf8), NULL, NULL); CAIMEDispatcher::sharedDispatcher()->dispatchInsertText(szUtf8, nLen); } if ( m_lpfnAccelerometerKeyHook!=NULL ) { (*m_lpfnAccelerometerKeyHook)( message,wParam,lParam ); } } break; case WM_PAINT: PAINTSTRUCT ps; BeginPaint(m_hWnd, &ps); EndPaint(m_hWnd, &ps); break; case WM_CLOSE: CAApplication::getApplication()->end(); break; case WM_DESTROY: destroyGL(); PostQuitMessage(0); break; default: if (m_wndproc) { m_wndproc(message, wParam, lParam, &bProcessed); if (bProcessed) break; } return DefWindowProc(m_hWnd, message, wParam, lParam); } if (m_wndproc && !bProcessed) { m_wndproc(message, wParam, lParam, &bProcessed); } return 0; }
bool CGdiPlusImage::DrawImage(CDC* pDC) { //´´½¨ÆÁÄ» ASSERT(pDC!=NULL); if ( !pDC ) return false; Bitmap bmp(m_rcDest.Width(), m_rcDest.Height()); Graphics* pGraphics = Graphics::FromImage(&bmp); if ( !pGraphics ) return false; GraphicsContainer Containter = pGraphics->BeginContainer(); pGraphics->SetSmoothingMode(SmoothingModeHighQuality); SolidBrush bgbrush(Color(238, 243, 250)); pGraphics->FillRectangle(&bgbrush, 0, 0, m_rcDest.Width(), m_rcDest.Height()); if ( m_pImage ) { //»ñÈ¡ÊôÐÔ INT nImageWidth = m_pImage->GetWidth(); INT nImageHeight = m_pImage->GetHeight(); float fMin = 1.0F; float fZoomRate = 1.0F; bool bZoomOut = false; int nXSrc = 0; int nYSrc = 0; if ( nImageWidth >= m_rcDest.Width() || nImageHeight >= m_rcDest.Height() ) { float fXRate = 1.0F * m_rcDest.Width() / nImageWidth; float fYRate = 1.0F * m_rcDest.Height() / nImageHeight; fMin = min(fXRate, fYRate); fZoomRate = max(nImageWidth * 1.0F / m_rcDest.Width(), nImageHeight * 1.0F / m_rcDest.Height()); bZoomOut = true; } int nDestWidth = fMin * nImageWidth; int nDestHeight = fMin * nImageHeight; //¹¹ÔìλÖà RectF rcDrawRect; rcDrawRect.X = m_rcDest.left + (m_rcDest.Width() - nDestWidth ) / 2; rcDrawRect.Y = m_rcDest.top + (m_rcDest.Height() - nDestHeight ) / 2; rcDrawRect.Width = nDestWidth; rcDrawRect.Height = nDestHeight; Matrix matrix; CPoint pt(m_rcDest.Width() / 2, m_rcDest.Height() / 2); PointF ptBase((float)pt.x, (float)pt.y); //¾ØÕó±ä»»Òª×¢Òâ˳Ðò£¬ÏÈƽÒÆÔÚËõ·ÅºóÐýת matrix.Translate((REAL)m_rcDest.left,(REAL)m_rcDest.top,MatrixOrderAppend); //Ëõ·Å if ( m_szZoom.cx != 1.0f || m_szZoom.cy != 1.0f ) { ptBase.X += m_szZoom.cx; ptBase.Y += m_szZoom.cy; matrix.Translate(-ptBase.X,-ptBase.Y,MatrixOrderAppend); matrix.Scale(m_szZoom.cx,m_szZoom.cy,MatrixOrderAppend); matrix.Translate(ptBase.X,ptBase.Y,MatrixOrderAppend); } //Ðýת if (m_nRotateAngle) { matrix.RotateAt((REAL)m_nRotateAngle,ptBase,MatrixOrderAppend); } pGraphics->SetTransform(&matrix); //͸Ã÷¾ØÕó ColorMatrix Matrix= { 1.0f,0.0f,0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f,m_cbAlphaDepth/255.0f,0.0f, 0.0f,0.0f,0.0f,0.0f,1.0f }; //ÉèÖÃÊôÐÔ ImageAttributes Attributes; Attributes.SetColorMatrix(&Matrix,ColorMatrixFlagsDefault,ColorAdjustTypeBitmap); //»æ»Í¼Ïñ pGraphics->DrawImage(m_pImage, rcDrawRect, nXSrc, nYSrc, (REAL)nImageWidth - nXSrc * 2, (REAL)nImageHeight - nYSrc * 2, UnitPixel,&Attributes); pGraphics->ResetTransform(); pGraphics->EndContainer(Containter); } // if ( m_pImage ) // ´ÓÄڴ濽±´ÖÁÉ豸 Graphics graphicsreal(pDC->GetSafeHdc()); graphicsreal.DrawImage(&bmp, 0, 0, m_rcDest.Width(), m_rcDest.Height()); delete pGraphics; pGraphics = NULL; return true; }
void CProgressCtrlEx::OnPaint() { CPaintDC paintDC(this); int nMin = 0; int nMax = 0; GetRange(nMin, nMax); ASSERT(nMin <= nMax); int nPos = GetPos(); ASSERT(nPos >= nMin && nPos <= nMax); DWORD dwStyle = GetStyle(); BOOL bVertical = FALSE; if (dwStyle & PBS_VERTICAL) { bVertical = TRUE; } CDC dc; dc.CreateCompatibleDC(&paintDC); ASSERT(dc.GetSafeHdc()); CRect rect; GetClientRect(&rect); CBitmap bmp; bmp.CreateCompatibleBitmap(&paintDC, rect.Width(), rect.Height()); ASSERT(bmp.GetSafeHandle()); CBitmap* pOldBitmap = (CBitmap*)dc.SelectObject(&bmp); CFont* pOldFont = NULL; CWnd* pParent = GetParent(); ASSERT(pParent); CFont* pFont = pParent->GetFont(); ASSERT(pFont); if (bVertical) { if (NULL == m_font.GetSafeHandle()) { LOGFONT lf = { 0 }; pFont->GetLogFont(&lf); lf.lfEscapement = 900; m_font.CreateFontIndirect(&lf); } ASSERT(m_font.GetSafeHandle()); pOldFont = (CFont*)dc.SelectObject(&m_font); } else { pOldFont = (CFont*)dc.SelectObject(pFont); } double dPercent = (double)(nPos - nMin) / ((double)(nMax - nMin)); dc.DrawEdge(rect, EDGE_SUNKEN, BF_RECT | BF_FLAT); CRect rc(rect); rc.DeflateRect(CSize(2, 2)); dc.FillSolidRect(&rc, m_clrBarBkColor); CString strText(_T("")); GetWindowText(strText); if (m_bShowPercent) { strText.AppendFormat(_T("%d%% "), static_cast<int>((dPercent * 100.0) + 0.5)); } dc.SetBkMode(TRANSPARENT); dc.SetTextColor(m_clrTextColor); CPoint pt(0, 0); CSize size = dc.GetOutputTextExtent(strText); if (!bVertical) { switch (m_AlignText) { case ALIGN_LEFT: pt.x = rc.left; break; case ALIGN_RIGHT: pt.x = rc.right - size.cx; break; case ALIGN_CENTER: default: pt.x = rc.left + (rc.Width() - size.cx) / 2; break; } pt.y = rc.top + (rc.Height() - size.cy) / 2; CRect rcPos(rc); rcPos.right = rcPos.left + (int)(dPercent * rcPos.Width()); dc.FillSolidRect(rcPos, m_clrBarColor); dc.SetTextColor(m_clrTextColor); dc.ExtTextOut(pt.x, pt.y, ETO_OPAQUE, rcPos, strText, NULL); dc.SetTextColor(m_clrTextBkColor); dc.ExtTextOut(pt.x, pt.y, ETO_CLIPPED, &rcPos, strText, NULL); } else { switch (m_AlignText) { case ALIGN_LEFT: pt.y = rc.bottom; break; case ALIGN_RIGHT: pt.y = rc.top + size.cx; break; case ALIGN_CENTER: default: pt.y = rc.bottom - (rc.Height() - size.cx) / 2; break; } pt.x = rc.left + (rc.Width() - size.cy) / 2; CRect rcPos(rc); rcPos.top = rcPos.bottom - (int)(dPercent * rcPos.Height()); dc.FillSolidRect(rcPos, m_clrBarColor); dc.SetTextColor(m_clrTextColor); dc.ExtTextOut(pt.x, pt.y, ETO_OPAQUE, rcPos, strText, NULL); dc.SetTextColor(m_clrTextBkColor); dc.ExtTextOut(pt.x, pt.y, ETO_CLIPPED, &rcPos, strText, NULL); } paintDC.BitBlt(rect.left, rect.top, rect.Width(), rect.Height(), &dc, 0, 0, SRCCOPY); dc.SelectObject(pOldFont); dc.SelectObject(pOldBitmap); bmp.DeleteObject(); dc.DeleteDC(); }
int sampleLine(const String &line, int y, String &code) { double mean = 0; int i=0, x=0, w=line.size(); // find quiet zones: Point sl = detail::quietZone(line, 0, w/2, 1, mean ); Point sr = detail::quietZone(line, w-1, w/2, -1, mean ); int distance = sr.x - sl.x; if ( distance < 58 ) { return 1; // too short } // try to sample a square wave from the grayscale data // between the quiet zones, // start at first black pixel bool last_state = true; vector<Point> pt(1,Point(0,0)); // pos,length, pos,length, .. for ( i = sl.x+1; i<sr.x; i++ ) { // todo : proper nms bool state = (line[i] < mean); // toggle state: if ( state != last_state ) { pt.push_back(Point(i, 1)); last_state = state; continue; } // state unchanged, increase length of current section pt.back().y ++; } // ean13 has 95 bits and 58 state toggles, // ean8 has 67 bits and 42 state toggles. double siz = distance; if ( pt.size() == 58 ) { siz /= 95.0; // ean13 } else if ( pt.size() == 42 ) { siz /= 67.0; // ean8 } else { return 2; // no match to either ean8 or ean13 } // scale pattern down to 1 pixel per bit: int sum = 0; double last = (sl.x+1); for( i=0; i<pt.size(); i++ ) { double d = pt[i].x - last; last = pt[i].x; d = int( 0.5 + d/siz ); // floor ? sum += d; pt[i].y = d; // now holds bit count } if ( sum > 95 ) { return 3; // too long } // make bitstring: bool bit = true; String bits = ""; for( int i=0; i<pt.size(); i++ ) { for( int j=0; j<pt[i].y; j++ ) { bits += ( bit ? '1' : '0' ); if ( bits.size() > 95 ) { return 4; // still too long } } bit = ! bit; } bits += '1'; if ( bits.size() == 67 ) return decode8( bits, code ); if ( bits.size() == 95 ) return decode13( bits, code ); return 4; // no match to either ean8 or ean13 }
void CSchemaCombo::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { if ( lpDrawItemStruct->itemID == (UINT)-1 ) return; if ( ( lpDrawItemStruct->itemAction & ODA_SELECT ) == 0 && ( lpDrawItemStruct->itemAction & ODA_DRAWENTIRE ) == 0 ) return; CRect rcItem( &lpDrawItemStruct->rcItem ); CPoint pt( rcItem.left + 1, rcItem.top + 1 ); CDC dc; dc.Attach( lpDrawItemStruct->hDC ); if ( Settings.General.LanguageRTL ) SetLayout( dc.m_hDC, LAYOUT_RTL ); dc.SetTextColor( ( lpDrawItemStruct->itemState & ODS_SELECTED ) ? CoolInterface.m_crHiText : CoolInterface.m_crDropdownText ); CSchemaPtr pSchema = (CSchemaPtr)lpDrawItemStruct->itemData; if ( pSchema != NULL ) { /*dc.FillSolidRect( &rcItem, GetSysColor( ( lpDrawItemStruct->itemState & ODS_SELECTED ) ? COLOR_HIGHLIGHT : COLOR_WINDOW ) );*/ if ( IsWindowEnabled() ) { if ( lpDrawItemStruct->itemState & ODS_SELECTED ) dc.FillSolidRect( &rcItem, CoolInterface.m_crHighlight ); else dc.FillSolidRect( &rcItem, CoolInterface.m_crDropdownBox ); } else dc.FillSolidRect( &rcItem, GetBkColor(lpDrawItemStruct->hDC) ); dc.SetBkMode( TRANSPARENT ); ShellIcons.Draw( &dc, pSchema->m_nIcon16, 16, pt.x, pt.y, CLR_NONE, ( lpDrawItemStruct->itemState & ODS_SELECTED ) ); rcItem.left += 20; rcItem.right -= 2; CFont* pOldFont = (CFont*)dc.SelectObject( &theApp.m_gdiFont ); CString strURI = pSchema->GetURI(); if ( dc.GetTextExtent( pSchema->m_sTitle + strURI ).cx > rcItem.Width() - 20 && strURI.GetLength() > 8 ) { LPCTSTR pszLeft = _tcschr( (LPCTSTR)strURI + 7, '/' ); int nRight = strURI.ReverseFind( '/' ); if ( pszLeft && nRight >= 0 ) { int nLeft = static_cast< int >( pszLeft - (LPCTSTR)strURI ); // !!! (TODO) strURI = strURI.Left( nLeft ) + _T("/\x2026") + strURI.Mid( nRight ); } } if ( dc.GetTextExtent( pSchema->m_sTitle + strURI ).cx <= rcItem.Width() - 20 ) { // COLORREF crBackup = dc.SetTextColor( GetSysColor( COLOR_GRAYTEXT ) ); dc.DrawText( strURI, &rcItem, DT_SINGLELINE|DT_RIGHT|DT_VCENTER|DT_NOPREFIX ); // dc.SetTextColor( crBackup ); } dc.SelectObject( &theApp.m_gdiFontBold ); dc.DrawText( pSchema->m_sTitle, &rcItem, DT_SINGLELINE|DT_LEFT|DT_VCENTER|DT_NOPREFIX ); dc.SelectObject( pOldFont ); } else if ( lpDrawItemStruct->itemID == 0 ) { /*dc.FillSolidRect( &rcItem, GetSysColor( ( lpDrawItemStruct->itemState & ODS_SELECTED ) ? COLOR_HIGHLIGHT : COLOR_WINDOW ) );*/ if ( IsWindowEnabled() ) { if ( lpDrawItemStruct->itemState & ODS_SELECTED ) dc.FillSolidRect( &rcItem, CoolInterface.m_crHighlight ); else dc.FillSolidRect( &rcItem, CoolInterface.m_crDropdownBox ); } else dc.FillSolidRect( &rcItem, GetBkColor(lpDrawItemStruct->hDC) ); dc.SetBkMode( TRANSPARENT ); CoolInterface.Draw( &dc, IDR_SEARCHFRAME, 16, pt.x, pt.y, CLR_NONE, ( lpDrawItemStruct->itemState & ODS_SELECTED ) ); rcItem.left += 20; rcItem.right -= 2; CFont* pOldFont = (CFont*)dc.SelectObject( &theApp.m_gdiFontBold ); dc.DrawText( m_sNoSchemaText, &rcItem, DT_SINGLELINE|DT_LEFT|DT_VCENTER|DT_NOPREFIX ); dc.SelectObject( pOldFont ); } else { dc.Draw3dRect( &rcItem, CoolInterface.m_crDropdownBox , CoolInterface.m_crDropdownBox ); rcItem.DeflateRect( 1, 1 ); if ( lpDrawItemStruct->itemState & ODS_SELECTED ) { dc.Draw3dRect( &rcItem, CoolInterface.m_crBorder, CoolInterface.m_crBorder ); rcItem.DeflateRect( 1, 1 ); dc.FillSolidRect( &rcItem, CoolInterface.m_crBackSel ); } else { dc.FillSolidRect( &rcItem, GetSysColor( COLOR_WINDOW /* COLOR_BTNFACE */ ) ); } dc.SetBkMode( TRANSPARENT ); pt = rcItem.CenterPoint(); pt.x -= 8; pt.y -= 8; CoolInterface.Draw( &dc, IDI_CHEVRON, 16, pt.x, pt.y ); } dc.Detach(); }
xs::Point GroundEyeshot::getViewLeftTop() { xs::Point pt (m_Eyeshot.getViewTopX(),m_Eyeshot.getViewTopY()); return pt; }
BOOL CCoolMenuBarCtrl::OnMenuMessage(MSG* pMsg) { if ( theApp.m_bClosing ) return FALSE; switch ( pMsg->message ) { case WM_MOUSEMOVE: { //CPoint pt( LOWORD( pMsg->lParam ), HIWORD( pMsg->lParam ) ); CPoint pt( pMsg->lParam ); ScreenToClient( &pt ); if ( m_pMouse == pt ) return TRUE; m_pMouse = pt; CCoolBarItem* pHit = HitTest( pt ); if ( pHit && pHit != m_pDown ) { if ( Settings.WINE.MenuFix ) PostMessage( WM_CANCELMODE, 0, 0 ); else SendMessage( WM_CANCELMODE, 0, 0 ); m_pHot = pHit; m_pDown = NULL; PostMessage( WM_TIMER, 4 ); return TRUE; } } break; case WM_LBUTTONDOWN: { //CPoint pt( LOWORD( pMsg->lParam ), HIWORD( pMsg->lParam ) ); CPoint pt( pMsg->lParam ); CWnd* pWnd = CWnd::WindowFromPoint( pt ); if ( pWnd ) { TCHAR szClass[2]; GetClassName( pWnd->GetSafeHwnd(), szClass, 2 ); if ( szClass[0] == '#' ) return FALSE; } ScreenToClient( &pt ); CCoolBarItem* pHit = HitTest( pt ); if ( pHit == NULL ) { m_pHot = m_pDown = NULL; if ( Settings.WINE.MenuFix ) PostMessage( WM_CANCELMODE, 0, 0 ); else SendMessage( WM_CANCELMODE, 0, 0 ); return TRUE; } else if ( pHit == m_pDown ) { m_pDown = NULL; PostMessage( WM_CANCELMODE, 0, 0 ); return TRUE; } } break; case WM_KEYDOWN: switch ( pMsg->wParam ) { case VK_LEFT: ShiftMenu( -1 ); return TRUE; case VK_RIGHT: ShiftMenu( 1 ); return TRUE; case VK_ESCAPE: PostMessage( WM_CANCELMODE, 0, 0 ); m_pHot = m_pDown = NULL; return TRUE; } break; default: break; } return FALSE; }
/* Can probably be made more efficient - like only checking one area */ static level_mask_t check_bg_collision(game_t *p_game, sprite_t *p_sprite, dir_t dir, point_t new_pt, point_t *p_overlap) { rect_t rect; int16_t x,y; rect = rect_add_pt(p_sprite->p_bounds[p_sprite->frame], new_pt); switch (dir) { case LEFT: rect.bottom_right.x = rect.top_left.x + TILE_W; rect.bottom_right.y-=TILE_H; break; case RIGHT: rect.top_left.x = rect.bottom_right.x - TILE_W; rect.bottom_right.y-=TILE_H; /* FIXME! Better with allow left/right */ break; case UP: rect.bottom_right.y = rect.top_left.y + TILE_W; break; case DOWN: rect.top_left.y = rect.bottom_right.y - TILE_W; break; } #ifndef NDEBUG { rect_t rect2 = rect_add_pt(p_sprite->p_bounds[p_sprite->frame], p_sprite->pt); draw_rect(p_game, rect2, vRGB(255,255,255)); } #endif draw_rect(p_game, rect, vRGB(255,0,0)); for (y = rect.top_left.y/TILE_H; y <= rect.bottom_right.y/TILE_H; y++) { for (x = rect.top_left.x/TILE_W; x <= rect.bottom_right.x/TILE_W; x++) { level_mask_t tile = tile_at(p_game, pt(x,y)); if (tile > 1) { rect_t tile_rect = rect_add_pt(tile_bounds[tile-1], pt_to_sprite(pt(x,y))); draw_rect(p_game, tile_rect, vRGB(0,255,0)); if (rect_overlap(tile_rect, rect, p_overlap)) { assert(tile != 0); #ifndef NDEBUG DbgPrintf(" %d:%d Tile %d rect %d:%d -> %d:%d (overlap %d,%d)\n\n", dir, p_sprite->state, tile, tile_rect.top_left.x,tile_rect.top_left.y, tile_rect.bottom_right.x, tile_rect.bottom_right.y, p_overlap->x, p_overlap->y ); vFlipScreen(0); #endif return tile; } } } } /* TMP! */ DbgPrintf("\n"); #ifndef NDEBUG vFlipScreen(0); #endif return 0; }
static void handle_input(game_t *p_game, uint32_t keys) { sprite_t *p_sprite = &p_game->player.sprite; if (!keys) { if (p_sprite->state == SPRITE_CROUCH) sprite_set_state(p_sprite, SPRITE_IDLE); } /* Handle running and jumping */ if (p_sprite->state == SPRITE_IDLE || p_sprite->state == SPRITE_RUN) { if (keys & KEY_LEFT) { p_sprite->state = SPRITE_RUN; p_sprite->dir = LEFT; } else if (keys & KEY_RIGHT) { p_sprite->state = SPRITE_RUN; p_sprite->dir = RIGHT; } if (keys & KEY_DOWN) sprite_set_state(p_sprite, SPRITE_CROUCH); /* Handle jumping */ if (p_sprite->state == SPRITE_IDLE && (keys & KEY_UP)) sprite_set_state(p_sprite, SPRITE_JUMP); else if (p_sprite->state == SPRITE_RUN && (keys & KEY_UP)) sprite_set_state(p_sprite, SPRITE_JUMP_RUN); } else if (p_sprite->state == SPRITE_CLIMB) { anim_table_t *p_cur = p_sprite->p_anims[SPRITE_CLIMB]; if (!keys) p_cur->entries[0].pt_offset = pt(0, 0); else { if (p_game->player.sprite.move_table_idx == 0) { if (p_cur->entries[0].anim_frame == FRAME_BRUCE_CLIMB) { p_cur->entries[0].anim_frame = FRAME_BRUCE_CLIMB+1; p_cur->entries[1].anim_frame = FRAME_BRUCE_CLIMB+1; } else { p_cur->entries[0].anim_frame = FRAME_BRUCE_CLIMB; p_cur->entries[1].anim_frame = FRAME_BRUCE_CLIMB; } } p_sprite->dir = RIGHT; if (keys & KEY_UP) p_cur->entries[0].pt_offset = pt(0, -4); else if (keys & KEY_DOWN) p_cur->entries[0].pt_offset = pt(0, 4); else if (keys & KEY_LEFT) p_cur->entries[0].pt_offset = pt(-4, 0); else if (keys & KEY_RIGHT) p_cur->entries[0].pt_offset = pt(4, 0); } /* Cannot hit etc when climbing */ return; } if (keys & KEY_FIRE) { if (p_sprite->state == SPRITE_RUN) sprite_set_state(p_sprite, SPRITE_KICK); else if (p_sprite->state == SPRITE_IDLE && p_sprite->state != SPRITE_HIT) sprite_set_state(p_sprite, SPRITE_HIT); } }
bool pointTest(const std::vector<Path>& paths, const std::vector<LineStyle>& lineStyles, std::int32_t x, std::int32_t y, const SWFMatrix& wm) { /* Principle: For the fill of the shape, we project a ray from the test point to the left side of the shape counting all crossings. When a line or curve segment is crossed we add 1 if the left fill style is set. Regardless of the left fill style we subtract 1 from the counter then the right fill style is set. This is true when the line goes in downward direction. If it goes upward, the fill styles are reversed. The final counter value reveals if the point is inside the shape (and depends on filling rule, see below). This method should not depend on subshapes and work for some malformed shapes situations: - wrong fill side (eg. left side set for a clockwise drawen rectangle) - intersecting paths */ point pt(x, y); // later we will need non-zero for glyphs... (TODO) bool even_odd = true; unsigned npaths = paths.size(); int counter = 0; // browse all paths for (unsigned pno=0; pno<npaths; pno++) { const Path& pth = paths[pno]; unsigned nedges = pth.m_edges.size(); float next_pen_x = pth.ap.x; float next_pen_y = pth.ap.y; float pen_x, pen_y; if (pth.empty()) continue; // If the path has a line style, check for strokes there if (pth.m_line != 0 ) { assert(lineStyles.size() >= pth.m_line); const LineStyle& ls = lineStyles[pth.m_line-1]; double thickness = ls.getThickness(); if (! thickness ) { thickness = 20; // at least ONE PIXEL thick. } else if ((!ls.scaleThicknessVertically()) && (!ls.scaleThicknessHorizontally()) ) { // TODO: pass the SWFMatrix to withinSquareDistance instead ? double xScale = wm.get_x_scale(); double yScale = wm.get_y_scale(); thickness *= std::max(xScale, yScale); } else if (ls.scaleThicknessVertically() != ls.scaleThicknessHorizontally()) { LOG_ONCE(log_unimpl(_("Collision detection for " "unidirectionally scaled strokes"))); } double dist = thickness / 2.0; double sqdist = dist * dist; if (pth.withinSquareDistance(pt, sqdist)) return true; } // browse all edges of the path for (unsigned eno=0; eno<nedges; eno++) { const Edge& edg = pth.m_edges[eno]; pen_x = next_pen_x; pen_y = next_pen_y; next_pen_x = edg.ap.x; next_pen_y = edg.ap.y; float cross1 = 0.0, cross2 = 0.0; int dir1 = 0, dir2 = 0; // +1 = downward, -1 = upward int crosscount = 0; if (edg.straight()) { // ignore horizontal lines // TODO: better check for small difference? if (edg.ap.y == pen_y) { continue; } // does this line cross the Y coordinate? if ( ((pen_y <= y) && (edg.ap.y >= y)) || ((pen_y >= y) && (edg.ap.y <= y)) ) { // calculate X crossing cross1 = pen_x + (edg.ap.x - pen_x) * (y - pen_y) / (edg.ap.y - pen_y); if (pen_y > edg.ap.y) dir1 = -1; // upward else dir1 = +1; // downward crosscount = 1; } else { // no crossing found crosscount = 0; } } else { // ==> curve case crosscount = curve_x_crossings<float>(pen_x, pen_y, edg.ap.x, edg.ap.y, edg.cp.x, edg.cp.y, y, cross1, cross2); dir1 = pen_y > y ? -1 : +1; dir2 = dir1 * (-1); // second crossing always in opposite dir. } // curve // ==> we have now: // - one (cross1) or two (cross1, cross2) ray crossings (X // coordinate) // - dir1/dir2 tells the direction of the crossing // (+1 = downward, -1 = upward) // - crosscount tells the number of crossings // need at least one crossing if (crosscount == 0) { continue; } // check first crossing if (cross1 <= x) { if (pth.m_fill0 > 0) counter += dir1; if (pth.m_fill1 > 0) counter -= dir1; } // check optional second crossing (only possible with curves) if ( (crosscount > 1) && (cross2 <= x) ) { if (pth.m_fill0 > 0) counter += dir2; if (pth.m_fill1 > 0) counter -= dir2; } }// for edge } // for path return ( (even_odd && (counter % 2) != 0) || (!even_odd && (counter != 0)) ); }
void CDlg_Chat_Clt::OnlineUserInfo(DWORD dwUserId, CStringArrayEx *pstrUserInfo) { if (NULL == pstrUserInfo) return; int nImageId = atoi((LPCTSTR)(*pstrUserInfo)[3]); m_wndOutlookBar.InsertItem(0, m_wndOutlookBar.GetItemCount(0), (LPCTSTR)(*pstrUserInfo)[1], nImageId, dwUserId); CString strCount; strCount.Format(_T("在线用户 (%d)"), m_wndOutlookBar.GetItemCount(0)); m_wndOutlookBar.SetFolderText(0, (LPCTSTR)strCount); if (m_dwMyId == dwUserId) { IMAGEINFO ImageInfo = {0}; g_ProFile.m_ImageList.GetImageInfo(nImageId, &ImageInfo); CSize szImage = CRect(ImageInfo.rcImage).Size(); CPoint pt(10, 50-szImage.cy-1); CDC dc; dc.Attach(m_hCompDC); g_ProFile.m_ImageList.Draw(&dc, nImageId, pt, ILD_NORMAL); dc.Detach(); RECT rcText = {15+szImage.cx, 30, 180, 50}; ::DrawText(m_hCompDC, (LPCTSTR)(*pstrUserInfo)[1], (*pstrUserInfo)[1].GetLength(), &rcText, DT_VCENTER|DT_SINGLELINE|DT_WORD_ELLIPSIS); } m_OnlineUserIdArray.Add(dwUserId); if (NULL == m_pFriendIdArray) return; for (int i = 0; i < m_pFriendIdArray->GetCount(); i++) { if (dwUserId == (*m_pFriendIdArray)[i]) { int j = 0; for (; j < m_OnlineFriendIdArray.GetCount(); j++) { if (dwUserId == m_OnlineFriendIdArray[j]) break; } if (j == m_OnlineFriendIdArray.GetCount()) { m_OnlineFriendIdArray.Add(dwUserId); int nImageId = atoi((LPCTSTR)(*pstrUserInfo)[3]); m_wndOutlookBar.InsertItem(1, j, (LPCTSTR)(*pstrUserInfo)[1], nImageId, dwUserId); strCount.Format(_T("我的好友 (%d/%d)"), m_OnlineFriendIdArray.GetCount(), m_pFriendIdArray->GetCount()); m_wndOutlookBar.SetFolderText(1, (LPCTSTR)strCount); } /* m_wndOutlookBar.RemoveItem(1, i); int nImageId = atoi((LPCTSTR)(*pstrUserInfo)[3]); m_wndOutlookBar.InsertItem(1, i, (LPCTSTR)(*pstrUserInfo)[1], nImageId, dwUserId); strCount.Format(_T("我的好友 (%d/%d)"), ++m_nOnlineFriends, m_wndOutlookBar.GetItemCount(1)); m_wndOutlookBar.SetFolderText(1, (LPCTSTR)strCount); */ break; } } m_wndOutlookBar.Invalidate(); }
void Button::init() { setFlags(ItemIsFocusable); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); title = new QPixmap(size.toSize()); title->fill(QColor(0, 0, 0, 0)); QPainter pt(title); pt.setFont(font); pt.setPen(Config.TextEditColor); pt.setRenderHint(QPainter::TextAntialiasing); pt.drawText(boundingRect(), Qt::AlignCenter, label); title_item = new QGraphicsPixmapItem(this); title_item->setPixmap(*title); title_item->show(); QGraphicsDropShadowEffect *de = new QGraphicsDropShadowEffect; de->setOffset(0); de->setBlurRadius(12); de->setColor(QColor(255, 165, 0)); title_item->setGraphicsEffect(de); QImage bgimg("image/system/button/button.png"); outimg = new QImage(size.toSize(), QImage::Format_ARGB32); qreal pad = 10; int w = bgimg.width(); int h = bgimg.height(); int tw = outimg->width(); int th = outimg->height(); qreal xc = (w - 2 * pad) / (tw - 2 * pad); qreal yc = (h - 2 * pad) / (th - 2 * pad); for (int i = 0; i < tw; i++) { for (int j = 0; j < th; j++) { int x = i; int y = j; if (x >= pad && x <= (tw - pad)) x = pad + (x - pad) * xc; else if (x >= (tw - pad)) x = w - (tw - x); if (y >= pad && y <= (th - pad)) y = pad + (y - pad) * yc; else if (y >= (th - pad)) y = h - (th - y); QRgb rgb = bgimg.pixel(x, y); outimg->setPixel(i, j, rgb); } } QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect; effect->setBlurRadius(5); effect->setOffset(this->boundingRect().height() / 7.0); effect->setColor(QColor(0, 0, 0, 200)); this->setGraphicsEffect(effect); glow = 0; timer_id = 0; }
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, QgsSymbolV2RenderContext *context, const QgsFeature*, QPointF shift ) const { //width double symbolWidth = mSymbolWidth; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_WIDTH ) ) //1. priority: data defined setting on symbol layer le { context->setOriginalValueVariable( mSymbolWidth ); symbolWidth = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_WIDTH, *context, mSymbolWidth ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolWidth = mSize; } if ( mSymbolWidthUnit == QgsSymbolV2::MM ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_HEIGHT ) ) //1. priority: data defined setting on symbol layer level { context->setOriginalValueVariable( mSymbolHeight ); symbolHeight = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_HEIGHT, *context, mSymbolHeight ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolHeight = mSize; } if ( mSymbolHeightUnit == QgsSymbolV2::MM ) { symbolHeight *= mmMapUnitScaleFactor; } //outline width double outlineWidth = mOutlineWidth; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH ) ) { context->setOriginalValueVariable( mOutlineWidth ); outlineWidth = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH, *context, mOutlineWidth ).toDouble(); } if ( mOutlineWidthUnit == QgsSymbolV2::MM ) { outlineWidth *= outlineWidth; } //fill color bool ok; QColor fc = mColor; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR ) ) { context->setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mColor ) ); QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR, *context, QVariant(), &ok ).toString(); if ( ok ) fc = QgsSymbolLayerV2Utils::decodeColor( colorString ); } //outline color QColor oc = mOutlineColor; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR ) ) { context->setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mOutlineColor ) ); QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR, *context, QVariant(), &ok ).toString(); if ( ok ) oc = QgsSymbolLayerV2Utils::decodeColor( colorString ); } //symbol name QString symbolName = mSymbolName; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME ) ) { context->setOriginalValueVariable( mSymbolName ); symbolName = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME, *context, mSymbolName ).toString(); } //offset double offsetX = 0; double offsetY = 0; markerOffset( *context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION ) ) { context->setOriginalValueVariable( mAngle ); rotation = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION, *context, mAngle ).toDouble() + mLineAngle; } else if ( !qgsDoubleNear( mAngle + mLineAngle, 0.0 ) ) { rotation = mAngle + mLineAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( !qgsDoubleNear( rotation, 0.0 ) ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == "circle" ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QPointF pt( t.map( QPointF( 0, 0 ) ) ); e.writeFilledCircle( layerName, oc, pt, halfWidth ); } else { QgsPolyline line; line.reserve( 40 ); double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * cos( angle ); double y = halfHeight * sin( angle ); QPointF pt( t.map( QPointF( x, y ) ) ); line.push_back( pt ); } //close ellipse with first point line.push_back( line.at( 0 ) ); if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsPolygon() << line, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( line, layerName, "CONTINUOUS", oc, outlineWidth ); } } else if ( symbolName == "rectangle" ) { QgsPolygon p( 1 ); p[0].resize( 5 ); p[0][0] = t.map( QPointF( -halfWidth, -halfHeight ) ); p[0][1] = t.map( QPointF( halfWidth, -halfHeight ) ); p[0][2] = t.map( QPointF( halfWidth, halfHeight ) ); p[0][3] = t.map( QPointF( -halfWidth, halfHeight ) ); p[0][4] = p[0][0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( p, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p[0], layerName, "CONTINUOUS", oc, outlineWidth ); return true; } else if ( symbolName == "cross" && mPen.style() != Qt::NoPen ) { QgsPolyline line( 2 ); line[0] = t.map( QPointF( -halfWidth, 0 ) ); line[1] = t.map( QPointF( halfWidth, 0 ) ); e.writePolyline( line, layerName, "CONTINUOUS", oc, outlineWidth ); line[0] = t.map( QPointF( 0, halfHeight ) ); line[1] = t.map( QPointF( 0, -halfHeight ) ); e.writePolyline( line, layerName, "CONTINUOUS", oc, outlineWidth ); return true; } else if ( symbolName == "triangle" ) { QgsPolygon p( 1 ); p[0].resize( 4 ); p[0][0] = QPointF( t.map( QPointF( -halfWidth, -halfHeight ) ) ); p[0][1] = QPointF( t.map( QPointF( halfWidth, -halfHeight ) ) ); p[0][2] = QPointF( t.map( QPointF( 0, halfHeight ) ) ); p[0][3] = p[0][0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( p, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p[0], layerName, "CONTINUOUS", oc, outlineWidth ); return true; } return false; //soon... }
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, const QgsSymbolV2RenderContext* context, const QgsFeature* f, const QPointF& shift ) const { //width double symbolWidth = mSymbolWidth; QgsExpression* widthExpression = expression( "width" ); if ( widthExpression ) //1. priority: data defined setting on symbol layer level { symbolWidth = widthExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolWidth = mSize; } if ( mSymbolWidthUnit == QgsSymbolV2::MM ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; QgsExpression* heightExpression = expression( "height" ); if ( heightExpression ) //1. priority: data defined setting on symbol layer level { symbolHeight = heightExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolHeight = mSize; } if ( mSymbolHeightUnit == QgsSymbolV2::MM ) { symbolHeight *= mmMapUnitScaleFactor; } //outline width double outlineWidth = mOutlineWidth; QgsExpression* outlineWidthExpression = expression( "outline_width" ); if ( outlineWidthExpression ) { outlineWidth = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble(); } if ( mOutlineWidthUnit == QgsSymbolV2::MM ) { outlineWidth *= outlineWidth; } //fill color QColor fc = mFillColor; QgsExpression* fillColorExpression = expression( "fill_color" ); if ( fillColorExpression ) { fc = QColor( fillColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() ); } int fillColorIndex = e.closestColorMatch( fc.rgb() ); //outline color QColor oc = mOutlineColor; QgsExpression* outlineColorExpression = expression( "outline_color" ); if ( outlineColorExpression ) { oc = QColor( outlineColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() ); } int outlineColorIndex = e.closestColorMatch( oc.rgb() ); //symbol name QString symbolName = mSymbolName; QgsExpression* symbolNameExpression = expression( "symbol_name" ); if ( symbolNameExpression ) { QgsExpression* symbolNameExpression = expression( "symbol_name" ); symbolName = symbolNameExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString(); } //offset double offsetX = 0; double offsetY = 0; markerOffset( *context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; QgsExpression* rotationExpression = expression( "rotation" ); if ( rotationExpression ) { rotation = rotationExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble(); } else if ( !qgsDoubleNear( mAngle, 0.0 ) ) { rotation = mAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( rotation != 0 ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == "circle" ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QPointF pt( t.map( QPointF( 0, 0 ) ) ); e.writeCircle( layerName, outlineColorIndex, QgsPoint( pt.x(), pt.y() ), halfWidth ); } else { QgsPolyline line; double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * cos( angle ); double y = halfHeight * sin( angle ); QPointF pt( t.map( QPointF( x, y ) ) ); line.push_back( QgsPoint( pt.x(), pt.y() ) ); } //close ellipse with first point line.push_back( line.at( 0 ) ); e.writePolyline( line, layerName, "solid", outlineColorIndex, outlineWidth, true ); } } else if ( symbolName == "rectangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( -halfWidth, halfHeight ) ) ); QPointF pt4( t.map( QPointF( halfWidth, halfHeight ) ) ); e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) ); return true; } else if ( symbolName == "cross" ) { QgsPolyline line1( 2 ); QPointF pt1( t.map( QPointF( -halfWidth, 0 ) ) ); QPointF pt2( t.map( QPointF( halfWidth, 0 ) ) ); line1[0] = QgsPoint( pt1.x(), pt1.y() ); line1[1] = QgsPoint( pt2.x(), pt2.y() ); e.writePolyline( line1, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false ); QgsPolyline line2( 2 ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, -halfHeight ) ) ); line2[0] = QgsPoint( pt3.x(), pt3.y() ); line2[1] = QgsPoint( pt4.x(), pt4.y() ); e.writePolyline( line2, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false ); return true; } else if ( symbolName == "triangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, halfHeight ) ) ); e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) ); return true; } return false; //soon... }
MStatus particlePathsCmd::doIt( const MArgList& args ) { MStatus stat = parseArgs( args ); if( stat != MS::kSuccess ) { return stat; } MFnParticleSystem cloud( particleNode ); if( ! cloud.isValid() ) { MGlobal::displayError( "The function set is invalid!" ); return MS::kFailure; } // // Create curves from the particle system in two stages. First, sample // all particle positions from the start time to the end time. Then, // use the data that was collected to create curves. // // Create the particle hash table at a fixed size. This should work fine // for small particle systems, but may become inefficient for larger ones. // If the plugin is running very slow, increase the size. The value should // be roughly the number of particles that are expected to be emitted // within the time period. // ParticleIdHash hash(1024); MIntArray idList; // // Stage 1 // MVectorArray positions; MIntArray ids; int i = 0; for (double time = start; time <= finish + TOLERANCE; time += increment) { MTime timeSeconds(time,MTime::kSeconds); // It is necessary to query the worldPosition attribute to force the // particle positions to update. // cloud.evaluateDynamics(timeSeconds,false); // MGlobal::executeCommand(MString("getAttr ") + cloud.name() + // MString(".worldPosition")); if (!cloud.isValid()) { MGlobal::displayError( "Particle system has become invalid." ); return MS::kFailure; } MGlobal::displayInfo( MString("Received ") + (int)(cloud.count()) + " particles, at time " + time); // Request position and ID data for particles // cloud.position( positions ); cloud.particleIds( ids ); if (ids.length() != cloud.count() || positions.length() != cloud.count()) { MGlobal::displayError( "Invalid array sizes." ); return MS::kFailure; } for (int j = 0; j < (int)cloud.count(); j++) { // Uncomment to show particle positions as the plugin accumulates // samples. /* MGlobal::displayInfo(MString("(") + (positions[j])[0] + MString(",") + (positions[j])[1] + MString(",") + (positions[j])[2] + MString(")")); */ MPoint pt(positions[j]); if (hash.getPoints(ids[j]).length() == 0) { idList.append(ids[j]); } hash.insert(ids[j],pt); } i++; } // // Stage 2 // for (i = 0; i < (int)(idList.length()); i++) { MPointArray points = hash.getPoints(idList[i]); // Don't bother with single samples if (points.length() <= 1) { continue; } // Add two additional points, so that the curve covers all sampled // values. // MPoint p1 = points[0]*2 - points[1]; MPoint p2 = points[points.length()-1]*2 - points[points.length()-2]; points.insert(p1,0); points.append(p2); // Uncomment to show information about the generated curves /* MGlobal::displayInfo( MString("ID ") + (int)(idList[i]) + " has " + (int)(points.length()) + " curve points."); for (int j = 0; j < (int)(points.length()); j++) { MGlobal::displayInfo(MString("(") + points[j][0] + MString(",") + points[j][1] + MString(",") + points[j][2] + MString(")")); } */ MDoubleArray knots; knots.insert(0.0,0); for (int j = 0; j < (int)(points.length()); j++) { knots.append((double)j); } knots.append(points.length()-1); MStatus status; MObject dummy; MFnNurbsCurve curve; curve.create(points,knots,3,MFnNurbsCurve::kOpen,false,false,dummy,&status); if (!status) { MGlobal::displayError("Failed to create nurbs curve."); return MS::kFailure; } } return MS::kSuccess; }
void RGBMatrix::updateMapChannels(const RGBMap& map, const FixtureGroup* grp) { quint32 mdAssigned = QLCChannel::invalid(); quint32 mdFxi = Fixture::invalidId(); uint fadeTime = 0; if (overrideFadeInSpeed() == defaultSpeed()) fadeTime = fadeInSpeed(); else fadeTime = overrideFadeInSpeed(); // Create/modify fade channels for ALL pixels in the color map. for (int y = 0; y < map.size(); y++) { for (int x = 0; x < map[y].size(); x++) { QLCPoint pt(x, y); GroupHead grpHead(grp->head(pt)); Fixture* fxi = doc()->fixture(grpHead.fxi); if (fxi == NULL) continue; if (grpHead.fxi != mdFxi) { mdAssigned = QLCChannel::invalid(); mdFxi = grpHead.fxi; } QLCFixtureHead head = fxi->head(grpHead.head); QVector <quint32> rgb = head.rgbChannels(); QVector <quint32> cmy = head.cmyChannels(); if (rgb.size() == 3) { // RGB color mixing { FadeChannel fc(doc(), grpHead.fxi, rgb.at(0)); fc.setTarget(qRed(map[y][x])); insertStartValues(fc, fadeTime); m_fader->add(fc); } { FadeChannel fc(doc(), grpHead.fxi, rgb.at(1)); fc.setTarget(qGreen(map[y][x])); insertStartValues(fc, fadeTime); m_fader->add(fc); } { FadeChannel fc(doc(), grpHead.fxi, rgb.at(2)); fc.setTarget(qBlue(map[y][x])); insertStartValues(fc, fadeTime); m_fader->add(fc); } } else if (cmy.size() == 3) { // CMY color mixing QColor col(map[y][x]); { FadeChannel fc(doc(), grpHead.fxi, cmy.at(0)); fc.setTarget(col.cyan()); insertStartValues(fc, fadeTime); m_fader->add(fc); } { FadeChannel fc(doc(), grpHead.fxi, cmy.at(1)); fc.setTarget(col.magenta()); insertStartValues(fc, fadeTime); m_fader->add(fc); } { FadeChannel fc(doc(), grpHead.fxi, cmy.at(2)); fc.setTarget(col.yellow()); insertStartValues(fc, fadeTime); m_fader->add(fc); } } if (m_dimmerControl && head.masterIntensityChannel() != QLCChannel::invalid()) { //qDebug() << "RGBMatrix: found dimmer at" << head.masterIntensityChannel(); // Simple intensity (dimmer) channel QColor col(map[y][x]); FadeChannel fc(doc(), grpHead.fxi, head.masterIntensityChannel()); if (col.value() == 0 && mdAssigned != head.masterIntensityChannel()) fc.setTarget(0); else { fc.setTarget(255); if (mdAssigned == QLCChannel::invalid()) mdAssigned = head.masterIntensityChannel(); } insertStartValues(fc, fadeTime); m_fader->add(fc); } } } }
int mitkHistogramMatchingTest(int /*argc*/, char* /*argv*/[]) { //Create Image out of nowhere mitk::Image::Pointer image; mitk::PixelType pt( mitk::MakeScalarPixelType<int>()); unsigned int dim[]={100,100,20}; std::cout << "Creating image: "; image = mitk::Image::New(); //image->DebugOn(); image->Initialize( mitk::MakeScalarPixelType<int>(), 3, dim); try { mitk::ImageWriteAccessor imgB(image); int* p = (int*) imgB.GetData(); int size = dim[0]*dim[1]*dim[2]; int i; for(i=0; i<size; ++i, ++p) *p=i; std::cout<<"[PASSED]"<<std::endl; } catch(const mitk::Exception&) { // we don't have image access, set test to failed std::cout<<"[FAILED] creation of the image" <<std::endl; return EXIT_FAILURE; } //Create second Image out of nowhere mitk::Image::Pointer image2; mitk::PixelType pt2( mitk::MakeScalarPixelType<int>() ); unsigned int dim2[]={100,100,20}; std::cout << "Creating image: "; image2 = mitk::Image::New(); //image->DebugOn(); image2->Initialize(mitk::MakeScalarPixelType<int>(), 3, dim2); try { mitk::ImageWriteAccessor imgB(image2); int* p2 = (int*) imgB.GetData(); int size2 = dim2[0]*dim2[1]*dim2[2]; int i2; for(i2=0; i2<size2; ++i2, ++p2) *p2=i2; std::cout<<"[PASSED]"<<std::endl; } catch(const mitk::Exception&) { // we don't have image access, set test to failed std::cout<<"[FAILED] creation of the image" <<std::endl; return EXIT_FAILURE; } std::cout << "Constructor: "; mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set Reference Image: "; histogramMatching->SetReferenceImage(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set Moving Image: "; histogramMatching->SetInput(image2); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set number of match points: "; histogramMatching->SetNumberOfMatchPoints(100); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set number of histogram levels: "; histogramMatching->SetNumberOfHistogramLevels(8); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set threshold at mean intensity: "; histogramMatching->SetThresholdAtMeanIntensity(true); std::cout<<"[PASSED]"<<std::endl; std::cout << "Perform histogram matching: "; histogramMatching->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Get the result image: "; mitk::Image::Pointer histimage = histogramMatching->GetOutput(); std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; }
/** @brief MOUSE MOVE @author KHS @return **/ void CCableRouteAssignTOLoadDlg::OnMouseMove(UINT nFlags, CPoint point) { if (m_bDragging) { //// Move the drag image CPoint pt(point); //get our current mouse coordinates ClientToScreen(&pt); //convert to screen coordinates m_pDragImage->DragMove(pt); //move the drag image to those coordinates // Unlock window updates (this allows the dragging image to be shown smoothly) m_pDragImage->DragShowNolock(false); //// Get the CWnd pointer of the window that is under the mouse cursor CWnd* pDropWnd = WindowFromPoint (pt); ASSERT(pDropWnd); //make sure we have a window //// If we drag outside current window we need to adjust the highlights displayed if (pDropWnd != m_pDropList) { if (m_nDropIndex != -1) //If we drag over the CListCtrl header, turn off the hover highlight { TRACE("m_nDropIndex is -1\n"); CMFCListCtrl* pList = (CMFCListCtrl*)m_pDropList; //VERIFY (pList->SetItemState (m_nDropIndex, 0, LVIS_DROPHILITED)); // redraw item //VERIFY (pList->RedrawItems (m_nDropIndex, m_nDropIndex)); //pList->UpdateWindow (); m_nDropIndex = -1; } else //If we drag out of the CListCtrl altogether { TRACE("m_nDropIndex is not -1\n"); //CListCtrl* pList = (CListCtrl*)m_pDropList; //int i = 0; //int nCount = pList->GetItemCount(); //for(i = 0; i < nCount; i++) //{ // pList->SetItemState(i, 0, LVIS_DROPHILITED); //} //pList->RedrawItems(0, nCount); //pList->UpdateWindow(); } } // Save current window pointer as the CListCtrl we are dropping onto m_pDropList = (CMFCTextColorListCtrl*)pDropWnd; if(m_pDropList != m_pDragList) { // Convert from screen coordinates to drop target client coordinates pDropWnd->ScreenToClient(&pt); //If we are hovering over a CListCtrl we need to adjust the highlights if(pDropWnd->IsKindOf(RUNTIME_CLASS(CMFCListCtrl)) && (pDropWnd->GetSafeHwnd() == m_wndAssignLoadListCtrl.GetSafeHwnd())) { TRACE("m_nDropIndex is not 100\n"); //Note that we can drop here SetCursor(LoadCursor(NULL, IDC_ARROW)); CListCtrl* pList = (CListCtrl*)pDropWnd; } else if(pDropWnd->IsKindOf(RUNTIME_CLASS(CMFCListCtrl)) && (pDropWnd->GetSafeHwnd() == m_wndRouteGrListCtrl.GetSafeHwnd())) { TRACE("m_nDropIndex is not 100\n"); //Note that we can drop here SetCursor(LoadCursor(NULL, IDC_ARROW)); UINT uFlags; CListCtrl* pList = (CListCtrl*)pDropWnd; // Turn off hilight for previous drop target pList->SetItemState (m_nDropIndex, 0, LVIS_DROPHILITED); // Redraw previous item pList->RedrawItems (m_nDropIndex, m_nDropIndex); // Get the item that is below cursor m_nDropIndex = ((CListCtrl*)pDropWnd)->HitTest(pt, &uFlags); if(-1 != m_nDropIndex) { // Highlight it pList->SetItemState(m_nDropIndex, LVIS_DROPHILITED, LVIS_DROPHILITED); // Redraw item pList->RedrawItems(m_nDropIndex, m_nDropIndex); pList->UpdateWindow(); }else SetCursor(LoadCursor(NULL, IDC_NO)); } else if(pDropWnd->IsKindOf(RUNTIME_CLASS(CMFCListCtrl)) && (pDropWnd->GetSafeHwnd() == m_wndNotAssignLoadListCtrl.GetSafeHwnd())) { TRACE("m_nDropIndex is not 100\n"); //Note that we can drop here SetCursor(LoadCursor(NULL, IDC_ARROW)); CListCtrl* pList = (CListCtrl*)pDropWnd; } } else { //If we are not hovering over a CListCtrl, change the cursor // to note that we cannot drop here SetCursor(LoadCursor(NULL, IDC_NO)); } // Lock window updates m_pDragImage->DragShowNolock(true); } CDialog::OnMouseMove(nFlags, point); }
//»æ»Í¼Ïñ bool CGdiPlusImage::DrawImage(CDC * pDC, INT nXPos, INT nYPos) { //¼ÓÔØÅÐ¶Ï //ASSERT(m_pImage!=NULL); if (m_pImage==NULL) return false; //´´½¨ÆÁÄ» ASSERT(pDC!=NULL); Graphics graphics(pDC->GetSafeHdc()); GraphicsContainer Containter = graphics.BeginContainer(); graphics.SetSmoothingMode(SmoothingModeHighQuality); //»ñÈ¡ÊôÐÔ INT nImageWidth=m_pImage->GetWidth(); INT nImageHeight=m_pImage->GetHeight(); //¹¹ÔìλÖà RectF rcDrawRect; rcDrawRect.X=0;//(REAL)nXPos; rcDrawRect.Y=0;//(REAL)nYPos; rcDrawRect.Width=(REAL)nImageWidth; rcDrawRect.Height=(REAL)nImageHeight; Matrix matrix; CPoint pt((nXPos+nImageWidth/2), (nYPos+nImageHeight/2)); PointF ptBase((float)pt.x,(float)pt.y); //¾ØÕó±ä»»Òª×¢Òâ˳Ðò£¬ÏÈƽÒÆÔÚËõ·ÅºóÐýת matrix.Translate((REAL)nXPos,(REAL)nYPos,MatrixOrderAppend); //Ëõ·Å if ( m_szZoom.cx != 1.0f || m_szZoom.cy != 1.0f ) { ptBase.X += m_szZoom.cx; ptBase.Y += m_szZoom.cy; matrix.Translate(-ptBase.X,-ptBase.Y,MatrixOrderAppend); matrix.Scale(m_szZoom.cx,m_szZoom.cy,MatrixOrderAppend); matrix.Translate(ptBase.X,ptBase.Y,MatrixOrderAppend); } //Ðýת if (m_nRotateAngle) { matrix.RotateAt((REAL)m_nRotateAngle,ptBase,MatrixOrderAppend); } graphics.SetTransform(&matrix); //͸Ã÷¾ØÕó ColorMatrix Matrix= { 1.0f,0.0f,0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f,m_cbAlphaDepth/255.0f,0.0f, 0.0f,0.0f,0.0f,0.0f,1.0f }; //ÉèÖÃÊôÐÔ ImageAttributes Attributes; Attributes.SetColorMatrix(&Matrix,ColorMatrixFlagsDefault,ColorAdjustTypeBitmap); //»æ»Í¼Ïñ graphics.DrawImage(m_pImage,rcDrawRect,0,0,(REAL)nImageWidth,(REAL)nImageHeight,UnitPixel,&Attributes); graphics.ResetTransform(); graphics.EndContainer(Containter); return true; }
QRect LDesktopPluginSpace::findOpenSpot(int gridwidth, int gridheight, int startRow, int startCol, bool reversed, QString plugID){ //Note about the return QPoint: x() is the column number, y() is the row number QPoint pt(0,0); //qDebug() << "FIND OPEN SPOT:" << gridwidth << gridheight << startRow << startCol << reversed; int row = startRow; int col = startCol; if(row<0){ row = 0; } //just in case - since this can be recursively called if(col<0){ col = 0; } //just in case - since this can be recursively called bool found = false; int rowCount, colCount; rowCount = RoundUp(this->height()/GRIDSIZE); colCount = RoundUp(this->width()/GRIDSIZE); if( (row+gridheight)>rowCount){ row = rowCount-gridheight; startRow = row; } if( (col+gridwidth)>colCount){ col = colCount-gridwidth; startCol = col; } QRect geom(0, 0, gridwidth*GRIDSIZE, gridheight*GRIDSIZE); //origin point will be adjusted in a moment if(DEBUG){ qDebug() << "Search for plugin space:" << rowCount << colCount << gridheight << gridwidth << this->size(); } if(TopToBottom && reversed && (startRow>0 || startCol>0) ){ //Arrange Top->Bottom (work backwards) //qDebug() << "Search backwards for space:" << rowCount << colCount << startRow << startCol << gridheight << gridwidth; while(col>=0 && !found){ while(row>=0 && !found){ bool ok = true; geom.moveTo(col*GRIDSIZE, row*GRIDSIZE); //qDebug() << " - Check Geom:" << geom << col << row; //Check all the existing items to ensure no overlap for(int i=0; i<ITEMS.length() && ok; i++){ if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict if(geom.intersects(ITEMS[i]->geometry())){ //Collision - move the next searchable row/column index ok = false; //qDebug() << "Collision:" << col << row; row = ((ITEMS[i]->geometry().y()-GRIDSIZE/2)/GRIDSIZE) -gridheight; //use top edge for next search (minus item height) //qDebug() << " - new row:" << row; } } if(ok){ pt = QPoint(col,row); found = true; } //found an open spot } if(!found){ col--; row=rowCount-gridheight; } //go to the previous column } }else if(TopToBottom){ //Arrange Top->Bottom while(col<(colCount-gridwidth) && !found){ while(row<(rowCount-gridheight) && !found){ bool ok = true; geom.moveTo(col*GRIDSIZE, row*GRIDSIZE); //qDebug() << " - Check Geom:" << geom << col << row; //Check all the existing items to ensure no overlap for(int i=0; i<ITEMS.length() && ok; i++){ if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict if(geom.intersects(ITEMS[i]->geometry())){ //Collision - move the next searchable row/column index ok = false; row = posToGrid(ITEMS[i]->geometry().bottomLeft()).y(); //use bottom edge for next search } } if(ok){ pt = QPoint(col,row); found = true; } //found an open spot //else{ row++; } } if(!found){ col++; row=0; } //go to the next column } }else if(reversed && (startRow>0 || startCol>0) ){ //Arrange Left->Right (work backwards) while(row>=0 && !found){ while(col>=0 && !found){ bool ok = true; geom.moveTo(col*GRIDSIZE, row*GRIDSIZE); //Check all the existing items to ensure no overlap for(int i=0; i<ITEMS.length() && ok; i++){ if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict if(geom.intersects(ITEMS[i]->geometry())){ //Collision - move the next searchable row/column index ok = false; col = (ITEMS[i]->geometry().x()-GRIDSIZE/2)/GRIDSIZE - gridwidth; // Fill according to row/column } } if(ok){ pt = QPoint(col,row); found = true; } //found an open spot //else{ col++; } } if(!found){ row--; col=colCount-gridwidth;} //go to the previous row } }else{ //Arrange Left->Right while(row<(rowCount-gridheight) && !found){ while(col<(colCount-gridwidth) && !found){ bool ok = true; geom.moveTo(col*GRIDSIZE, row*GRIDSIZE); //Check all the existing items to ensure no overlap for(int i=0; i<ITEMS.length() && ok; i++){ if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict if(geom.intersects(ITEMS[i]->geometry())){ //Collision - move the next searchable row/column index ok = false; col = posToGrid(ITEMS[i]->geometry().topRight()).x(); // Fill according to row/column } } if(ok){ pt = QPoint(col,row); found = true; } //found an open spot //else{ col++; } } if(!found){ row++; col=0;} //go to the next row } } if(!found){ //qDebug() << "Could not find a spot:" << startRow << startCol << gridheight << gridwidth; if( (startRow!=0 || startCol!=0) && !reversed){ //Did not check the entire screen yet - gradually work it's way back to the top/left corner //qDebug() << " - Start backwards search"; return findOpenSpot(gridwidth, gridheight,startRow,startCol, true); //reverse the scan }else if(gridwidth>1 && gridheight>1){ //Decrease the size of the item by 1x1 grid points and try again //qDebug() << " - Out of space: Decrease item size and try again..."; return findOpenSpot(gridwidth-1, gridheight-1, 0, 0); }else{ //qDebug() << " - Could not find an open spot for a desktop plugin:" << gridwidth << gridheight << startRow << startCol; return QRect(-1,-1,-1,-1); } }else{ return QRect(pt,QSize(gridwidth,gridheight)); } }
MODULE* PCB_EDIT_FRAME::Create_MuWaveComponent( int shape_type ) { int oX; D_PAD* pad; MODULE* module; wxString msg, cmp_name; int pad_count = 2; int angle = 0; // Ref and value text size (O = use board default value. // will be set to a value depending on the footprint size, if possible int text_size = 0; // Enter the size of the gap or stub int gap_size = GetDesignSettings().GetCurrentTrackWidth(); switch( shape_type ) { case 0: msg = _( "Gap" ); cmp_name = wxT( "muwave_gap" ); text_size = gap_size; break; case 1: msg = _( "Stub" ); cmp_name = wxT( "muwave_stub" ); text_size = gap_size; pad_count = 2; break; case 2: msg = _( "Arc Stub" ); cmp_name = wxT( "muwave_arcstub" ); pad_count = 1; break; default: msg = wxT( "???" ); break; } wxString value = StringFromValue( g_UserUnit, gap_size ); wxTextEntryDialog dlg( this, msg, _( "Create microwave module" ), value ); if( dlg.ShowModal() != wxID_OK ) { m_canvas->MoveCursorToCrossHair(); return NULL; // cancelled by user } value = dlg.GetValue(); gap_size = ValueFromString( g_UserUnit, value ); bool abort = false; if( shape_type == 2 ) { double fcoeff = 10.0, fval; msg.Printf( wxT( "%3.1f" ), angle / fcoeff ); wxTextEntryDialog angledlg( this, _( "Angle in degrees:" ), _( "Create microwave module" ), msg ); if( angledlg.ShowModal() != wxID_OK ) { m_canvas->MoveCursorToCrossHair(); return NULL; // cancelled by user } msg = angledlg.GetValue(); if( !msg.ToDouble( &fval ) ) { DisplayError( this, _( "Incorrect number, abort" ) ); abort = true; } angle = std::abs( KiROUND( fval * fcoeff ) ); if( angle > 1800 ) angle = 1800; } if( abort ) { m_canvas->MoveCursorToCrossHair(); return NULL; } module = CreateMuWaveBaseFootprint( cmp_name, text_size, pad_count ); pad = module->Pads(); switch( shape_type ) { case 0: //Gap : oX = -( gap_size + pad->GetSize().x ) / 2; pad->SetX0( oX ); pad->SetX( pad->GetPos0().x + pad->GetPosition().x ); pad = pad->Next(); pad->SetX0( oX + gap_size + pad->GetSize().x ); pad->SetX( pad->GetPos0().x + pad->GetPosition().x ); break; case 1: //Stub : pad->SetPadName( wxT( "1" ) ); pad = pad->Next(); pad->SetY0( -( gap_size + pad->GetSize().y ) / 2 ); pad->SetSize( wxSize( pad->GetSize().x, gap_size ) ); pad->SetY( pad->GetPos0().y + pad->GetPosition().y ); break; case 2: // Arc Stub created by a polygonal approach: { EDGE_MODULE* edge = new EDGE_MODULE( module ); module->GraphicalItems().PushFront( edge ); edge->SetShape( S_POLYGON ); edge->SetLayer( F_Cu ); int numPoints = (angle / 50) + 3; // Note: angles are in 0.1 degrees std::vector<wxPoint>& polyPoints = edge->GetPolyPoints(); polyPoints.reserve( numPoints ); edge->m_Start0.y = -pad->GetSize().y / 2; polyPoints.push_back( wxPoint( 0, 0 ) ); int theta = -angle / 2; for( int ii = 1; ii<numPoints - 1; ii++ ) { wxPoint pt( 0, -gap_size ); RotatePoint( &pt.x, &pt.y, theta ); polyPoints.push_back( pt ); theta += 50; if( theta > angle / 2 ) theta = angle / 2; } // Close the polygon: polyPoints.push_back( polyPoints[0] ); } break; default: break; } module->CalculateBoundingBox(); GetBoard()->m_Status_Pcb = 0; OnModify(); return module; }
void MeshfreeInterpolation::gather_remote_data () { #ifndef LIBMESH_HAVE_MPI // no MPI -- no-op return; #else // This function must be run on all processors at once parallel_object_only(); START_LOG ("gather_remote_data()", "MeshfreeInterpolation"); // block to avoid incorrect completion if called in quick succession on // two different MeshfreeInterpolation objects this->comm().barrier(); std::vector<Real> send_buf, recv_buf; libmesh_assert_equal_to (_src_vals.size(), _src_pts.size()*this->n_field_variables()); send_buf.reserve (_src_pts.size()*(3 + this->n_field_variables())); // Everyone packs their data at the same time for (unsigned int p_idx=0, v_idx=0; p_idx<_src_pts.size(); p_idx++) { const Point &pt(_src_pts[p_idx]); send_buf.push_back(pt(0)); send_buf.push_back(pt(1)); send_buf.push_back(pt(2)); for (unsigned int var=0; var<this->n_field_variables(); var++) { libmesh_assert_less (v_idx, _src_vals.size()); #ifdef LIBMESH_USE_COMPLEX_NUMBERS send_buf.push_back (_src_vals[v_idx].real()); send_buf.push_back (_src_vals[v_idx].imag()); v_idx++; #else send_buf.push_back (_src_vals[v_idx++]); #endif } } // Send our data to everyone else. Note that MPI-1 said you could not // use the same buffer in nonblocking sends, but that restriction has // recently been removed. std::vector<Parallel::Request> send_request(this->n_processors()-1); // Use a tag for best practices. In debug mode parallel_only() blocks above // so we can be sure there is no other shenanigarry going on, but in optimized // mode there is no such guarantee - other prcoessors could be somewhere else // completing some other communication, and we don't want to intercept that. Parallel::MessageTag tag = this->comm().get_unique_tag ( 6000 ); for (unsigned int proc=0, cnt=0; proc<this->n_processors(); proc++) if (proc != this->processor_id()) this->comm().send (proc, send_buf, send_request[cnt++], tag); // All data has been sent. Receive remote data in any order for (processor_id_type comm_step=0; comm_step<(this->n_processors()-1); comm_step++) { // blocking receive this->comm().receive (Parallel::any_source, recv_buf, tag); // Add their data to our list Point pt; Number val; std::vector<Real>::const_iterator it=recv_buf.begin(); while (it != recv_buf.end()) { pt(0) = *it, ++it; pt(1) = *it, ++it; pt(2) = *it, ++it; _src_pts.push_back(pt); for (unsigned int var=0; var<this->n_field_variables(); var++) { #ifdef LIBMESH_USE_COMPLEX_NUMBERS Real re = *it; ++it; Real im = *it; ++it; val = Number(re,im); #else val = *it, ++it; #endif _src_vals.push_back(val); } } } Parallel::wait (send_request); STOP_LOG ("gather_remote_data()", "MeshfreeInterpolation"); #endif // LIBMESH_HAVE_MPI }
int mitkDemonsRegistrationTest(int /*argc*/, char* /*argv*/[]) { //Create Image out of nowhere mitk::Image::Pointer image; mitk::PixelType pt(mitk::MakeScalarPixelType<int>()); unsigned int dim[]={100,100,20}; std::cout << "Creating image: "; image = mitk::Image::New(); //image->DebugOn(); image->Initialize(mitk::MakeScalarPixelType<int>(), 3, dim); int *p = (int*)image->GetData(); int size = dim[0]*dim[1]*dim[2]; int i; for(i=0; i<size; ++i, ++p) *p=i; std::cout<<"[PASSED]"<<std::endl; //Create second Image out of nowhere mitk::Image::Pointer image2; mitk::PixelType pt2(mitk::MakeScalarPixelType<int>()); unsigned int dim2[]={100,100,20}; std::cout << "Creating image: "; image2 = mitk::Image::New(); //image->DebugOn(); image2->Initialize(mitk::MakeScalarPixelType<int>(), 3, dim2); int *p2 = (int*)image2->GetData(); int size2 = dim2[0]*dim2[1]*dim2[2]; int i2; for(i2=0; i2<size2; ++i2, ++p2) *p2=i2; std::cout<<"[PASSED]"<<std::endl; std::cout << "Constructor: "; mitk::DemonsRegistration::Pointer demonsRegistration = mitk::DemonsRegistration::New(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set Reference Image: "; demonsRegistration->SetReferenceImage(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set Moving Image: "; demonsRegistration->SetInput(image2); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set number of iterations: "; demonsRegistration->SetNumberOfIterations(5); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set standard deviation: "; demonsRegistration->SetStandardDeviation(1.0); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set save deformation field: "; demonsRegistration->SetSaveDeformationField(false); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set deformation field file name: "; demonsRegistration->SetDeformationFieldFileName("TestField.mhd"); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set save result image: "; demonsRegistration->SetSaveResult(false); std::cout<<"[PASSED]"<<std::endl; std::cout << "Set result image file name: "; demonsRegistration->SetResultFileName("TestResult.mhd"); std::cout<<"[PASSED]"<<std::endl; std::cout << "Perform registration: "; demonsRegistration->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Get the result image: "; mitk::Image::Pointer resultImage = demonsRegistration->GetOutput(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Get the deformation field: "; itk::Image<class itk::Vector<float, 3>,3>::Pointer deformationField = demonsRegistration->GetDeformationField(); std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; }
S13707 func13707() { S13707 pt(NULL, NULL); return pt; }
EDGE_MODULE* FOOTPRINT_EDIT_FRAME::Begin_Edge_Module( EDGE_MODULE* aEdge, wxDC* DC, STROKE_T type_edge ) { MODULE* module = GetBoard()->m_Modules; if( module == NULL ) return NULL; if( aEdge == NULL ) // Start a new edge item { SaveCopyInUndoList( module, UR_CHANGED ); aEdge = new EDGE_MODULE( module ); MoveVector.x = MoveVector.y = 0; // Add the new item to the Drawings list head module->GraphicalItems().PushFront( aEdge ); // Update characteristics of the segment or arc. aEdge->SetFlags( IS_NEW ); aEdge->SetAngle( 0 ); aEdge->SetShape( type_edge ); if( aEdge->GetShape() == S_ARC ) aEdge->SetAngle( ArcValue ); aEdge->SetWidth( GetDesignSettings().m_ModuleSegmentWidth ); aEdge->SetLayer( GetActiveLayer() ); // Initialize the starting point of the new segment or arc aEdge->SetStart( GetCrossHairPosition() ); // Initialize the ending point of the new segment or arc aEdge->SetEnd( aEdge->GetStart() ); // Initialize the relative coordinates aEdge->SetStart0( aEdge->GetStart() - module->GetPosition() ); RotatePoint( &aEdge->m_Start0, -module->GetOrientation() ); aEdge->m_End0 = aEdge->m_Start0; module->CalculateBoundingBox(); m_canvas->SetMouseCapture( ShowNewEdgeModule, Abort_Move_ModuleOutline ); } /* Segment creation in progress. * The ending coordinate is updated by the function * ShowNewEdgeModule() called on move mouse event * during the segment creation */ else { if( type_edge == S_SEGMENT ) { if( aEdge->m_Start0 != aEdge->m_End0 ) { aEdge->Draw( m_canvas, DC, GR_OR ); EDGE_MODULE* newedge = new EDGE_MODULE( *aEdge ); // insert _after_ aEdge, which is the same as inserting before aEdge->Next() module->GraphicalItems().Insert( newedge, aEdge->Next() ); aEdge->ClearFlags(); aEdge = newedge; // point now new item aEdge->SetFlags( IS_NEW ); aEdge->SetWidth( GetDesignSettings().m_ModuleSegmentWidth ); aEdge->SetStart( GetCrossHairPosition() ); aEdge->SetEnd( aEdge->GetStart() ); // Update relative coordinate. aEdge->SetStart0( aEdge->GetStart() - module->GetPosition() ); wxPoint pt( aEdge->GetStart0() ); RotatePoint( &pt, -module->GetOrientation() ); aEdge->SetStart0( pt ); aEdge->SetEnd0( aEdge->GetStart0() ); module->CalculateBoundingBox(); module->SetLastEditTime(); OnModify(); } } else { wxMessageBox( wxT( "Begin_Edge() error" ) ); } } return aEdge; }
static Rect set_annotations(Metadata_Simple*metadata,const vector<double>&labels,shared_ptr<ImRGBZ>&im) { // Label description: // Each line is corresponding to one image. // Each line has 16x3 numbers, which indicates (x, y, z) of 16 joint locations. Note that these are joint CENTRE locations. // Note that (x, y) are in pixels and z is in mm. // The order of 16 joints is 0:Palm, 1Thumb root, 2Thumb mid, 3Thumb tip, 4Index root, 5Index mid, 6Index tip, // 7Middle root, 8Middle mid, 9Middle tip, 10:Ring root, 11:Ring mid, 12:Ring tip, 13:Pinky root, 14:Pinky mid, 15:Pinky tip. // We used Intel Creative depth sensor. Calibration parameters can be obtained as in Page 119 of SDK Manual: Rect handBB; auto getKeypoint = [&](int index) { Point2d pt(labels[0 + index*3],labels[1 + index*3]); // compute the handBB from the keypoints. if(handBB == Rect()) handBB = Rect(pt,Size(1,1)); else handBB |= Rect(pt,Size(1,1)); return pt; }; metadata->keypoint("carpals",getKeypoint(0),true); metadata->keypoint("Z_P0",getKeypoint(0),true); metadata->keypoint("Z_P1",getKeypoint(0),true); // thumb metadata->keypoint("Z_J53",getKeypoint(1),true); metadata->keypoint("Z_J52",getKeypoint(2),true); metadata->keypoint("Z_J51",getKeypoint(3),true); // index metadata->keypoint("Z_J43",getKeypoint(4),true); metadata->keypoint("Z_J42",getKeypoint(5),true); metadata->keypoint("Z_J41",getKeypoint(6),true); // mid metadata->keypoint("Z_J33",getKeypoint(7),true); metadata->keypoint("Z_J32",getKeypoint(8),true); metadata->keypoint("Z_J31",getKeypoint(9),true); // ring metadata->keypoint("Z_J23",getKeypoint(10),true); metadata->keypoint("Z_J22",getKeypoint(11),true); metadata->keypoint("Z_J21",getKeypoint(12),true); // pinky metadata->keypoint("Z_J13",getKeypoint(13),true); metadata->keypoint("Z_J12",getKeypoint(14),true); metadata->keypoint("Z_J11",getKeypoint(15),true); // set the hand bb Mat Zeroded = imopen(im->Z,5); //cv::erode(im,result,Mat()); handBB = bbWhere(Zeroded,[](Mat&Z,int y,int x) { return goodNumber(Z.at<float>(y,x)) and Z.at<float>(y,x) < params::MAX_Z(); }); handBB = rectResize(handBB,2,2); metadata->set_HandBB(handBB); metadata->set_is_left_hand(true); // generate the segmentation if(g_params.get_value("SEGMENTATION") == "TRUE") { Mat seg = drawRegions(*metadata); metadata->setSegmentation(seg); } return handBB; }
LRESULT CBCGPPlannerManagerView::OnNotifyLButtonDblClk (WPARAM wParam, LPARAM lParam) { CPoint pt(BCG_GET_X_LPARAM(lParam), BCG_GET_Y_LPARAM(lParam)); OnDblClkCtrl ((UINT) wParam, pt); return 0L; }
void Palette::mouseDoubleClickEvent(QMouseEvent* ev) { int i = idx(ev->pos()); if (i == -1) return; Score* score = mscore->currentScore(); if (score == 0) return; const Selection& sel = score->selection(); if (sel.state() == SEL_NONE) return; Element* element = 0; if (i < size() && cells[i]) element = cells[i]->element; if (element == 0) return; ScoreView* viewer = mscore->currentScoreView(); if (viewer->mscoreState() != STATE_EDIT && viewer->mscoreState() != STATE_LYRICS_EDIT && viewer->mscoreState() != STATE_HARMONY_FIGBASS_EDIT && viewer->mscoreState() != STATE_TEXT_EDIT) { // Already in startCmd in this case score->startCmd(); } if (sel.state() == SEL_LIST) { foreach(Element* e, sel.elements()) applyDrop(score, viewer, e, element); } else if (sel.state() == SEL_RANGE) { // TODO: check for other element types: if (element->type() == Element::BAR_LINE) { // TODO: apply to multiple measures Measure* m = sel.startSegment()->measure(); QRectF r = m->staffabbox(sel.staffStart()); QPointF pt(r.x() + r.width() * .5, r.y() + r.height() * .5); applyDrop(score, viewer, m, element, pt); } else { int track1 = sel.staffStart() * VOICES; int track2 = sel.staffEnd() * VOICES; Segment* startSegment = sel.startSegment(); Segment* endSegment = sel.endSegment(); //keep it, it could change during the loop for (Segment* s = startSegment; s && s != endSegment; s = s->next1()) { for (int track = track1; track < track2; ++track) { Element* e = s->element(track); if (e == 0) continue; if (e->type() == Element::CHORD) { Chord* chord = static_cast<Chord*>(e); foreach(Note* n, chord->notes()) applyDrop(score, viewer, n, element); } else { // do not apply articulation to barline in a range selection if(e->type() != Element::BAR_LINE || element->type() != Element::ARTICULATION) applyDrop(score, viewer, e, element); } } } } } else qDebug("unknown selection state\n"); if (viewer->mscoreState() != STATE_EDIT && viewer->mscoreState() != STATE_LYRICS_EDIT && viewer->mscoreState() != STATE_HARMONY_FIGBASS_EDIT && viewer->mscoreState() != STATE_TEXT_EDIT) { //Already in startCmd mode in this case score->endCmd(); } mscore->endCmd(); }