QImage QPlatformPixmap::toImage(const QRect &rect) const { if (rect.contains(QRect(0, 0, w, h))) return toImage(); else return toImage().copy(rect); }
QIcon generateIcon(const char* iconPath) { QIcon icon; QString normalPath(iconPath); auto tokens = normalPath.split('.'); TF_ASSERT(tokens.length() == 2); QString off(tokens[0]); QString on(tokens[0] + stateOn); QString ext("." + tokens[1]); QString disabledPath(off + modeDisabled + ext); QString activePath(off + modeActive + ext); QString selectedPath(off + modeSelected + ext); QString normalOnPath(on + ext); QString disabledOnPath(on + modeDisabled + ext); QString activeOnPath(on + modeActive + ext); QString selectedOnPath(on + modeSelected + ext); auto offIcon = QPixmap(normalPath); icon.addPixmap(offIcon, QIcon::Normal, QIcon::Off); icon.addPixmap(QPixmap(disabledPath), QIcon::Disabled, QIcon::Off); icon.addPixmap(QPixmap(activePath), QIcon::Active, QIcon::Off); icon.addPixmap(QPixmap(selectedPath), QIcon::Selected, QIcon::Off); auto onIcon = QPixmap(normalOnPath); if (onIcon.isNull()) { QPainter p; auto img = offIcon.toImage().convertToFormat(QImage::Format_ARGB32); auto mask(img); auto width = mask.width(); auto height = mask.height(); auto outerRect = mask.rect(); auto innerRect = QRect(width / 16, height / 16, width - width / 8, height - height / 8); p.begin(&mask); p.setCompositionMode(QPainter::CompositionMode_SourceIn); p.fillRect(outerRect, QApplication::palette().highlight()); p.fillRect(innerRect, Qt::transparent); p.end(); p.begin(&img); p.setCompositionMode(QPainter::CompositionMode_SourceOver); p.drawImage(0, 0, mask); p.end(); onIcon.convertFromImage(img); } icon.addPixmap(onIcon, QIcon::Normal, QIcon::On); icon.addPixmap(QPixmap(disabledOnPath), QIcon::Disabled, QIcon::On); icon.addPixmap(QPixmap(activeOnPath), QIcon::Active, QIcon::On); icon.addPixmap(QPixmap(selectedOnPath), QIcon::Selected, QIcon::On); return icon; }
void ReplyPreview::prepare( not_null<Image*> image, FileOrigin origin, Images::Options options) { int w = image->width(), h = image->height(); if (w <= 0) w = 1; if (h <= 0) h = 1; auto thumbSize = (w > h) ? QSize( w * st::msgReplyBarSize.height() / h, st::msgReplyBarSize.height()) : QSize( st::msgReplyBarSize.height(), h * st::msgReplyBarSize.height() / w); thumbSize *= cIntRetinaFactor(); const auto prepareOptions = Images::Option::Smooth | Images::Option::TransparentBackground | options; auto outerSize = st::msgReplyBarSize.height(); auto bitmap = image->pixNoCache( origin, thumbSize.width(), thumbSize.height(), prepareOptions, outerSize, outerSize); _data = std::make_unique<ReplyPreview::Data>( std::make_unique<Images::ImageSource>( bitmap.toImage(), "PNG"), ((options & Images::Option::Blurred) == 0)); }
static PyObject* output_fillbitmap(PyObject* _self, PyObject* args, PyObject* kwargs) { OutputObject* self = (OutputObject*)_self; PyObject*_line=0; PyObject*_bitmap=0; static char *kwlist[] = {"line", "bitmap", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", kwlist, &PyList_Type, &_line, &_bitmap)) return NULL; gfximage_t*image = toImage(_bitmap); if(!image) return PY_ERROR("invalid image"); gfxline_t*line = toLine(_line); if(!line) return 0; /* TODO */ gfxmatrix_t m; memset(&m, 0, sizeof(gfxmatrix_t)); m.m00 = m.m11 = 1.0; self->output_device->fillbitmap(self->output_device, line, image, &m, 0); gfxline_free(line); return PY_NONE; }
void InspectorImage::postInit() { Image* image = toImage(inspector->element()); bool v = !b.autoscale->isChecked(); b.size->setEnabled(v); b.sizeIsSpatium->setEnabled(v); b.size->setSuffix(image->sizeIsSpatium() ? "sp" : "mm"); }
HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const { if (isNull()) return 0; HBITMAP bitmap = 0; if (data->classId() == QPixmapData::RasterClass) { QRasterPixmapData* d = static_cast<QRasterPixmapData*>(data.data()); int w = d->image.width(); int h = d->image.height(); HDC display_dc = GetDC(0); // Define the header BITMAPINFO bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = w; bmi.bmiHeader.biHeight = -h; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = w * h * 4; // Create the pixmap uchar *pixels = 0; bitmap = CreateDIBSection(display_dc, &bmi, DIB_RGB_COLORS, (void **) &pixels, 0, 0); ReleaseDC(0, display_dc); if (!bitmap) { qErrnoWarning("QPixmap::toWinHBITMAP(), failed to create dibsection"); return 0; } if (!pixels) { qErrnoWarning("QPixmap::toWinHBITMAP(), did not allocate pixel data"); return 0; } // Copy over the data QImage::Format imageFormat = QImage::Format_ARGB32; if (format == NoAlpha) imageFormat = QImage::Format_RGB32; else if (format == PremultipliedAlpha) imageFormat = QImage::Format_ARGB32_Premultiplied; const QImage image = d->image.convertToFormat(imageFormat); int bytes_per_line = w * 4; for (int y=0; y<h; ++y) memcpy(pixels + y * bytes_per_line, image.scanLine(y), bytes_per_line); } else { QPixmapData *data = new QRasterPixmapData(depth() == 1 ? QPixmapData::BitmapType : QPixmapData::PixmapType); data->fromImage(toImage(), Qt::AutoColor); return QPixmap(data).toWinHBITMAP(format); } return bitmap; }
int AnsiConvApp::OnRun() { wxLog::SetActiveTarget(new wxLogStderr); wxInitAllImageHandlers(); const AnsiData& ad = AnsiData::FromFile(input_name, encoding); wxImage image = toImage(ad, 12); image.SaveFile(output_name, "image/png"); return 0; }
Document *DocumentController::createFromClipboard() { auto pixmap = qApp->clipboard()->pixmap(); if (pixmap.isNull()) return 0; auto layer = RasterLayer::createFromImage(pixmap.toImage()); layer->setName(tr("Clipboard")); return new Document(appController()->unduplicatedFileTempName(tr("Clipboard")), pixmap.size(), {layer}); }
bool OrthographicCamera::project(const Vector& p, float* sx, float* sy) { Vector po = p - o; if(Vector::dotProduct(po, w) <= 0.0f) return false; float fx = Vector::dotProduct(po, u); float fy = Vector::dotProduct(po, v); toImage(fx, fy, sx, sy); return true; }
bool CanvasModel::save(const QString &filename) const { if(filename.endsWith(".ora", Qt::CaseInsensitive)) { // Special case: Save as OpenRaster with all the layers intact. return openraster::saveOpenRaster(filename, m_layerstack); } else { // Regular image formats: flatten the image first. return toImage().save(filename); } }
double FuncionChi2VoronoiImagen::f (double pars[]) { double **imagen, ret = 0; int nx = im->size[0], ny = im->size[1]; // Verificamos que los poligonos esten dentro del cuadrado. for (int i = 0; i < n_pars / 3; i++) { if (pars[3 * i] < -1e-5 || pars[3 * i] > 1 || pars[3 * i + 1] < -1e-5 || pars[3 * i + 1] > 1) { cerr << "ERROR en FuncionChi2VoronoiImagen::f\n"; cerr << " pol [" << i << "] = {" << pars[3 * i] << ", " << pars[3 * i + 1] << ", " << pars[3 * i + 2] << "}\n"; cerr << " n_pars = " << n_pars << "\n"; //return 1e300; } } if (malla != NULL) { eliminarMallaVoronoi (malla); } malla = newMallaVoronoi (); for (int i = 0; i < n_pars / 3; i++) { //cout << "insertando {" << pars[3 * i] << ", " << pars[3 * i + 1] << ", " // << pars[3 * i + 2] << "}\n"; insertarSitio (malla, &(pars[3 * i]), &(pars[3 * i + 1]), pars[3 * i + 2]); } imagen = toImage (malla, nx, ny, NULL); /* struct image *fg_image = do_read ("../../gaussianas3.fits"); for (int i = 0; i < fg_image->size[0]; i++) { for (int j = 0; j < fg_image->size[1]; j++) { fg_image->pixels[i + j * fg_image->size[0]] = imagen[i][j]; } } do_write_fits (fg_image, "!auxF.fits"); do_write_fits (im, "!auxIm.fits"); */ for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++) { ret += pow (imagen [i][j] - im->pixels[i + j * nx], 2); //cout << "restando " << imagen [i][j] << " - " << im->pixels[i + j * nx] << "\n"; } free (imagen[i]); //delete [] (imagen[i]); } free (imagen); //delete [] imagen; //cout << "ret f = " << ret << "\n"; //cout << "ret 1/f = " << 1/ret << "\n"; return ret; }
bool ToDraw::contains(const QPointF &point) const { bool result = QGraphicsSvgItem::contains(point); if (result) { QRectF bounds = transform().mapRect(unclippedRect()); const QImage &img = toImage(elementId(), qRound(bounds.width()), qRound(bounds.height()), renderer()); QPointF transformedPoint = transform().map(point); result = qAlpha(img.pixel(transformedPoint.toPoint())) != 0; } return result; }
static JSValueRef pixmapToDataUrl(JSContextRef context, JSObjectRef function, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { QVariant& data = *static_cast<QVariant*>(JSObjectGetPrivate(object)); QByteArray byteArray; QBuffer buffer(&byteArray); toImage(data).save(&buffer, "PNG"); QByteArray encoded = QByteArray("data:image/png;base64,") + byteArray.toBase64(); JSRetainPtr<JSStringRef> str(Adopt, JSStringCreateWithUTF8CString(encoded.constData())); JSValueRef value = JSValueMakeString(context, str.get()); return value; }
void testGetArticulationPoints(TBlock *board, const TPos p1 = 0, const TPos p2 = 120){ #ifdef OPENCV imshow("test", toImage(board)); #endif // OPENCV TBlock oBoard[BOARD_SIZE]; CArticulationPoints::getArticulationPoints(board, p1, p2, oBoard); printBoard(oBoard, true); #ifdef OPENCV waitKey(100); #endif // OPENCV system("pause"); }
void testRateBoard(TBlock*board, const TPos p1 = 0, const TPos p2 = 120){ if (isIsolated(board, p1, p2)) return; #ifdef OPENCV while (true){ imshow("test", toImage(board)); int c = waitKey(10); // if (c == ' ') break; } #endif // OPENCV CHeuristicBase::simpleRateBoard(board, p1, p2, PLAYER_1); }
static JSValueRef pixmapToImageData(JSContextRef context, JSObjectRef function, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { QVariant& data = *static_cast<QVariant*>(JSObjectGetPrivate(object)); QImage image = toImage(data); int width = image.width(); int height = image.height(); RefPtr<ImageData> imageData = ImageData::create(IntSize(width, height)); copyPixelsInto(image, width, height, imageData->data()->data()); JSDOMGlobalObject* globalObject = static_cast<JSDOMGlobalObject*>(::toJS(JSContextGetGlobalObject(context))); JSC::ExecState* exec = ::toJS(context); return ::toRef(exec, toJS(exec, globalObject, imageData.get())); }
static int Image_blit(lua_State* L){ int argc = lua_gettop(L); ge_Image* dest = selfImage(L, &argc); if(argc < 3){ return luaL_error(L, "Argument error: geImage.Blit(x, y, image, [sx, sy, width, height, flags]) takes at least 3 arguments."); } int x = luaL_checkint(L, 1); int y = luaL_checkint(L, 2); ge_Image* img = *toImage(L, 3); int sx = 0; int sy = 0; int width = img->width; int height = img->height; int flags = 0; if(argc > 3){ sx = luaL_checkint(L, 4); } if(argc > 4){ sy = luaL_checkint(L, 5); } if(argc > 5){ width = luaL_checkint(L, 6); } if(argc > 6){ height = luaL_checkint(L, 7); } if(argc > 7){ flags = luaL_checkint(L, 8); } if(dest){ geBlitImageToImage(x, y, img, sx, sy, width, height, dest); }else{ geBlitImage(x, y, img, sx, sy, width, height, flags); } return 1; }
QVariant QtPixmapRuntime::toQt(JSContextRef context, JSObjectRef obj, QMetaType::Type hint, JSValueRef* exception) { if (!obj) return emptyVariantForHint(hint); if (JSValueIsObjectOfClass(context, obj, QtPixmapRuntime::getClassRef())) { QVariant* originalVariant = static_cast<QVariant*>(JSObjectGetPrivate(obj)); if (hint == qMetaTypeId<QPixmap>()) return QVariant::fromValue<QPixmap>(toPixmap(*originalVariant)); if (hint == qMetaTypeId<QImage>()) return QVariant::fromValue<QImage>(toImage(*originalVariant)); } JSObject* jsObject = ::toJS(obj); if (!jsObject->inherits(&JSHTMLImageElement::s_info)) return emptyVariantForHint(hint); JSHTMLImageElement* elementJSWrapper = static_cast<JSHTMLImageElement*>(jsObject); HTMLImageElement* imageElement = static_cast<HTMLImageElement*>(elementJSWrapper->impl()); if (!imageElement) return emptyVariantForHint(hint); CachedImage* cachedImage = imageElement->cachedImage(); if (!cachedImage) return emptyVariantForHint(hint); Image* image = cachedImage->imageForRenderer(imageElement->renderer()); if (!image) return emptyVariantForHint(hint); QImage* nativeImage = image->nativeImageForCurrentFrame(); if (!nativeImage) return emptyVariantForHint(hint); return (hint == static_cast<QMetaType::Type>(qMetaTypeId<QPixmap>())) ? QVariant::fromValue<QPixmap>(QPixmap::fromImage(*nativeImage)) : QVariant::fromValue<QImage>(*nativeImage); }
static JSValueRef assignToHTMLImageElement(JSContextRef context, JSObjectRef function, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { if (!argumentCount) return JSValueMakeUndefined(context); JSObjectRef objectArg = JSValueToObject(context, arguments[0], exception); if (!objectArg) return JSValueMakeUndefined(context); JSObject* jsObject = ::toJS(objectArg); if (!jsObject->inherits(&JSHTMLImageElement::s_info)) return JSValueMakeUndefined(context); QVariant& data = *static_cast<QVariant*>(JSObjectGetPrivate(object)); // We now know that we have a valid <img> element as the argument, we can attach the image to it. RefPtr<StillImage> stillImage = WebCore::StillImage::create(toImage(data)); HTMLImageElement* imageElement = static_cast<HTMLImageElement*>(static_cast<JSHTMLImageElement*>(jsObject)->impl()); imageElement->setCachedImage(new CachedImage(stillImage.get())); return JSValueMakeUndefined(context); }
bool IPLData::isConvertibleTo(IPLDataType dataType) { switch (dataType) { case IPLData::IMAGE_BW: case IPLData::IMAGE_GRAYSCALE: case IPLData::IMAGE_COLOR: return toImage() != NULL; case IPLData::IMAGE_COMPLEX: return toComplexImage() != NULL; case IPLData::POINT: return toPoint() != NULL; case IPLData::MATRIX: return toMatrix() != NULL; case IPLData::IMAGE_ORIENTED: case IPLData::SHAPES: case IPLData::UNDEFINED: default: throw std::logic_error("Unknown method for data type"); break; } return false; }
QImage CanvasModel::selectionToImage(int layerId) const { QImage img; paintcore::Layer *layer = m_layerstack->getLayer(layerId); if(layer) img = layer->toImage(); else img = toImage(); if(m_selection) { img = img.copy(m_selection->boundingRect().intersected(QRect(0, 0, img.width(), img.height()))); if(!m_selection->isAxisAlignedRectangle()) { // Mask out pixels outside the selection QPainter mp(&img); mp.setCompositionMode(QPainter::CompositionMode_DestinationIn); mp.drawImage(0, 0, m_selection->shapeMask(Qt::white)); } } return img; }
// ----------------------------------------------------------------------------- // Returns the texture matching [name], loading it from resources if necessary. // If [mixed] is true, flats are also searched if no matching texture is found // ----------------------------------------------------------------------------- const MapTextureManager::Texture& MapTextureManager::texture(std::string_view name, bool mixed) { // Get texture matching name auto& mtex = textures_[StrUtil::upper(name)]; // Get desired filter type auto filter = OpenGL::TexFilter::Linear; if (map_tex_filter == 0) filter = OpenGL::TexFilter::NearestLinearMin; else if (map_tex_filter == 1) filter = OpenGL::TexFilter::Linear; else if (map_tex_filter == 2) filter = OpenGL::TexFilter::LinearMipmap; else if (map_tex_filter == 3) filter = OpenGL::TexFilter::NearestMipmap; // If the texture is loaded if (mtex.gl_id) { // If the texture filter matches the desired one, return it auto& tex_info = OpenGL::Texture::info(mtex.gl_id); if (tex_info.filter == filter) return mtex; else { // Otherwise, reload the texture OpenGL::Texture::clear(mtex.gl_id); mtex.gl_id = 0; } } // Texture not found or unloaded, look for it // Look for stand-alone textures first auto etex = App::resources().getTextureEntry(name, "hires", archive_); auto textypefound = CTexture::Type::HiRes; if (etex == nullptr) { etex = App::resources().getTextureEntry(name, "textures", archive_); textypefound = CTexture::Type::Texture; } if (etex) { SImage image; // Get image format hint from type, if any if (Misc::loadImageFromEntry(&image, etex)) { mtex.gl_id = OpenGL::Texture::createFromImage(image, palette_.get(), filter); // Handle hires texture scale if (textypefound == CTexture::Type::HiRes) { auto ref = App::resources().getTextureEntry(name, "textures", archive_); if (ref) { SImage imgref; if (Misc::loadImageFromEntry(&imgref, ref)) { int w, h, sw, sh; w = image.width(); h = image.height(); sw = imgref.width(); sh = imgref.height(); mtex.world_panning = true; mtex.scale = { (double)sw / (double)w, (double)sh / (double)h }; } } } } } // Try composite textures then auto ctex = App::resources().getTexture(name, archive_); if (ctex) // Composite textures take precedence over the textures directory { textypefound = CTexture::Type::WallTexture; SImage image; if (ctex->toImage(image, archive_, palette_.get(), true)) { mtex.gl_id = OpenGL::Texture::createFromImage(image, palette_.get(), filter); double sx = ctex->scaleX(); if (sx == 0) sx = 1.0; double sy = ctex->scaleY(); if (sy == 0) sy = 1.0; mtex.world_panning = ctex->worldPanning(); mtex.scale = { 1.0 / sx, 1.0 / sy }; } } // Not found if (!mtex.gl_id) { // Try flats if mixed if (mixed) return flat(name, false); // Otherwise use missing texture mtex.gl_id = OpenGL::Texture::missingTexture(); } return mtex; }
// ----------------------------------------------------------------------------- // Returns the flat matching [name], loading it from resources if necessary. // If [mixed] is true, textures are also searched if no matching flat is found // ----------------------------------------------------------------------------- const MapTextureManager::Texture& MapTextureManager::flat(std::string_view name, bool mixed) { // Get flat matching name auto& mtex = flats_[StrUtil::upper(name)]; // Get desired filter type auto filter = OpenGL::TexFilter::Linear; if (map_tex_filter == 0) filter = OpenGL::TexFilter::NearestLinearMin; else if (map_tex_filter == 1) filter = OpenGL::TexFilter::Linear; else if (map_tex_filter == 2) filter = OpenGL::TexFilter::LinearMipmap; else if (map_tex_filter == 3) filter = OpenGL::TexFilter::NearestMipmap; // If the texture is loaded if (mtex.gl_id) { // If the texture filter matches the desired one, return it auto& tex_info = OpenGL::Texture::info(mtex.gl_id); if (tex_info.filter == filter) return mtex; else { // Otherwise, reload the texture OpenGL::Texture::clear(mtex.gl_id); mtex.gl_id = 0; } } if (mixed) { auto ctex = App::resources().getTexture(name, archive_); if (ctex && ctex->isExtended() && ctex->type() != "WallTexture") { SImage image; if (ctex->toImage(image, archive_, palette_.get(), true)) { mtex.gl_id = OpenGL::Texture::createFromImage(image, palette_.get(), filter); double sx = ctex->scaleX(); if (sx == 0) sx = 1.0; double sy = ctex->scaleY(); if (sy == 0) sy = 1.0; mtex.scale = { 1.0 / sx, 1.0 / sy }; mtex.world_panning = ctex->worldPanning(); return mtex; } } } // Flat not found, look for it // Palette8bit* pal = getResourcePalette(); if (!mtex.gl_id) { auto entry = App::resources().getTextureEntry(name, "hires", archive_); if (entry == nullptr) entry = App::resources().getTextureEntry(name, "flats", archive_); if (entry == nullptr) entry = App::resources().getFlatEntry(name, archive_); if (entry) { SImage image; if (Misc::loadImageFromEntry(&image, entry)) mtex.gl_id = OpenGL::Texture::createFromImage(image, palette_.get(), filter); } } // Not found if (!mtex.gl_id) { // Try textures if mixed if (mixed) return texture(name, false); // Otherwise use missing texture else mtex.gl_id = OpenGL::Texture::missingTexture(); } return mtex; }
// ----------------------------------------------------------------------------- // Returns the sprite matching [name], loading it from resources if necessary. // Sprite name also supports wildcards (?) // ----------------------------------------------------------------------------- const MapTextureManager::Texture& MapTextureManager::sprite( std::string_view name, std::string_view translation, std::string_view palette) { // Don't bother looking for nameless sprites if (name.empty()) return tex_invalid; // Get sprite matching name /*auto hashname = StrUtil::upper(name); if (!translation.empty()) hashname += StrUtil::lower(translation); if (!palette.empty()) hashname += StrUtil::upper(palette);*/ auto hashname = fmt::format("{}{}{}", name, translation, palette); StrUtil::upperIP(hashname); auto& mtex = sprites_[hashname]; // Get desired filter type auto filter = OpenGL::TexFilter::Linear; if (map_tex_filter == 0) filter = OpenGL::TexFilter::NearestLinearMin; else if (map_tex_filter == 1) filter = OpenGL::TexFilter::Linear; else if (map_tex_filter == 2) filter = OpenGL::TexFilter::Linear; else if (map_tex_filter == 3) filter = OpenGL::TexFilter::NearestMipmap; // If the texture is loaded if (mtex.gl_id) { // If the texture filter matches the desired one, return it auto& tex_info = OpenGL::Texture::info(mtex.gl_id); if (tex_info.filter == filter) return mtex; else { // Otherwise, reload the texture OpenGL::Texture::clear(mtex.gl_id); mtex.gl_id = 0; } } // Sprite not found, look for it bool found = false; bool mirror = false; SImage image; // Palette8bit* pal = getResourcePalette(); auto entry = App::resources().getPatchEntry(name, "sprites", archive_); if (!entry) entry = App::resources().getPatchEntry(name, "", archive_); if (!entry && name.length() == 8) { std::string newname{ name }; newname[4] = name[6]; newname[5] = name[7]; newname[6] = name[4]; newname[7] = name[5]; entry = App::resources().getPatchEntry(newname, "sprites", archive_); if (entry) mirror = true; } if (entry) { found = true; Misc::loadImageFromEntry(&image, entry); } else // Try composite textures then { auto ctex = App::resources().getTexture(name, archive_); if (ctex && ctex->toImage(image, archive_, palette_.get(), true)) found = true; } // We have a valid image either from an entry or a composite texture. if (found) { auto pal = palette_.get(); // Apply translation if (!translation.empty()) image.applyTranslation(translation, pal, true); // Apply palette override if (!palette.empty()) { auto newpal = App::resources().getPaletteEntry(palette, archive_); if (newpal && newpal->size() == 768) { pal = image.palette(); pal->loadMem(newpal->data()); } } // Apply mirroring if (mirror) image.mirror(false); // Turn into GL texture mtex.gl_id = OpenGL::Texture::createFromImage(image, pal, filter, false); return mtex; } else if (name.back() == '?') { name.remove_suffix(1); auto stex = &sprite(fmt::format("{}0", name), translation, palette); if (!stex->gl_id) stex = &sprite(fmt::format("{}1", name), translation, palette); if (stex->gl_id) return *stex; if (!stex->gl_id && name.length() == 5) { for (char chr = 'A'; chr <= ']'; ++chr) { stex = &sprite(fmt::format("{}0{}0", name, chr), translation, palette); if (stex->gl_id) return *stex; stex = &sprite(fmt::format("{}1{}1", name, chr), translation, palette); if (stex->gl_id) return *stex; } } } return tex_invalid; }
/*! Creates a \c HBITMAP equivalent to the QPixmap. Returns the \c HBITMAP handle. If \a mask is not NULL, the mask mode is turned on. In this mode, the bitmap mask is also created from the QPixmap's mask and returned in the given variable. This bitmap mask will contain two vertically adjacent sections, the first of which is the AND mask and the second one is the XOR mask (according to WinCreatePointer() specification). Also, in mask mode, the HBITMAP returned for the pixmap itself will be prepared for masking (with transparent pixels made black). This mode is useful for creating system icons and pointers (\sa toPmHPOINTER()). if \a embedRealAlpha is \c true, the real alpha chennel (not the 1bpp mask) will be embedded in the high 8 bits of the 32-bit pixel value for each pixel in the created bitmap (which always has 1 plane and the 32-bit depth). This extra information isn't touched by PM/GPI but may be used by custom drawing routines to do real alpha blending. Note that if \a mask is not NULL but the pixmap does neither have a mask nor the alpha channel, an emptpy bitmap mask with no transparency (zeroed AND and XOR parts) will be created and returned. It is the caller's responsibility to free both returned \c HBITMAP handes after use. \warning This function is only available on OS/2. \sa fromPmHBITMAP(), toPmHPOINTER() */ HBITMAP QPixmap::toPmHBITMAP(HBITMAP *mask, bool embedRealAlpha) const { if (data->classId() != QPixmapData::RasterClass) { QPixmapData *data = new QRasterPixmapData(depth() == 1 ? QPixmapData::BitmapType : QPixmapData::PixmapType); data->fromImage(toImage(), Qt::AutoColor); return QPixmap(data).toPmHBITMAP(mask, embedRealAlpha); } QRasterPixmapData* d = static_cast<QRasterPixmapData*>(data.data()); int w = d->image.width(); int h = d->image.height(); HPS hps = qt_alloc_mem_ps(w, h * 2); if (hps == NULLHANDLE) return NULLHANDLE; HBITMAP hbm = NULLHANDLE; HBITMAP hbmMask = NULLHANDLE; // Note that we always use ARGB32 even if embedRealAlpha is false because // in this case we will use the alpha channel to dither the 1bpp mask QImage image = d->image.convertToFormat(QImage::Format_ARGB32); // flip the bitmap top to bottom for PM image = image.mirrored(); // bitmap header + 2 palette entries (for the mask) char bmi[sizeof(BITMAPINFOHEADER2) + 4 * 2]; memset(bmi, 0, sizeof(bmi)); PBITMAPINFOHEADER2 bmh = (PBITMAPINFOHEADER2)bmi; bmh->cbFix = sizeof(BITMAPINFOHEADER2); PULONG pal = (PULONG)(bmi + sizeof(BITMAPINFOHEADER2)); // create the normal bitmap from the pixmap data bmh->cx = w; bmh->cy = h; bmh->cPlanes = 1; bmh->cBitCount = 32; hbm = GpiCreateBitmap(hps, bmh, CBM_INIT, (PBYTE)(const uchar *)image.bits(), (PBITMAPINFO2)&bmi); if (mask) { // get the mask QImage mask; if (hasAlpha()) { if (!embedRealAlpha) { // We prefer QImage::createAlphaMask() over QPixmap::mask() // since the former will dither while the latter will convert any // non-zero alpha value to an opaque pixel mask = image.createAlphaMask().convertToFormat(QImage::Format_Mono); // note: for some strange reason, createAlphaMask() (as opposed to // mask().toImage()) returns an image already flipped top to bottom, // so take it into account // create the AND mask mask.invertPixels(); // add the XOR mask (and leave it zeroed) mask = mask.copy(0, -h, w, h * 2); } else { // if we embedded real alpha, we still need a mask if we are going // to create a pointer out of this pixmap (WinCreatePointerIndirect() // requirement), but we will use QPixmap::mask() because it won't be // able to destroy the alpha channel of non-fully transparent pixels // when preparing the color bitmap for masking later. We could also // skip this prepare step, but well, let's go this way, it won't hurt. mask = this->mask().toImage().convertToFormat(QImage::Format_Mono); // create the AND mask mask.invertPixels(); // add the XOR mask (and leave it zeroed) mask = mask.copy(0, 0, w, h * 2); // flip the bitmap top to bottom for PM mask = mask.mirrored(false, true); } } else { mask = QImage(w, h * 2, QImage::Format_Mono); mask.fill(0); } // create the mask bitmap bmh->cbFix = sizeof(BITMAPINFOHEADER2); bmh->cx = w; bmh->cy = h * 2; bmh->cPlanes = 1; bmh->cBitCount = 1; bmh->cclrUsed = 2; pal[0] = 0; pal[1] = 0x00FFFFFF; hbmMask = GpiCreateBitmap(hps, bmh, CBM_INIT, (PBYTE)(const uchar *)mask.bits(), (PBITMAPINFO2)&bmi); // prepare the bitmap for masking by setting transparent pixels to black GpiSetBitmap(hps, hbm); POINTL ptls[] = { { 0, 0 }, { w - 1, h - 1 }, // dst: inclusive-inclusive { 0, h }, { w, h * 2 }, // src: inclusive-exclusive }; ptls[0].y -= h; ptls[1].y -= h; enum { AllImageAttrs = IBB_COLOR | IBB_BACK_COLOR | IBB_MIX_MODE | IBB_BACK_MIX_MODE }; IMAGEBUNDLE ib = { CLR_TRUE, CLR_FALSE, FM_OVERPAINT, BM_OVERPAINT }; GpiSetAttrs(hps, PRIM_IMAGE, AllImageAttrs, 0, (PBUNDLE)&ib); GpiDrawBits(hps, (PBYTE)(const uchar *)mask.bits(), (PBITMAPINFO2)&bmi, 4, ptls, ROP_SRCAND, BBO_IGNORE); } qt_free_mem_ps(hps); if (mask) *mask = hbmMask; return hbm; }
std::shared_ptr<gameplay::Texture> DWordTexture::toTexture() const { auto tex = std::make_shared<gameplay::Texture>(toImage(), false); return tex; }
QPixmap QPlatformPixmap::transformed(const QTransform &matrix, Qt::TransformationMode mode) const { return QPixmap::fromImage(toImage().transformed(matrix, mode)); }
void Layer::resize(int top, int right, int bottom, int left) { // Minimize amount of data that needs to be copied optimize(); // Resize sublayers foreach(Layer *sl, _sublayers) sl->resize(top, right, bottom, left); // Calculate new size int width = left + _width + right; int height = top + _height + bottom; int xtiles = Tile::roundTiles(width); int ytiles = Tile::roundTiles(height); QVector<Tile> tiles(xtiles * ytiles); // if there is no old content, resizing is simple bool hascontent = false; for(int i=0;i<_tiles.count();++i) { if(!_tiles.at(i).isBlank()) { hascontent = true; break; } } if(!hascontent) { _width = width; _height = height; _xtiles = xtiles; _ytiles = ytiles; _tiles = tiles; return; } // Sample colors around the layer edges to determine fill color // for the new tiles Tile bgtile; { QColor bgcolor = _sampleEdgeColors(this, top>0, right>0, bottom>0, left>0); if(bgcolor.alpha()>0) bgtile = Tile(bgcolor); } if((left % Tile::SIZE) || (top % Tile::SIZE)) { // If top/left adjustment is not divisble by tile size, // we need to move the layer content QImage oldcontent = toImage(); _width = width; _height = height; _xtiles = xtiles; _ytiles = ytiles; _tiles = tiles; if(left<0 || top<0) { int cropx = 0; if(left<0) { cropx = -left; left = 0; } int cropy = 0; if(top<0) { cropy = -top; top = 0; } oldcontent = oldcontent.copy(cropx, cropy, oldcontent.width()-cropx, oldcontent.height()-cropy); } _tiles.fill(bgtile); putImage(left, top, oldcontent, false); } else { // top/left offset is aligned at tile boundary: // existing tile content can be reused const int firstrow = Tile::roundTiles(-top); const int firstcol = Tile::roundTiles(-left); int oldy = firstrow; for(int y=0;y<ytiles;++y,++oldy) { int oldx = firstcol; const int oldyy = _xtiles * oldy; const int yy = xtiles * y; for(int x=0;x<xtiles;++x,++oldx) { const int i = yy + x; if(oldy<0 || oldy>=_ytiles || oldx<0 || oldx>=_xtiles) { tiles[i] = bgtile; } else { const int oldi = oldyy + oldx; tiles[i] = _tiles.at(oldi); } } } _width = width; _height = height; _xtiles = xtiles; _ytiles = ytiles; _tiles = tiles; } }
void testFindPath(TBlock *board, const TPos&p = 0) { static CMyTimer* timer = CMyTimer::getInstance(); TPos pos = p; int c = 0; int upper = 0, lower = 0, exact = 0, calculatedExact = 0; bool bOk; #ifdef OPENCV imshow("original board", toImage(board)); waitKey(1); #endif // OPENCV upper = CBC::calculateLength(board, pos, true, EXACT_AREA_BELOW_10); assert(upper != TIMEOUT_POINTS); if (upper > 45) return; // { // int t1, t2; // static CBCO o; // CBC::calculateBCs(board, &o, pos); // t1 = CBC::calculateLength(board, pos, false, ESTIMATE_ALL); // t2 = o.findLengthOfLongestPath(ESTIMATE_ALL); // assert(t1 == t2); // // t1 = CBC::calculateLength(board, pos, false, EXAXT_AREA_BELOW_10); // t2 = o.findLengthOfLongestPath(EXAXT_AREA_BELOW_10); // assert(t1 == t2); // // t1 = CBC::calculateLength(board, pos, false, EXAXT_AREA_BELOW_25); // t2 = o.findLengthOfLongestPath(EXAXT_AREA_BELOW_25); // assert(t1 == t2); // // t1 = CBC::calculateLength(board, pos, false, EXACT); // t2 = o.findLengthOfLongestPath(EXACT); // assert(t1 == t2); // // return; // } nTimes++; cout << "Upper Estimated length : " << upper << endl; timer->reset(); calculatedExact = CBC::calculateLength(board, pos, false, EXACT); assert(calculatedExact != TIMEOUT_POINTS); int timeInMs = timer->getTimeInMs(); cout << "Exact Calculated length : " << calculatedExact << " calculated in " << timeInMs << " ms\n"; exact = exploreMapWithoutRecursion(board, BOARD_SIZE, pos); cout << "Exact length : " << exact << endl; lower = CHeuristicBase::getLowerLengthOfTheLongestPath(board, pos); cout << "Lower Estimated length : " << lower << endl; int travelled = 0; while (true){ if (getAvailableMoves(board, pos).size() == 0) break; timer->reset(); TMove i = CHeuristicBase::getFirstMove(board, pos, EXACT, -1); int temp = CBC::calculateLength(board, pos, false, EXACT); assert(temp != TIMEOUT_POINTS); assert(travelled + temp == exact); travelled++; bOk = move(board, pos, i); assert(bOk); pos = MOVE(pos, i); #ifdef OPENCV imshow("game", toImage(board)); waitKey(1); #endif // OPENCV } cout << "Traveled length : " << travelled << endl << endl; if (lower == exact) lowwer_extract++; if (travelled == exact) traveled_exact++; if (upper > exact) upper_extract++; if (calculatedExact != exact || calculatedExact != travelled || upper < exact) system("pause"); }
void ListViewSingleButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // // This method paints a new row into the listview // painter->save(); // Set normal background color painter->setBrush((QColor("#ffffff"))); // Alternating rows if (index.row() % 2) { // Set brush to aliceblue painter->setBrush((QColor("#f5f5f5"))); } if(index.model()->data(index, Qt::UserRole + 4).toInt() == ConnectionState::Error) { painter->setBrush(QColor("#FFCCCC")); } QString textBottom (index.model()->data(index, Qt::UserRole + 101).toString()); QString textName (index.data(Qt::DisplayRole).toString()); // Hindergrund zeichnen painter->setPen(Qt::NoPen); if (textBottom == "__divider__") { painter->setBrush(QBrush(QColor("#f2f2f2"))); //0053a1 painter->drawRect(option.rect); painter->setPen(Qt::lightGray); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); if (index.row() == 0) { painter->drawLine(option.rect.topLeft(), option.rect.topRight()); } painter->setPen(Qt::black); QStyleOptionViewItem nOptionD (option); QFont sdasda("Verdana", 10, QFont::Normal); //sdasda.setPixelSize(11); painter->setFont(sdasda); nOptionD.rect.adjust(3, 0, 0, 0); painter->drawText(nOptionD.rect, textName); rectForRow.insert(index.row(), QRect()); rectForRow[index.row()] = option.rect; painter->restore(); return; } painter->drawRect(option.rect); // Get text QString ip (index.data(Qt::UserRole + 1).toString()); quint32 lastUsed(index.data(Qt::UserRole + 2).toUInt()); quint32 lastConnected(index.data(Qt::UserRole + 3).toUInt()); // Set and calc items width int buttonWidth (36* windowsDpiScale()); int buttonHeight (36* windowsDpiScale()); int marginRight (10* windowsDpiScale()); int marginTop (5* windowsDpiScale()); // Draw delete button QStyleOptionViewItem buttonOption (option); // -10 is the right margin, the margin is necessary to reset the state when mouse is leaving to the right side buttonOption.rect.setRight(buttonWidth + 2 * marginRight); buttonOption.rect.setHeight(buttonHeight); buttonOption.rect.adjust(10* windowsDpiScale(), option.rect.height() / 2 - buttonHeight / 2, -(marginRight), marginTop + 1); buttonOption.rect.setHeight(buttonHeight); // Draw delete button and return limits // This is to figure out which button is under the mouse position rectForRow.insert(index.row(), QRect()); rectForRow[index.row()] = buttonOption.rect; auto drawButton = [](const QModelIndex &index, QPainter *painter, const QRect &rect, int role, ConnectionState conState) { // Draw delete button QStyleOptionButton buttonStyle; // // Set the button state to enabled buttonStyle.state |= QStyle::State_Enabled; // Set postion and size to the item buttonStyle.rect = rect; // Button is a flat button buttonStyle.features = QStyleOptionButton::Flat; // No text, only an icon // Icon default is 16x16 buttonStyle.iconSize = QSize(16* windowsDpiScale(), 16* windowsDpiScale()); // // Set the button states ButtonState state = (ButtonState) index.data(role).toInt(); QPen pen; pen.setWidth(1); switch(conState) { case ConnectionState::Disconnected: { if(state == Hover) { pen.setColor("#808080"); painter->setBrush(QBrush("#F0D151")); } else if(state == Pressed) { } else { pen.setColor("#808080"); painter->setBrush(QBrush("#EEEEEC")); } } break; case ConnectionState::Connecting: { if(state == Hover) { pen.setColor("#808080"); painter->setBrush(QBrush("#EEEEEC")); } else if(state == Pressed) { } else { pen.setColor("#808080"); painter->setBrush(QBrush("#F1C40F")); } } break; case ConnectionState::Connected: { if(state == Hover) { pen.setColor("#808080"); painter->setBrush(QBrush("#EEEEEC")); } else if(state == Pressed) { } else { pen.setColor("#808080"); painter->setBrush(QBrush("#72C02C")); } } break; case ConnectionState::Error: { if(state == Hover) { pen.setColor("#808080"); painter->setBrush(QBrush("#F0D151")); } else if(state == Pressed) { } else { pen.setColor("#808080"); painter->setBrush(QBrush("#FF0000")); } } break; default: { pen.setColor("#808080"); painter->setBrush(QBrush("#EEEEEC")); } } // Set the pen and draw the border of the button painter->setPen(pen); painter->drawRect(buttonStyle.rect); painter->setBrush(Qt::NoBrush); QRect buttonOption(rect); // Draw button QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonStyle, painter); }; ConnectionState conState = (ConnectionState)index.data(Qt::UserRole + 4).toInt(); drawButton(index, painter, buttonOption.rect, Qt::UserRole + 100, conState); // this->buttonLimits = this->drawButton(index, painter, buttonOption.rect, this->iconForType(this->buttonIconType, option), Qt::UserRole + 100); // Draw text QStyleOptionViewItem textOption (option); textOption.rect.adjust(buttonWidth + marginRight + 10 + 4, 4, buttonWidth + 2 * marginRight, 0); QPen pen; pen.setColor(QColor("#2c2c2c")); painter->setPen(pen); QFont font1("Verdana", 9, QFont::Normal); //font1.setPixelSize(11); QFont font2("Verdana", 7, QFont::Normal); //font2.setPixelSize(9); painter->setFont(font1); painter->drawText(textOption.rect, textName); textOption.rect.adjust(0, 13* windowsDpiScale(), 0, 0); painter->setFont(font2); //painter->drawText(textOption.rect, "Connected: "); //textOption.rect.adjust(0, 9, 0, 0); //painter->drawText(textOption.rect, "Last used: "); //textOption.rect.adjust(0, 9, 0, 0); typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>::type> days; std::chrono::seconds sec((QDateTime::currentDateTime().toTime_t() - lastConnected)); auto d = std::chrono::duration_cast<days>(sec); auto h = std::chrono::duration_cast<std::chrono::hours>(sec - d); auto m = std::chrono::duration_cast<std::chrono::minutes>((sec - d - h)); auto s = std::chrono::duration_cast<std::chrono::seconds>((sec - d - h - m)); QString day("%1%2 D "); day = day.arg(d.count() < 10 ? "0" : "") .arg(d.count()); QString hour("%1%2 H "); hour = hour.arg(h.count() < 10 ? "0" : "") .arg(h.count()); QString minute("%1%2 M "); minute = minute.arg(m.count() < 10 ? "0" : "") .arg(m.count()); switch(conState) { case ConnectionState::Connected: painter->drawText(textOption.rect, QObject::tr("Connected: ") + (day) + (hour) + (d.count() > 0 ? "" : minute)); break; case ConnectionState::Disconnected: painter->drawText(textOption.rect, QObject::tr("Last used: ") + (lastUsed == 0 ? QObject::tr("Never") : QDateTime::fromTime_t(lastUsed).toString("dd.MM.yy hh:mm"))); break; default: painter->drawText(textOption.rect, QObject::tr("Last used: ") + (lastUsed == 0 ? QObject::tr("Never") : QDateTime::fromTime_t(lastUsed).toString("dd.MM.yy hh:mm"))); break; }; if(buttonOption.rect.size() != _lastImgSize) { imgStart = imgStart_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgOffline = imgOffline_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgError = imgError_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgOnline = imgOnline_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgStop = imgStop_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgConnecting = imgConnecting_.scaled(buttonOption.rect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); auto s = buttonOption.rect.size(); // I dont know why this thing has to be adjusted, but well, it works. s.setWidth(s.width() - 1); s.setHeight(s.height() - 1); movieKeks->setScaledSize(s); QSize size(16, 16); imgIconUsers = imgIconUsers_.scaled(size * windowsDpiScale(), Qt::KeepAspectRatio, Qt::SmoothTransformation); imgIconAutostart = imgIconAutostart_.scaled(size * windowsDpiScale(), Qt::KeepAspectRatio, Qt::SmoothTransformation); _lastImgSize = buttonOption.rect.size(); } buttonOption.rect.adjust(((buttonWidth) - imgStart.width()) / 2 +1, ((buttonWidth) - imgStart.height()) / 2 + 1, 0, 0); ButtonState state = (ButtonState) index.data(Qt::UserRole + 100).toInt(); switch(conState) { case ConnectionState::Disconnected: { if(state == Hover) painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgStart); else painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgOffline); } break; case ConnectionState::Connecting: { if(state == Hover) painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgStop); else { auto pixx = movieKeks->currentPixmap(); //auto size = imgStart.size(); ////size.setHeight(size.height() -10); //pixx = pixx.scaled(imgStart.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), pixx.toImage()); } } break; case ConnectionState::Connected: { if(state == Hover) painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgStop); else painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgOnline); } break; case ConnectionState::Error: { if(state == Hover) painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgStart); else painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgError); } break; default: { if(state == Hover) painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgStart); else painter->drawImage(buttonOption.rect.left(), buttonOption.rect.top(), imgOffline); } } static const int iconPadding = 5; textOption.rect.setTop(buttonOption.rect.bottom()); textOption.rect.adjust(0, -imgIconAutostart.height()+2, 0, 0); textOption.rect.setWidth(imgIconAutostart.width()); if(index.data(Qt::UserRole + 5).toBool()) { painter->drawImage(textOption.rect.left(), textOption.rect.top(), imgIconAutostart); textOption.rect.adjust(imgIconAutostart.width() + iconPadding, 0, 0, 0); } if(index.data(Qt::UserRole + 6).toBool()) { painter->drawImage(textOption.rect.left(), textOption.rect.top(), imgIconUsers); textOption.rect.adjust(imgIconAutostart.width() + iconPadding, 0, 0, 0); } painter->setPen(Qt::lightGray); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); // Restore saved painter painter->restore(); }