Beispiel #1
0
void ImageWidget::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu;

    if (mType == Photo) {
        if (!mReadOnly) {
            menu.addAction(i18n("Change photo..."), this, SLOT(changeImage()));
            menu.addAction(i18n("Change URL..."), this, SLOT(changeUrl()));
        }

        if (mHasImage) {
            menu.addAction(i18n("Save photo..."), this, SLOT(saveImage()));

            if (!mReadOnly) {
                menu.addAction(i18n("Remove photo"), this, SLOT(deleteImage()));
            }
        }
    } else {
        if (!mReadOnly) {
            menu.addAction(i18n("Change logo..."), this, SLOT(changeImage()));
            menu.addAction(i18n("Change URL..."), this, SLOT(changeUrl()));
        }

        if (mHasImage) {
            menu.addAction(i18n("Save logo..."), this, SLOT(saveImage()));

            if (!mReadOnly) {
                menu.addAction(i18n("Remove logo"), this, SLOT(deleteImage()));
            }
        }
    }

    menu.exec(event->globalPos());
}
Beispiel #2
0
void motion(int x,int y) {
    switch(action) {
    case MOVE:
        renderCam->positions->x-=(float)(x-xStart)*0.01f;
        renderCam->positions->y+=(float)(y-yStart)*0.01f;
        deleteImage();
        break;
    case ZOME:
        renderCam->positions->z+=float(y-yStart)*0.01f;
        deleteImage();
        break;
    }
    xStart=x;
    yStart=y;
    glutPostRedisplay();
}
Beispiel #3
0
void ThumbView::slImageChanged( KFileItem *kfit )
{
   if( ! kfit ) return;
   // kdDebug(28000) << "changes to one thumbnail!" << endl;

   KURL thumbDir = currentDir();
   KURL itemUrl = kfit->url();

   /* delete filename */
   itemUrl.setFileName( QString());
   if( !itemUrl.equals( thumbDir, true ))
   {
      // kdDebug(28000) << "returning, because directory does not match: " << itemUrl.prettyURL() << endl;
      // kdDebug(28000) << "and my URL: " << thumbDir.prettyURL() << endl;
      return;
   }

   if( deleteImage( kfit ))
   {
      kdDebug(28000) << "was changed, deleted first!" << endl;
   }
   /* Trigger a new reading */
   KFileItemList li;
   li.append( kfit );
   slNewFileItems( li );
}
Beispiel #4
0
void HistoryDialog::contextMenu(QPoint point)
{
  mContextIndex = ui->tableView->indexAt(point);;

  QMenu contextMenu(ui->tableView);

  QAction copyAction((mContextIndex.column() == 0) ? tr("Copy Path") : tr("Copy URL"), &contextMenu);
  connect(&copyAction, SIGNAL(triggered()), this, SLOT(copy()));
  contextMenu.addAction(&copyAction);

  QAction deleteAction(tr("Delete from imgur.com"), &contextMenu);
  QAction locationAction(tr("Open Location"), &contextMenu);

  QAction removeAction(tr("Remove history entry"), &contextMenu);

  if (mContextIndex.data().toString().isEmpty()) {
    copyAction.setEnabled(false);
    deleteAction.setEnabled(false);
  }

  if (mContextIndex.column() == 0) {
    connect(&locationAction, SIGNAL(triggered()), this, SLOT(location()));
    contextMenu.addAction(&locationAction);
  }
  else {
    connect(&deleteAction, SIGNAL(triggered()), this, SLOT(deleteImage()));
    contextMenu.addAction(&deleteAction);
  }

  connect(&removeAction, SIGNAL(triggered()), this, SLOT(removeHistoryEntry()));
  contextMenu.addAction(&removeAction);
  contextMenu.exec(QCursor::pos());
}
Beispiel #5
0
void ThumbView::slImageDeleted( KFileItem *kfit )
{
   deleteImage( kfit );


   /*
    From a mail from Waldo pointing out two probs in Thumbview:

    1) KDirLister is the owner of the KFileItems it emits, this means
       that you must watch it's deleteItem() signal vigourously,
       otherwise you may end up with KFileItems that are already
       deleted. This burden is propagated to classes that use
       KDirLister, such as KFileIconView.

       This has a tendency to go wrong in combination with PreviewJob,
       because it stores a list of KFileItems while running. This has
       the potential to crash if the fileitems are being deleted
       during this time. The remedy is to make sure to remove
       fileitems that get deleted from the PreviewJob with
       PreviewJob::removeItem.

   */
   if( m_job )  /* is a job running? Remove the item from it if existing. */
   {
       m_job->removeItem( kfit );
   }

   /* check if it is in the pending list */
   m_pendingJobs.removeRef(kfit);
}
Beispiel #6
0
BoxImage::~BoxImage()
{
    if (state == CompletelyAvailable) {
        for (unsigned i = 0; i < frameCount; ++i)
            deleteImage(pixels + i * (naturalWidth * naturalHeight * 4));
    }
    delete pixels;
}
Beispiel #7
0
int l_Image_Delete( lua_State* L )
{
	ImageData* imgData = lua_checkimage( L, 1 );

	free( imgData->imgData );
	deleteImage(imgData);

	return 0;
}
void LLViewerImageList::updateImagesDecodePriorities()
{
	// Update the decode priority for N images each frame
	{
		const size_t max_update_count = llmin((S32) (1024*gFrameIntervalSeconds) + 1, 32); //target 1024 textures per second
		S32 update_counter = llmin(max_update_count, mUUIDMap.size()/10);
		uuid_map_t::iterator iter = mUUIDMap.upper_bound(mLastUpdateUUID);
		while(update_counter > 0 && !mUUIDMap.empty())
		{
			if (iter == mUUIDMap.end())
			{
				iter = mUUIDMap.begin();
			}
			mLastUpdateUUID = iter->first;
			LLPointer<LLViewerImage> imagep = iter->second;
			++iter; // safe to incrament now

			//
			// Flush formatted images using a lazy flush
			//
			const F32 LAZY_FLUSH_TIMEOUT = 30.f;
			S32 min_refs = 3; // 1 for mImageList, 1 for mUUIDMap, 1 for local reference
			if (imagep->hasCallbacks())
			{
				min_refs++; // Add an extra reference if we're on the loaded callback list
			}
			S32 num_refs = imagep->getNumRefs();
			if (num_refs == min_refs)
			{
				if (imagep->mLastReferencedTimer.getElapsedTimeF32() > LAZY_FLUSH_TIMEOUT)
				{
					// Remove the unused image from the image list
					deleteImage(imagep);
					imagep = NULL; // should destroy the image
					continue;
				}
			}
			else
			{
				imagep->mLastReferencedTimer.reset();
			}
			
			imagep->processTextureStats();
			F32 old_priority = imagep->getDecodePriority();
			F32 decode_priority = imagep->calcDecodePriority();
			// Ignore < 20% difference
			if ((decode_priority < old_priority * .8f || decode_priority > old_priority * 1.25f))
			{
				removeImageFromList(imagep);
				imagep->setDecodePriority(decode_priority);
				addImageToList(imagep);
			}
			update_counter--;
		}
	}
}
Beispiel #9
0
void EResurse::loadImage(){
    if(Picture)
        deleteImage();
    QFile f(_url);
    if(f.open(QIODevice::ReadOnly)){
        QDataStream stream(&f);
        QString patch;
        stream>>patch;
        Picture= ESprite::getHeidImage(patch);
        f.close();
    }else{
Beispiel #10
0
void setupSizeResource()
{
    deleteImage(img);
    free(img_content);
    checkCudaErrors(cuMemFree(d_img_content));

    item_size = width * height * 4;

    img = createImage(width, height);
    img_content = (unsigned char*)malloc(item_size);
    checkCudaErrors(cuMemAlloc(&d_img_content, item_size));
    checkCudaErrors(cuMemcpyHtoD(d_fragColor, &d_img_content, d_fragColor_bytes));
}
void ScreenImageMgr::createScreenImage(const QString& id, const QString& filename, float x, float y,
	float scale, bool visible, float alpha, float fadeDuration)
{
	// First check to see if there is already an image loaded with the
	// specified ID, and drop it if necessary
	if (allScreenImages.contains(id))
		deleteImage(id);

	ScreenImage* i = new ScreenImage(filename, x, y, visible, scale, alpha, fadeDuration);
	if (i==NULL)
		return;

	allScreenImages[id] = i;
}
Beispiel #12
0
bool DTrash::deleteDirRecursivley(const QString& dirToDelete)
{
    QDir srcDir(dirToDelete);

    foreach (const QFileInfo& fileInfo, srcDir.entryInfoList(QDir::Files))
    {
        if (!deleteImage(fileInfo.filePath()))
        {
            return false;
        }
    }

    foreach (const QFileInfo& fileInfo, srcDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
        deleteDirRecursivley(fileInfo.filePath());
    }

    return srcDir.removeRecursively();
}
Beispiel #13
0
Photos::Photos(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Photos)
{
    ui->setupUi(this);

    position = 0;
    original_x = 40;
    original_y = 18;
    image_width = 380;
    image_height = 200;
    transform_flag = 0;
    widget_width = QWidget::width();
    widget_height = QWidget::height();

    mouse_flag = 0;
    static_height = 50;
    static_width =  80;

   // translateLanguage();
    designUI();

    this->setMouseTracking(true);
    this->setWindowFlags(Qt::FramelessWindowHint);

    connect(ui->open_pushButton, SIGNAL(clicked()), this, SLOT(openFiles()));
    connect(ui->previous_pushButton, SIGNAL(clicked()), this, SLOT(previousPhoto()));
    connect(ui->next_pushButton, SIGNAL(clicked()), this, SLOT(nextPhoto()));
  //  connect(ui->previous_Button, SIGNAL(clicked()), this, SLOT(previousPhoto()));
    //connect(ui->next_Button, SIGNAL(clicked()), this, SLOT(nextPhoto()));
    connect(ui->expand_pushButton, SIGNAL(clicked()), this, SLOT(expandImage()));
    connect(ui->narrow_pushButton, SIGNAL(clicked()), this, SLOT(narrowImage()));
    connect(ui->delete_pushButton, SIGNAL(clicked()), this, SLOT(deleteImage()));
    connect(ui->adjust_pushButton, SIGNAL(clicked()), this, SLOT(adjustPhoto()));


   // QPainter *painter1 = new QPainter;
   // painter1->setBrush(Qt::black);
    //painter1->drawPixmap(original_x, original_y, image_width, image_height, pixmap);


}
Beispiel #14
0
QString BackEnd::deleteSelectedImages()
{
    auto selectedImagesIndexes = m_imagesSelection.selectedIndexes();

    if (!selectedImagesIndexes.empty())
    {
        QList<QPersistentModelIndex> selectedImagesPersistentIndexes;
        for (auto index : selectedImagesIndexes)
            selectedImagesPersistentIndexes.append(QPersistentModelIndex(index));

        for (auto index : selectedImagesPersistentIndexes)
        {
            auto msg = deleteImage(index);
            if (msg != "")
                return failedMsg + " (удалена часть изображений)";
        }
    }

    return "";
}
Beispiel #15
0
bool SmugMug::deleteDuplicates(SmugID albumId)
{
	OwnedArray<ImageItem> images;
	if (getImages(images, albumId))
	{
		OwnedArray<SmugID> duplicateIds;
		StringArray fileNames;

		for (int i = 0; i < images.size(); i++)
		{
			if (fileNames.contains(images[i]->filename))
				duplicateIds.add(new SmugID(images[i]->id));
			else
				fileNames.add(images[i]->filename);
		}

		for (int i = 0; i < duplicateIds.size(); i++)
			deleteImage(*duplicateIds[i]);

		return true;
	}
	return false;
}
Beispiel #16
0
void keyboard(unsigned char key, int x, int y)
{
    //std::cout << key << std::endl;
    switch (key)
    {
    case(27):
        exit(1);
        break;

    case 'w':
        (renderCam->positions)->y+=1.0f;
        deleteImage();
        break;
    case 's':
        (renderCam->positions)->y-=1.0f;
        deleteImage();
        break;

    case 'a':
        (renderCam->positions)->x+=1.0f;
        deleteImage();
        break;
    case 'd':
        (renderCam->positions)->x-=1.0f;
        deleteImage();
        break;

    case 'q':
        (renderCam->positions)->z+=1.0f;
        deleteImage();
        break;
    case 'e':
        (renderCam->positions)->z-=1.0f;
        deleteImage();
        break;
    }

    glutPostRedisplay();
}
Beispiel #17
0
/**
 * OCR process from gray image input
 */
int ocrProcess(Image binImg) {

    int i, h, w;
    h = binImg.h;
    w = binImg.w;
    int count =0, lCount = 0;

    int start = 0;
    int endLine = 0;
    int nLine;
    Rect rect;

    int* charIndex[20];

    system("rm -rf data");
    system("mkdir -p data");
    system("rm -rf leven");
    system("mkdir -p leven");


    createNetworkFromFile();

    /// segmentation processing
    while((nLine = ccLineLabeling(binImg, start))!= 0) {
        if(nLine < 3) continue;
        printf("%d\n",nLine);
        int baseLine = getBaselineHeight(nLine);

//        int avgSpace = getAverageSpace(nLine);
        /// get slant deg
        int slantDeg = getSlantDeg(binImg, baseLine, nLine);
//        printf("slantDeg = %d\n", slantDeg);

        int nChar = 0;

        for(i = 0; i < nLine; i++) {
            int index = getSegmentIndex(i);
//            printf("%d ", index);
            rect = getCharRect(index);
            endLine = endLine > (rect.y + rect.h) ? endLine :(rect.y + rect.h);
            Image charImg = getImageFromRect(binImg, rect, index);
            if(slantDeg) {
                charImg = slantRemoval(charImg, slantDeg);
            }
//            char* name = (char*) malloc(20* sizeof(char));
//            sprintf(name, "out_s_%d_%d.txt", lCount, i);
//            printImage(charImg, name);

            charImg = contourFinding(charImg);
            smoothContour(charImg);
            thinImageOnMatch(charImg);
            double* input = getFeature(charImg);
            double prop, maxProp = 0.0;

            /// recognition
            nChar++;
            charIndex[nChar-1] = charRecognition(input, &prop);


            /// check space
            //int space = getSpace(i, nLine, binImg);
            //if(space > baseLine/2) {//printf(" ");
            //    createWordFst(charIndex, nChar);
            //    nChar = 0;
            //    printf(" ");
            //}
            deleteImage(charImg);
            free(input);
            count++;
//            }
//            printf(" ");
//            start_w = end_w;
//            deleteImage(wordImg);
        }
        printf("\n");
        start = endLine;
        lCount++;
    }
    deleteImage(binImg);
    deleteNetwork();
    printf("%d\n", count);
    return 0;
}
Beispiel #18
0
GBitmap::~GBitmap()
{
   deleteImage();
}
void LLViewerTextureList::updateImagesDecodePriorities()
{
	// Update the decode priority for N images each frame
	{
		const size_t max_update_count = llmin((S32) (1024*gFrameIntervalSeconds) + 1, 32); //target 1024 textures per second
		S32 update_counter = llmin(max_update_count, mUUIDMap.size()/10);
		uuid_map_t::iterator iter = mUUIDMap.upper_bound(mLastUpdateUUID);
		while(update_counter > 0 && !mUUIDMap.empty())
		{
			if (iter == mUUIDMap.end())
			{
				iter = mUUIDMap.begin();
			}
			mLastUpdateUUID = iter->first;
			LLPointer<LLViewerFetchedTexture> imagep = iter->second;
			++iter; // safe to incrament now

			//
			// Flush formatted images using a lazy flush
			//
			const F32 LAZY_FLUSH_TIMEOUT = 30.f; // stop decoding
			const F32 MAX_INACTIVE_TIME  = 50.f; // actually delete
			S32 min_refs = 3; // 1 for mImageList, 1 for mUUIDMap, 1 for local reference
			if (imagep->hasCallbacks())
			{
				min_refs++; // Add an extra reference if we're on the loaded callback list
			}
			S32 num_refs = imagep->getNumRefs();
			if (num_refs == min_refs)
			{
				if (imagep->getLastReferencedTimer()->getElapsedTimeF32() > LAZY_FLUSH_TIMEOUT)
				{
					// Remove the unused image from the image list
					deleteImage(imagep);
					imagep = NULL; // should destroy the image								
				}
				continue;
			}
			else
			{
				if(imagep->hasSavedRawImage())
				{
					if(imagep->getElapsedLastReferencedSavedRawImageTime() > MAX_INACTIVE_TIME)
					{
						imagep->destroySavedRawImage() ;
					}
				}

				if(imagep->isDeleted())
				{
					continue ;
				}
				else if(imagep->isDeletionCandidate())
				{
					imagep->destroyTexture() ;																
					continue ;
				}
				else if(imagep->isInactive())
				{
					if (imagep->getLastReferencedTimer()->getElapsedTimeF32() > MAX_INACTIVE_TIME)
					{
						imagep->setDeletionCandidate() ;
					}
					continue ;
				}
				else
				{
					imagep->getLastReferencedTimer()->reset();

					//reset texture state.
					imagep->setInactive() ;										
				}
			}
			
			imagep->processTextureStats();
			F32 old_priority = imagep->getDecodePriority();
			F32 old_priority_test = llmax(old_priority, 0.0f);
			F32 decode_priority = imagep->calcDecodePriority();
			F32 decode_priority_test = llmax(decode_priority, 0.0f);
			// Ignore < 20% difference
			if ((decode_priority_test < old_priority_test * .8f) ||
				(decode_priority_test > old_priority_test * 1.25f))
			{
				removeImageFromList(imagep);
				imagep->setDecodePriority(decode_priority);
				addImageToList(imagep);
			}
			update_counter--;
		}
	}
}
Beispiel #20
0
int main() {
    createWindow(640, 480);
    int framecnt = 0;

    Image* img = loadTGAImage("cat.tga");
    if(img == NULL) {
        printf("ERROR: Could not open image file\n");
        exit(1);
    }
    Image* font = loadTGAImage("font.tga");
    if(font == NULL) {
        printf("ERROR: Could not load font file\n");
        exit(1);
    }

    int mousePos[2] = {0, 0};

    while(1) {
        KeyEvent ev;
        profileBlockStart("eventHandling");
        while(pollEvent(&ev)) {
            switch(ev.type) {
            case KEY_DOWN:
                printf("Keycode: %d\n", ev.key);
                if(ev.key == 53) {
                    goto endGame;
                }
                break;
            case MOUSE_MOVE:
                mousePos[0] = ev.posx;
                mousePos[1] = ev.posy;
                break;
            }
        }
        profileBlockEnd("eventHandling");
        Image* fb = getFramebuffer();
        profileBlockStart("clearFramebuffer");
        Color backColor = color(0, 30, 140, 40);
        clear(fb, &backColor);
        profileBlockEnd("clearFramebuffer");

        profileBlockStart("paintCats");
        for(int i = 0; i < 300; i++) {
            paint(PAINT_OVER, img, fb, (int)(fb->width / 2 + (i * 0.7) * sin(i * 1.221 + framecnt * 0.004)),
                  (int)(fb->height / 2 + (i * 0.7) * cos(i * 1.221 + framecnt * 0.004)));
        }
        profileBlockEnd("paintCats");

        profileBlockStart("paintText");
        Color textColor = color(255, 200, 250, 255);
        textColor.a = (framecnt * 32) % 256;
        drawText(fb, font, &textColor, "Hello world!", mousePos[0], mousePos[1]);
        drawButton(fb, font, "Click here!", 120, 200);

        profileBlockEnd("paintText");

        profileBlockStart("flush");
        flushFramebuffer();
        profileBlockEnd("flush");
        framecnt++;
    }

endGame:
    saveProfile("_profile.json");
    deleteImage(img);
    closeWindow();
}
Beispiel #21
0
void AnimationFrame::cut()
{
    mClipboard->setMimeData(mModel->mimeData(animator->getSelection()));
    deleteImage();
}
Beispiel #22
0
bool ImageViewer::openImage(const QString &fileName)
{
    if ( !fileName.isEmpty() )
    {
        deleteImage();

        std::string sstr = fileName.toLocal8Bit().data();
        IplImage* newImage = cvLoadImage( sstr.c_str(), 1 );

        if ( !newImage )
        {
            QMessageBox::warning( this,
                                  tr("提示"),
                                  tr("无法打开文件 %1.\n").arg(fileName),
                                  QMessageBox::Close);
            return false;
        }

        _orgWidth = newImage->width;
        _orgHeight = newImage->height;

        if (cv::max(newImage->width,newImage->height) > 800)
        {
            _scale = cv::max(newImage->width/600.0f, newImage->height/600.0f);
            _ocvImage = cvCreateImage(cvSize(newImage->width/_scale, newImage->height/_scale), 8, 3);
            cvResize(newImage,_ocvImage);
        }
        else if (newImage->width <= 250 || newImage->height <= 250)
        {
            _scale = cv::min(newImage->width/300.0f, newImage->height/300.0f);
            _ocvImage = cvCreateImage(cvSize(newImage->width/_scale,newImage->height/_scale),8,3);
            cvResize(newImage,_ocvImage);
        }
        else
        {
            _ocvImage = cvCreateImage(cvSize(newImage->width, newImage->height), 8, 3);
            cvCopy(newImage, _ocvImage);
        }


        if( !_srcOcvImage )
        {
            _srcOcvImage = cvCreateImage(cvSize(_ocvImage->width, _ocvImage->height), _ocvImage->depth, _ocvImage->nChannels);
            cvCopy(_ocvImage, _srcOcvImage);
        }

        _srcWidth = _ocvImage->width;
        _srcHeight = _ocvImage->height;

        _labelMapImage = new QImage(_ocvImage->width, _ocvImage->height, QImage::Format_ARGB32);
        QImage _alphaImage(_ocvImage->width, _ocvImage->height, QImage::Format_Indexed8);
        _alphaImage.fill(255);
        _labelMapImage->setAlphaChannel(_alphaImage);
        _labelMapImage->fill(qRgb(0, 0, 0));

        QImage *image = IplImageToQImage( _ocvImage );

        setImage( *image );
        DELETEPTR(image);

        if(CV_IS_IMAGE(newImage))
        {
            cvReleaseImage(&newImage);
            newImage = 0;
        }
    }
    return true;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
  // Main function for the raytracer. Parses input parameters,
  // sets up the initial blank image, and calls the functions
  // that set up the scene and do the raytracing.
  struct image *im; // Will hold the raytraced image
  struct view *cam; // Camera and view for this scene
  int sx;   // Size of the raytraced image
  int antialiasing; // Flag to determine whether antialiaing is enabled or disabled
  char output_name[1024]; // Name of the output file for the raytraced .ppm image
  struct point3D e;   // Camera view parameters 'e', 'g', and 'up'
  struct point3D g;
  struct point3D up;
  double du, dv;      // Increase along u and v directions for pixel coordinates
  struct point3D pc,d;    // Point structures to keep the coordinates of a pixel and
        // the direction or a ray
  struct ray3D *ray;    // Structure to keep the ray from e to a pixel
  // struct colourRGB col;    // Return colour for raytraced pixels
  struct colourRGB background;   // Background colour
  int i,j;      // Counters for pixel coordinates
  unsigned char *rgbIm;

  if (argc<5)
  {
    fprintf(stderr,"RayTracer: Can not parse input parameters\n");
    fprintf(stderr,"USAGE: RayTracer size rec_depth antialias output_name\n");
    fprintf(stderr,"   size = Image size (both along x and y)\n");
    fprintf(stderr,"   rec_depth = Recursion depth\n");
    fprintf(stderr,"   antialias = A single digit, 0 disables antialiasing. Anything else enables antialiasing\n");
    fprintf(stderr,"   output_name = Name of the output file, e.g. MyRender.ppm\n");
    exit(0);
  }
  sx=atoi(argv[1]);
  MAX_DEPTH=atoi(argv[2]);
  if (atoi(argv[3])==0) antialiasing=0; else antialiasing=1;
    strcpy(&output_name[0],argv[4]);

  fprintf(stderr,"Rendering image at %d x %d\n",sx,sx);
  fprintf(stderr,"Recursion depth = %d\n",MAX_DEPTH);
  if (!antialiasing) fprintf(stderr,"Antialising is off\n");
  else  fprintf(stderr,"Antialising is on\n");
  fprintf(stderr,"Output file name: %s\n",output_name);

  object_list=NULL;
  light_list=NULL;
  texture_list=NULL;

  // Allocate memory for the new image
  im=newImage(sx, sx);
  if (!im)
  {
    fprintf(stderr,"Unable to allocate memory for raytraced image\n");
    exit(0);
  }
  else rgbIm=(unsigned char *)im->rgbdata;

  ///////////////////////////////////////////////////
  // TO DO: You will need to implement several of the
  //        functions below. For Assignment 3, you can use
  //        the simple scene already provided. But
  //        for Assignment 4 you need to create your own
  //        *interesting* scene.
  ///////////////////////////////////////////////////
  buildScene();   // Create a scene. This defines all the
      // objects in the world of the raytracer

  //////////////////////////////////////////
  // TO DO: For Assignment 3 you can use the setup
  //        already provided here. For Assignment 4
  //        you may want to move the camera
  //        and change the view parameters
  //        to suit your scene.
  //////////////////////////////////////////

  // Mind the homogeneous coordinate w of all vectors below. DO NOT
  // forget to set it to 1, or you'll get junk out of the
  // geometric transformations later on.

  // Camera center is at (0,0,-1)
  e.px=0;
  e.py=0;
  e.pz=-1;
  e.pw=1;

  // To define the gaze vector, we choose a point 'pc' in the scene that
  // the camera is looking at, and do the vector subtraction pc-e.
  // Here we set up the camera to be looking at the origin.
  g.px=0-e.px;
  g.py=0-e.py;
  g.pz=0-e.pz;
  g.pw=1;
  // In this case, the camera is looking along the world Z axis, so
  // vector w should end up being [0, 0, -1]

  // Define the 'up' vector to be the Y axis
  up.px=0;
  up.py=1;
  up.pz=0;
  up.pw=1;

  // Set up view with given the above vectors, a 4x4 window,
  // and a focal length of -1 (why? where is the image plane?)
  // Note that the top-left corner of the window is at (-2, 2)
  // in camera coordinates.
  cam=setupView(&e, &g, &up, -1, -2, 2, 4);

  if (cam==NULL)
  {
    fprintf(stderr,"Unable to set up the view and camera parameters. Our of memory!\n");
    cleanup(object_list,light_list, texture_list);
    deleteImage(im);
    exit(0);
  }

  // Set up background colour here
  background.R=0;
  background.G=0;
  background.B=0;

  // Do the raytracing
  //////////////////////////////////////////////////////
  // TO DO: You will need code here to do the raytracing
  //        for each pixel in the image. Refer to the
  //        lecture notes, in particular, to the
  //        raytracing pseudocode, for details on what
  //        to do here. Make sure you undersand the
  //        overall procedure of raytracing for a single
  //        pixel.
  //////////////////////////////////////////////////////
  du=cam->wsize/(sx-1);   // du and dv. In the notes in terms of wl and wr, wt and wb,
  dv=-cam->wsize/(sx-1);    // here we use wl, wt, and wsize. du=dv since the image is
        // and dv is negative since y increases downward in pixel
        // coordinates and upward in camera coordinates.
  colourRGB col;
  point3D origin;
  point3D direction;
  ray3D initialRay;
  colourRGB total;
  int offset;
  int aaSamples;
  fprintf(stderr,"View parameters:\n");
  fprintf(stderr,"Left=%f, Top=%f, Width=%f, f=%f\n",cam->wl,cam->wt,cam->wsize,cam->f);
  fprintf(stderr,"Camera to world conversion matrix (make sure it makes sense!):\n");
  printmatrix(cam->C2W);
  fprintf(stderr,"World to camera conversion matrix:\n");
  printmatrix(cam->W2C);
  fprintf(stderr,"\n");
  fprintf(stderr,"Rendering row: ");
  #pragma omp parallel for schedule(dynamic,32) shared(rgbIm, object_list, light_list, texture_list) private(j)
  for (j=0;j<sx;j++)    // For each of the pixels in the image
  // for (j=2;j<3;j++)
  {
    fprintf(stderr,"%d/%d, ",j,sx);
    #pragma omp parallel for private(origin, direction, col, initialRay, i, aaSamples, offset, total)
    for (i=0;i<sx;i++)
    // for (i=2;i<3;i++)
    {
      if (!antialiasing){
        col.R = 0;
        col.G = 0;
        col.B = 0;
        // = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
        origin.px = cam->wl+i*du;
        origin.py = cam->wt+j*dv;
        origin.pz = cam->f;
        origin.pw = 1.0;
        matVecMult(cam->C2W, &origin);
        // Construct direction vector using Pij - e
        // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
        direction.px = origin.px;
        direction.py = origin.py;
        direction.pz = origin.pz;
        direction.pw = 1.0;
        subVectors(&e, &direction);
        normalize(&direction);
        // Construct ray using both origin and direction.
        // ray3D initialRay;// = newRay(origin, direction);
        initialRay.p0 = origin;
        initialRay.d = direction;
        // Setting up colors.
        // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));

        // Tracing ray
        rayTrace(&initialRay, 1, &col, NULL);
        offset = (sx * j * 3) + (i * 3);
        *(rgbIm + offset + 0) = col.R*255;
        *(rgbIm + offset + 1) = col.G*255;
        *(rgbIm + offset + 2) = col.B*255;
        // Tear down col struct.
        // free(col);
      } else {
        total.R = 0;
        total.G = 0;
        total.B = 0;
        for (aaSamples = 0; aaSamples < 20; aaSamples ++){
          col.R = 0;
          col.G = 0;
          col.B = 0;
          // point3D origin;// = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
          origin.px = cam->wl+(i+drand48()-0.5)*du;
          origin.py = cam->wt+(j+drand48()-0.5)*dv;
          origin.pz = cam->f;
          origin.pw = 1.0;
          matVecMult(cam->C2W, &origin);
          // Construct direction vector using Pij - e
          // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
          direction.px = origin.px;
          direction.py = origin.py;
          direction.pz = origin.pz;
          direction.pw = 1.0;
          subVectors(&e, &direction);
          normalize(&direction);
          // Construct ray using both origin and direction.
          // ray3D initialRay;// = newRay(origin, direction);
          initialRay.p0 = origin;
          initialRay.d = direction;
          // Setting up colors.
          // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));
          // Tracing ray
          rayTrace(&initialRay, 1, &col, NULL);
          total.R += col.R;
          total.G += col.G;
          total.B += col.B;
        }
        offset = (sx * j * 3) + (i * 3);
        total.R = total.R / 20 * 255.0;
        total.G = total.G / 20 * 255.0;
        total.B = total.B / 20 * 255.0;
        *(rgbIm + offset + 0) = total.R;
        *(rgbIm + offset + 1) = total.G;
        *(rgbIm + offset + 2) = total.B;
      }
    } // end for i
  } // end for j
  
  fprintf(stderr,"\nDone!\n");

  // Output rendered image
  imageOutput(im,output_name);

  // Exit section. Clean up and return.
  cleanup(object_list,light_list,texture_list);   // Object, light, and texture lists
  deleteImage(im);          // Rendered image
  free(cam);            // camera view
  exit(0);
}
void BatchProcessImagesDialog::slotFinished()
{
    if (m_convertStatus == PROCESS_DONE)
    {
        // processAborted() has already been called. No need to show the warning.
        return;
    }

    BatchProcessImagesItem *item = static_cast<BatchProcessImagesItem*>(**m_listFile2Process_iterator);
    m_listFiles->scrollToItem(m_listFiles->currentItem());

    if (m_ProcessusProc->exitStatus() == QProcess::CrashExit)
    {
        int code = KMessageBox::warningContinueCancel(this,
                   i18n("The 'convert' program from 'ImageMagick' package has been stopped abnormally"),
                   i18n("Error running 'convert'"));

        if (code == KMessageBox::Cancel)
        {
            processAborted(true);
        }
        else
        {
            item->changeResult(i18nc("batch process result", "Failed."));
            item->changeError(i18n("'convert' program from 'ImageMagick' package "
                                   "has been stopped abnormally."));
            ++*m_listFile2Process_iterator;
            ++m_progressStatus;
            m_ui->m_progress->setValue((int)((float) m_progressStatus * (float) 100 / (float) m_nbItem));

            if (**m_listFile2Process_iterator)
                startProcess();
            else
                endProcess();
        }
        return;
    }

    int ValRet = m_ProcessusProc->exitCode();
    kWarning() << "Convert exit (" << ValRet << ")";

    switch (ValRet)
    {
        case 0:
        { // Process finished successfully !
            item->changeResult(i18n("OK"));
            item->changeError(i18n("no processing error"));
            processDone();

            KUrl src;
            src.setPath(item->pathSrc());
            KUrl dest = m_ui->m_destinationUrl->url();
            dest.addPath(item->nameDest());
            QString errmsg;

            KUrl::List urlList;
            urlList.append(src);
            urlList.append(dest);
            iface()->refreshImages(urlList);

            if (!item->overWrote())
            {
                // Do not add an entry if there was an image at the location already.
                bool ok = iface()->addImage(dest, errmsg);

                if (!ok)
                {
                    int code = KMessageBox::warningContinueCancel(this, i18n(
                                  "<qt>Error adding image to application; error message was: "
                                  "<b>%1</b></qt>", errmsg),
                              i18n("Error Adding Image to Application"));

                    if (code == KMessageBox::Cancel)
                    {
                        slotProcessStop();
                        break;
                    }
                    else
                    {
                        item->changeResult(i18nc("batch process result", "Failed."));
                    }
                }
            }

            if (src != dest)
            {
                // Clone data in KIPI host application.
                KPImageInfo info(src);
                info.cloneData(dest);

                // Move XMP sidecar file.
                KPMetadata::moveSidecar(src, dest);
            }

            if (m_ui->m_removeOriginal->isChecked() && src != dest)
            {
                KUrl deleteImage(item->pathSrc());

                if (KIO::NetAccess::del(deleteImage, kapp->activeWindow()) == false)
                {
                    item->changeResult(i18nc("batch process result", "Warning:"));
                    item->changeError(i18n("cannot remove original image file."));
                }
                else
                {
                    iface()->delImage(item->pathSrc());
                }
            }
            break;
        }
        case 15:
        { //  process aborted !
            processAborted(true);
            break;
        }
        default :
        { // Processing error !
            item->changeResult(i18nc("batch process result", "Failed."));
            item->changeError(i18n("cannot process original image file."));
            break;
        }
    }

    ++*m_listFile2Process_iterator;
    ++m_progressStatus;
    m_ui->m_progress->setValue((int)((float)m_progressStatus *(float)100 / (float)m_nbItem));

    if (**m_listFile2Process_iterator)
        startProcess();
    else
        endProcess();
}
void MyServer::slotReadClient()
{

    QTcpSocket* pClientSocket = (QTcpSocket*)sender();

    QDataStream in(pClientSocket);
    in.setVersion(QDataStream::Qt_5_3);


    for(;;){

        if(!nextBlockSize){
            if(pClientSocket->bytesAvailable() < sizeof(quint32)) {
                break;
            }

            in >> nextBlockSize;
        }

        if(pClientSocket->bytesAvailable() < nextBlockSize) {
            break;
        }


        QString request;
        in >> request;

        QStringList req_param = request.split(" ");

        if(req_param.at(0) == "GETCURRENTVERSION")
            sendCurrVers(pClientSocket);

        if(req_param.at(0) == "GETSUBJECTS")
            sendArrayToClient(pClientSocket,getSubjects());

        if(req_param.at(0) == "GETTHEMES")
            sendArrayToClient(pClientSocket,getThemes(req_param.at(1)));

        if(req_param.at(0) == "GETPICTURES")
            sendArrayToClient(pClientSocket,getPictures(req_param.at(1),req_param.at(2)));

        if(req_param.at(0) == "GETIMAGE")
            sendImageToClient(pClientSocket,getImage(req_param.at(1)));

        if(req_param.at(0) == "PUTSUBJECT"){
            putSubject(req_param.at(1));
            version++;
        }
        if(req_param.at(0) == "PUTTHEME"){
            putTheme(req_param.at(1),req_param.at(2));
            version++;
        }
        if(req_param.at(0) == "PUTIMAGE")
        {
            QImage img;

            in >> img;

            quint32 k = putImage(img,req_param.at(1),req_param.at(2), req_param.at(3));
            version++;
            QList<QString> lst;
            lst << QString("%1").arg(k);
            sendArrayToClient(pClientSocket,lst);
        }
        if(req_param.at(0) == "DELETESUBJECT"){
            deleteSubject(req_param.at(1));
            version++;
        }
        if(req_param.at(0) == "DELETETHEME"){
            deleteTheme(req_param.at(1),req_param.at(2));
            version++;
        }
        if(req_param.at(0) == "DELETEIMAGE"){
            deleteImage(req_param.at(1));
            version++;
        }
        if(req_param.at(0) == "SWAPIMAGE"){
            QImage img;

            in >> img;

            swapImage(img,req_param.at(1));
            version++;
        }
Beispiel #26
0
ImageViewer::~ImageViewer()
{
    deleteImage();
}