Revision 4181 org.gvsig.raster.gdal/trunk/org.gvsig.raster.gdal/org.gvsig.raster.gdal.io/src/main/java/org/gvsig/raster/gdal/io/GdalNative.java

View differences:

GdalNative.java
32 32

  
33 33
import org.gdal.gdal.Dataset;
34 34
import org.gdal.gdal.gdal;
35
import org.gdal.gdal.gdal;
36 35
import org.gdal.ogr.ogr;
36

  
37 37
import org.gvsig.fmap.dal.coverage.RasterLibrary;
38 38
import org.gvsig.fmap.dal.coverage.RasterLocator;
39 39
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
......
66 66
import org.gvsig.tools.task.TaskStatus;
67 67
/**
68 68
 * Soporte 'nativo' para ficheros desde GDAL.
69
 * 
69
 *
70 70
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
71 71
 * @author Nacho Brodin (nachobrodin@gmail.com)
72 72
 */
......
82 82
	private int[]                        dataType                = null;
83 83
	DataStoreMetadata                    metadata                = null;
84 84
	protected boolean                    georeferenced           = true;
85
	
85

  
86 86
	/**
87 87
	 * Vectores que contiene los desplazamientos de un pixel cuando hay supersampling.
88 88
	 * , es decir el n?mero de pixels de pantalla que tiene un pixel de imagen. Como todos
89 89
	 * los pixeles no tienen el mismo ancho y alto ha de meterse en un array y no puede ser
90
	 * una variable. Adem?s hay que tener en cuenta que el primer y ?ltimo pixel son de 
91
	 * distinto tama?o que el resto.   
90
	 * una variable. Adem?s hay que tener en cuenta que el primer y ?ltimo pixel son de
91
	 * distinto tama?o que el resto.
92 92
	 */
93 93
	public int[]                              stepArrayX             = null;
94 94
	public int[]                              stepArrayY             = null;
......
113 113
	protected DataStoreColorInterpretation    colorInterpr           = null;
114 114
	protected AffineTransform                 ownTransformation      = null;
115 115
	protected AffineTransform                 externalTransformation = new AffineTransform();
116
	
116

  
117 117
	public static int getGdalTypeFromRasterBufType(int rasterBufType) {
118 118
		switch (rasterBufType) {
119 119
			case Buffer.TYPE_BYTE: return Gdal.GDT_Byte;
......
127 127
		}
128 128
		return Gdal.GDT_Unknown;
129 129
	}
130
	
130

  
131 131
	/**
132 132
	 * Conversi?n de los tipos de datos de gdal a los tipos de datos de RasterBuf
133 133
	 * @param gdalType Tipo de dato de gdal
......
168 168
		}
169 169
		return Buffer.TYPE_UNDEFINED;
170 170
	}
171
	
171

  
172 172
	/**
173 173
	 * Overview usada en el ?ltimo setView
174 174
	 */
175 175
	int currentOverview = -1;
176
	
176

  
177 177
	public GdalNative(String fName) throws GdalException, IOException {
178 178
		super();
179 179
		init(fName);
180 180
	}
181
	
181

  
182 182
	private static long initializeGdal(String fName) throws GdalException {
183 183
		gdal.AllRegister();
184 184
		ogr.RegisterAll();
185 185
		Dataset data = gdal.Open(fName, 1);
186 186
		if (data == null)
187 187
			throw new GdalException("Error en la apertura del fichero. El fichero no tiene un formato v?lido.");
188
		
188

  
189 189
		return GdalDataset.getCPtr(data);
190 190
	}
191 191

  
......
194 194
//		isInitialized = true;
195 195
//		init(fName);
196 196
//	}
197
	
197

  
198 198
	private void init(String fName) throws GdalException, IOException {
199 199
		gdal.AllRegister();
200 200
		ogr.RegisterAll();
......
249 249
					isCorrect = true;
250 250
			if (!isCorrect)
251 251
				throw new GdalException("");
252
			
252

  
253 253
			double psX = trans.adfgeotransform[1];
254 254
			double psY = trans.adfgeotransform[5];
255 255
			double rotX = trans.adfgeotransform[4];
256 256
			double rotY = trans.adfgeotransform[2];
257 257
			double offX = trans.adfgeotransform[0];
258 258
			double offY = trans.adfgeotransform[3];
259
			
259

  
260 260
			ownTransformation = new AffineTransform(psX, rotX, rotY, psY, offX, offY);
261 261
					//trans.adfgeotransform[1], trans.adfgeotransform[4], trans.adfgeotransform[2], trans.adfgeotransform[5], trans.adfgeotransform[0], trans.adfgeotransform[3]);
262 262
			externalTransformation = (AffineTransform) ownTransformation.clone();
......
276 276
		}
277 277
//		}
278 278
	}
279
	
279

  
280 280
	/**
281 281
	 * Returns true if this provider is open and false if don't
282 282
	 * @return
......
284 284
	public boolean isOpen() {
285 285
		return open;
286 286
	}
287
	
287

  
288 288
	/**
289 289
	 * Obtiene el flag que informa de si el raster tiene valor no data o no.
290 290
	 * Consultar� todas las bandas del mismo y si alguna tiene valor no data
......
300 300
		}
301 301
		return false;
302 302
	}
303
	
303

  
304 304
	/**
305 305
	 * Obtiene el flag que informa de si el raster tiene valor no data o no
306 306
	 * en una banda concreta.
......
364 364
	 * Asigna el tipo de dato
365 365
	 * @param dt entero que representa el tipo de dato
366 366
	 */
367
	public void setDataType(int[] dt) { 
368
		dataType = dt; 
367
	public void setDataType(int[] dt) {
368
		dataType = dt;
369 369
	}
370
	
370

  
371 371
	/**
372 372
	 * Obtiene el tipo de dato
373 373
	 * @return entero que representa el tipo de dato
374 374
	 */
375
	public int[] getDataType() { 
376
		return dataType; 
375
	public int[] getDataType() {
376
		return dataType;
377 377
	}
378
	
378

  
379 379
	/**
380 380
	 * Gets the color interpretation
381 381
	 * @return
382 382
	 */
383
	public ColorInterpretation getColorInterpretation() { 
384
		return colorInterpr; 
383
	public ColorInterpretation getColorInterpretation() {
384
		return colorInterpr;
385 385
	}
386
	
386

  
387 387
	/**
388 388
	 * Gets the color table
389 389
	 * @return
......
391 391
	public ColorTable getColorTable() {
392 392
		return palette;
393 393
	}
394
	
394

  
395 395
	/**
396 396
	 * Obtiene un punto 2D con las coordenadas del raster a partir de uno en coordenadas
397 397
	 * del punto real.
......
401 401
	 */
402 402
	public Point2D worldToRasterWithoutRot(Point2D pt) {
403 403
		Point2D p = new Point2D.Double();
404
		AffineTransform at = new AffineTransform(	externalTransformation.getScaleX(), 0, 
405
													0, externalTransformation.getScaleY(), 
404
		AffineTransform at = new AffineTransform(	externalTransformation.getScaleX(), 0,
405
													0, externalTransformation.getScaleY(),
406 406
													externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
407 407
		try {
408 408
			at.inverseTransform(pt, p);
......
411 411
		}
412 412
		return p;
413 413
	}
414
		
414

  
415 415
	/**
416 416
	 * Obtiene un punto 2D con las coordenadas del raster a partir de uno en coordenadas
417 417
	 * del punto real.
......
428 428
		}
429 429
		return p;
430 430
	}
431
	
431

  
432 432
	/**
433 433
	 * Obtiene un punto del raster en coordenadas pixel a partir de un punto en coordenadas
434
	 * reales. 
434
	 * reales.
435 435
	 * @param pt Punto en coordenadas reales
436 436
	 * @return Punto en coordenadas pixel.
437 437
	 */
......
440 440
		externalTransformation.transform(pt, p);
441 441
		return p;
442 442
	}
443
	
443

  
444 444
	/**
445 445
	 * Calcula el overview a usar. Hay que tener en cuenta que tenemos que tener calculadas las variables
446 446
	 * viewPortScale, currentFullWidth y currentFulHeight
......
469 469
			}
470 470
		}
471 471
	}
472
	
472

  
473 473
	public void setView(double dWorldTLX, double dWorldTLY,
474 474
						double dWorldBRX, double dWorldBRY,
475 475
						int nWidth, int nHeight) throws GdalException {
......
490 490
		stepY = 1D / viewportScaleY;
491 491

  
492 492
		lastReadLine = Math.min(tl.getY(), br.getY());
493
		
493

  
494 494
		//Para lectura del renderizado (ARGB). readWindow selecciona las bandas que necesita.
495 495

  
496 496
		// calcula el overview a usar
497 497
		gdalBands = new GdalRasterBand[4];
498 498
		calcOverview(tl, br);
499 499
	}
500
	
500

  
501 501
	/**
502 502
	 * Selecciona bandas y overview en el objeto GdalRasterBand[] para el n�mero de bandas solicitado.
503 503
	 * @param nbands N�mero de bandas solicitado.
......
529 529
			}
530 530
		}
531 531
	}
532
		
532

  
533 533
	int lastY = -1;
534
	
534

  
535 535
	/**
536 536
	 * Lee una l�nea de bytes
537 537
	 * @param line Buffer donde se cargan los datos
......
549 549
			}
550 550
		}
551 551
	}
552
	
552

  
553 553
	/**
554 554
	 * Lee una l�nea de shorts
555 555
	 * @param line Buffer donde se cargan los datos
......
603 603
			}
604 604
		}
605 605
	}
606
	
606

  
607 607
	/**
608 608
	 * Lee una l�nea de doubles
609 609
	 * @param line Buffer donde se cargan los datos
......
624 624

  
625 625
	/**
626 626
	 * Lee una l�nea completa del raster y devuelve un array del tipo correcto. Esta funci�n es util
627
	 * para una lectura rapida de todo el fichero sin necesidad de asignar vista. 
627
	 * para una lectura rapida de todo el fichero sin necesidad de asignar vista.
628 628
	 * @param nLine N�mero de l�nea a leer
629 629
	 * @param band Banda requerida
630 630
	 * @return Object que es un array unidimendional del tipo de datos del raster
......
654 654
		if (dataType[band] == GDT_CInt16 || dataType[band] == GDT_CInt32 ||
655 655
				dataType[band] == GDT_CFloat32 || dataType[band] == GDT_CFloat64)
656 656
			return null;
657
		
657

  
658 658
		return null;
659 659
	}
660
	
660

  
661 661
	/**
662 662
	 * Lee una bloque completo del raster y devuelve un array tridimensional del tipo correcto. Esta funci�n es util
663
	 * para una lectura rapida de todo el fichero sin necesidad de asignar vista. 
663
	 * para una lectura rapida de todo el fichero sin necesidad de asignar vista.
664 664
	 * @param nLine N�mero de l�nea a leer
665 665
	 * @param band Banda requerida
666 666
	 * @return Object que es un array unidimendional del tipo de datos del raster
......
672 672
		int heightBuffer = (int)(blockHeight * scale);
673 673

  
674 674
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
675
				
675

  
676 676
		GdalRasterBand[] gdalBand = new GdalRasterBand[bBandNr];
677
		for (int iBand = 0; iBand < gdalBand.length; iBand++) 
677
		for (int iBand = 0; iBand < gdalBand.length; iBand++)
678 678
			gdalBand[iBand] = super.getRasterBand(iBand + 1);
679
				
679

  
680 680
		GdalBuffer[] gdalBuf = new GdalBuffer[bBandNr];
681
				
681

  
682 682
		if (dataType[0] == GDT_Byte) {
683 683
			byte[][][] buf = new byte[bBandNr][heightBuffer][widthBuffer];
684 684
			for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
685 685
				gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
686 686
				for (int iRow = 0; iRow < heightBuffer; iRow++) {
687
					for (int iCol = 0; iCol < widthBuffer; iCol++) 
687
					for (int iCol = 0; iCol < widthBuffer; iCol++)
688 688
						buf[iBand][iRow][iCol] = gdalBuf[iBand].buffByte[iRow * widthBuffer + iCol];
689 689
					if(task.getEvent() != null)
690 690
						task.manageEvent(task.getEvent());
691 691
				}
692 692
				gdalBuf[iBand].buffByte = null;
693
			}	
693
			}
694 694
			return buf;
695 695
		} else if (dataType[0] == GDT_CInt16 || dataType[0] == GDT_Int16  || dataType[0] == GDT_UInt16) {
696 696
			short[][][] buf = new short[bBandNr][heightBuffer][widthBuffer];
697 697
			for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
698 698
				gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
699 699
				for (int iRow = 0; iRow < heightBuffer; iRow++) {
700
					for (int iCol = 0; iCol < widthBuffer; iCol++) 
700
					for (int iCol = 0; iCol < widthBuffer; iCol++)
701 701
						buf[iBand][iRow][iCol] = gdalBuf[iBand].buffShort[iRow * widthBuffer + iCol];
702 702
					if(task.getEvent() != null)
703 703
						task.manageEvent(task.getEvent());
704 704
				}
705 705
				gdalBuf[iBand].buffShort = null;
706
			}	
706
			}
707 707
			return buf;
708 708
		} else if (dataType[0] == GDT_CInt32 || dataType[0] == GDT_Int32  || dataType[0] == GDT_UInt32) {
709 709
			int[][][] buf = new int[bBandNr][heightBuffer][widthBuffer];
710 710
			for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
711 711
				gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
712
				for (int iRow = 0; iRow < heightBuffer; iRow++) { 
712
				for (int iRow = 0; iRow < heightBuffer; iRow++) {
713 713
					for (int iCol = 0; iCol < widthBuffer; iCol++)
714 714
						buf[iBand][iRow][iCol] = gdalBuf[iBand].buffInt[iRow * widthBuffer + iCol];
715 715
					if(task.getEvent() != null)
716 716
						task.manageEvent(task.getEvent());
717 717
				}
718 718
				gdalBuf[iBand].buffInt = null;
719
			}	
719
			}
720 720
			return buf;
721 721
		} else if(dataType[0] == GDT_Float32 || dataType[0] == GDT_CFloat32) {
722 722
			float[][][] buf = new float[bBandNr][heightBuffer][widthBuffer];
......
729 729
						task.manageEvent(task.getEvent());
730 730
				}
731 731
				gdalBuf[iBand].buffFloat = null;
732
			}	
732
			}
733 733
			return buf;
734 734
		} else if(dataType[0] == GDT_Float64 || dataType[0] == GDT_CFloat64) {
735 735
			double[][][] buf = new double[bBandNr][heightBuffer][widthBuffer];
736 736
			for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
737 737
				gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
738 738
				for (int iRow = 0; iRow < heightBuffer; iRow++) {
739
					for (int iCol = 0; iCol < widthBuffer; iCol++) 
739
					for (int iCol = 0; iCol < widthBuffer; iCol++)
740 740
						buf[iBand][iRow][iCol] = gdalBuf[iBand].buffDouble[iRow * widthBuffer + iCol];
741 741
					if(task.getEvent() != null)
742 742
						task.manageEvent(task.getEvent());
743 743
				}
744 744
				gdalBuf[iBand].buffDouble = null;
745
			}		
745
			}
746 746
			return buf;
747 747
		}
748
				
748

  
749 749
		return null;
750 750
	}
751
	
751

  
752 752
	/**
753 753
	 * Lectura de una l�nea de datos.
754 754
	 * @param line
......
764 764
		while(y >= gdalBands[0].getRasterBandYSize())
765 765
			y--;
766 766

  
767
		if (x+w > gdalBands[0].getRasterBandXSize()) 
767
		if (x+w > gdalBands[0].getRasterBandXSize())
768 768
			w = gdalBands[0].getRasterBandXSize()-x;
769 769

  
770 770
		if(gdalBands[0].getRasterColorTable() != null) {
......
798 798

  
799 799
		return;
800 800
	}
801
	
801

  
802 802
	private List<ColorItem> gdalColorTable2ColorItems(GdalColorTable table) {
803 803
		try {
804 804
			List<ColorItem> colorItems = new ArrayList<ColorItem>();
......
821 821
		}
822 822
		return null;
823 823
	}
824
	
825
			
824

  
825

  
826 826
	/**
827 827
	 * Cuando se hace una petici�n de carga de buffer la extensi�n pedida puede
828 828
	 * estar ajustada a la extensi�n del raster o no estarlo. En caso de no
829 829
	 * estarlo los pixeles del buffer que caen fuera de la extensi�n del raster
830 830
	 * tendr�n valor de NoData. Esta funci�n calcula en que pixel del buffer hay
831 831
	 * que empezar a escribir en caso de que este sea mayor que los datos a leer.
832
	 * 
832
	 *
833 833
	 * @param dWorldTLX Posici�n X superior izquierda en coord reales
834 834
	 * @param dWorldTLY Posici�n Y superior izquierda en coord reales
835 835
	 * @param dWorldBRX Posici�n X inferior derecha en coord reales
......
837 837
	 * @param nWidth Ancho en pixeles del buffer
838 838
	 * @param nHeight Alto en pixeles del buffer
839 839
	 * @return desplazamiento dentro del buffer en X e Y
840
	 */ 
840
	 */
841 841
	private int[] calcStepBuffer(Extent dataExtent, int nWidth, int nHeight, int[] stpBuffer) {
842 842
		Extent imageExtent = getExtentWithoutRot();
843 843
		Extent ajustDataExtent = RasterLocator.getManager().getRasterUtils().calculateAdjustedView(dataExtent, imageExtent);
......
847 847
			Point2D p3 = worldToRasterWithoutRot(new Point2D.Double(dataExtent.minX(), dataExtent.maxY()));
848 848
			//    		Point2D p4 = worldToRasterWithoutRot(new Point2D.Double(dataExtent.maxX(), dataExtent.minY()));
849 849
			//Ese es el ancho y alto q tendr�a el buffer en caso de haberse ajustado
850
			int w = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX())); 
850
			int w = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX()));
851 851
			int h = (int)Math.abs(Math.floor(p1.getY()) - Math.ceil(p2.getY()));
852 852

  
853 853
			stpBuffer[0] = (int)(p1.getX() + (-p3.getX()));
854 854
			stpBuffer[1] = (int)(p1.getY() + (-p3.getY()));
855
			stpBuffer[2] = stpBuffer[0] + w; 
855
			stpBuffer[2] = stpBuffer[0] + w;
856 856
			stpBuffer[3] = stpBuffer[1] + h;
857 857
			return new int[]{w, h};
858 858
		}
859 859
		return new int[]{nWidth, nHeight};
860 860
	}
861
	
861

  
862 862
	/**
863 863
	 * Lee una ventana de datos sin resampleo a partir de coordenadas reales.
864 864
	 * @param buf Buffer donde se almacenan los datos
......
882 882
			tl.setLocation(tl.getX() - 1, tl.getY());
883 883
		else
884 884
			br.setLocation(br.getX() - 1, br.getY());
885
		
885

  
886 886
		if(tl.getY() > br.getY())
887 887
			tl.setLocation(tl.getX(), tl.getY() - 1);
888 888
		else
889 889
			br.setLocation(br.getX(), br.getY() - 1);
890
		
890

  
891 891
		if(gdalBands.length == 0)
892 892
			return;
893 893

  
......
905 905
				x  = 0;
906 906
			if(y < 0)
907 907
				y  = 0;
908
			readDataCachedBuffer(buf, bandList, new int[]{x, y, wh[0], wh[1]}, 
908
			readDataCachedBuffer(buf, bandList, new int[]{x, y, wh[0], wh[1]},
909 909
					wh[0], wh[1], 0, 0, stpBuffer, status);
910 910
			return;
911 911
		}
912 912

  
913
		readDataCachedBuffer(buf, bandList, new int[]{x, y, nWidth, nHeight}, 
913
		readDataCachedBuffer(buf, bandList, new int[]{x, y, nWidth, nHeight},
914 914
				nWidth, nHeight, 0, 0, stpBuffer, status);
915 915
	}
916
	
916

  
917 917
	public void readWindow(Buffer buf, BandList bandList, Extent ext, Rectangle adjustedWindow, TaskStatus status) throws GdalException, ProcessInterruptedException {
918 918
		setView(ext.getULX(), ext.getULY(), ext.getLRX(), ext.getLRY(), buf.getWidth(), buf.getHeight());
919 919

  
......
923 923
		selectGdalBands(getRasterCount());
924 924

  
925 925
		int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
926
		
926

  
927 927
		adjustedWindow = getAdjustedWindowInOverviewCoordinates(adjustedWindow);
928 928

  
929
		readDataCachedBuffer(buf, 
930
				bandList, 
931
				new int[]{(int)adjustedWindow.getX(), (int)adjustedWindow.getY(), (int)adjustedWindow.getWidth(), (int)adjustedWindow.getHeight()}, 
932
				buf.getWidth(), 
933
				buf.getHeight(), 
929
		readDataCachedBuffer(buf,
930
				bandList,
931
				new int[]{(int)adjustedWindow.getX(), (int)adjustedWindow.getY(), (int)adjustedWindow.getWidth(), (int)adjustedWindow.getHeight()},
932
				buf.getWidth(),
933
				buf.getHeight(),
934 934
				0, 0, stpBuffer, status);
935 935
	}
936
	
936

  
937 937
	/**
938 938
	 * Adjust the request rectangle to the overview size. The requests in Gdal have to be
939 939
	 * in the overview scale
......
947 947
		int y = (int) (((long)adjustedWindow.getY() * (long)overviewHeight) / (long)height);
948 948
		return new Rectangle(x, y, nWidth, nHeight);
949 949
	}
950
			
950

  
951 951
	/**
952 952
	 * Lee una ventana de datos con resampleo a partir de coordenadas reales. Este m�todo lee la
953 953
	 * ventana de una vez cargando los datos de un golpe en el buffer. Las coordenadas se solicitan
954 954
	 * en coordenadas del mundo real por lo que estas pueden caer en cualquier parte de un pixel.
955
	 * Esto se hace m�s evidente cuando supersampleamos en la petici�n, es decir el buffer de de 
955
	 * Esto se hace m�s evidente cuando supersampleamos en la petici�n, es decir el buffer de de
956 956
	 * mayor tama�o que el n�mero de pixels solicitado.
957
	 * 
958
	 * Para resolver esto escribiremos con la funci�n readRaster los datos sobre un buffer mayor 
959
	 * que el solicitado. Despu�s calcularemos el desplazamiento en pixels dentro de este buffer 
957
	 *
958
	 * Para resolver esto escribiremos con la funci�n readRaster los datos sobre un buffer mayor
959
	 * que el solicitado. Despu�s calcularemos el desplazamiento en pixels dentro de este buffer
960 960
	 * de mayor tama�o hasta llegar a la coordenada real donde comienza la petici�n real que ha
961
	 * hecho el usuario. Esto es as� porque cuando supersampleamos no queremos los pixeles del 
962
	 * raster de disco completos sino que en los bordes del buffer quedan cortados.  
963
	 *  
961
	 * hecho el usuario. Esto es as� porque cuando supersampleamos no queremos los pixeles del
962
	 * raster de disco completos sino que en los bordes del buffer quedan cortados.
963
	 *
964 964
	 * @param buf Buffer donde se almacenan los datos
965 965
	 * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
966 966
	 * @param dWorldTLX Posici�n X superior izquierda en coord reales
......
983 983
		lr.setLocation(lr.getX() < 0 ? 1 : lr.getX(), lr.getY() < 0 ? 1 : lr.getY());
984 984
		ul.setLocation(ul.getX() - 0.5, ul.getY() - 0.5);
985 985
		lr.setLocation(lr.getX() - 0.5, lr.getY() - 0.5);
986
		
986

  
987 987
		adjustPoints(ul, lr);
988
		
988

  
989 989
		if(gdalBands.length == 0)
990 990
			return;
991
		
991

  
992 992
		selectGdalBands(/*buf.getBandCount()*/getRasterCount());
993 993

  
994 994
		Rectangle requestWindow = new Rectangle(
995
				(int) Math.min(ul.getX(), lr.getX()), 
996
				(int) Math.min(ul.getY(), lr.getY()), 
997
				(int)nWidth, 
995
				(int) Math.min(ul.getX(), lr.getX()),
996
				(int) Math.min(ul.getY(), lr.getY()),
997
				(int)nWidth,
998 998
				(int)nHeight);
999 999

  
1000
		requestWindow = getAdjustedWindowInOverviewCoordinates(requestWindow); 
1000
		requestWindow = getAdjustedWindowInOverviewCoordinates(requestWindow);
1001 1001

  
1002 1002
		int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
1003 1003
		//Si el buffer no se ajusta al extent entonces calculamos en que posici�n comienza a escribirse dentro del buffer
......
1014 1014
			stpBuffer[3] = (int)((stpBuffer[3] * bufHeight) / requestWindow.getHeight());
1015 1015
			bufWidth = (int)Math.abs(stpBuffer[2] - stpBuffer[0]);
1016 1016
			bufHeight = (int)Math.abs(stpBuffer[3] - stpBuffer[1]);
1017
			readDataCachedBuffer(buf, bandList, 
1018
					new int[]{(int)requestWindow.getX(), (int)requestWindow.getY(), wh[0], wh[1]}, 
1017
			readDataCachedBuffer(buf, bandList,
1018
					new int[]{(int)requestWindow.getX(), (int)requestWindow.getY(), wh[0], wh[1]},
1019 1019
						bufWidth, bufHeight, 0, 0, stpBuffer, status);
1020 1020
			return;
1021 1021
		}
1022 1022

  
1023
		if ((requestWindow.getX() + requestWindow.getWidth()) > gdalBands[0].getRasterBandXSize()) 
1023
		if ((requestWindow.getX() + requestWindow.getWidth()) > gdalBands[0].getRasterBandXSize())
1024 1024
			requestWindow.setSize((int)(gdalBands[0].getRasterBandXSize() - requestWindow.getX()), (int)requestWindow.getHeight());
1025 1025

  
1026
		if ((requestWindow.getY() + requestWindow.getHeight()) > gdalBands[0].getRasterBandYSize()) 
1026
		if ((requestWindow.getY() + requestWindow.getHeight()) > gdalBands[0].getRasterBandYSize())
1027 1027
			requestWindow.setSize((int)requestWindow.getWidth(), (int)(gdalBands[0].getRasterBandYSize() - requestWindow.getY()));
1028 1028

  
1029
		readDataCachedBuffer(buf, bandList, 
1030
				new int[]{(int)requestWindow.getX(), (int)requestWindow.getY(), (int)requestWindow.getWidth(), (int)requestWindow.getHeight()}, 
1029
		readDataCachedBuffer(buf, bandList,
1030
				new int[]{(int)requestWindow.getX(), (int)requestWindow.getY(), (int)requestWindow.getWidth(), (int)requestWindow.getHeight()},
1031 1031
				bufWidth, bufHeight, 0, 0, stpBuffer, status);
1032 1032
	}
1033
	
1033

  
1034 1034
	private void adjustPoints(Point2D ul, Point2D lr) {
1035 1035
		double a = (ul.getX() - (int)ul.getX());
1036 1036
		double b = (ul.getY() - (int)ul.getY());
1037
		ul.setLocation(	(a > 0.95 || a < 0.05) ? Math.round(ul.getX()) : ul.getX(), 
1037
		ul.setLocation(	(a > 0.95 || a < 0.05) ? Math.round(ul.getX()) : ul.getX(),
1038 1038
						(b > 0.95 || b < 0.05) ? Math.round(ul.getY()) : ul.getY());
1039
		lr.setLocation(	(a > 0.95 || a < 0.05) ? Math.round(lr.getX()) : lr.getX(), 
1039
		lr.setLocation(	(a > 0.95 || a < 0.05) ? Math.round(lr.getX()) : lr.getX(),
1040 1040
						(b > 0.95 || b < 0.05) ? Math.round(lr.getY()) : lr.getY());
1041 1041
	}
1042 1042

  
......
1055 1055
	 */
1056 1056
	public void readWindow(Buffer buf, BandList bandList, int x, int y, int w, int h, TaskStatus status) throws GdalException, ProcessInterruptedException {
1057 1057
		gdalBands = new GdalRasterBand[getRasterCount()];
1058
		
1058

  
1059 1059
		if(buf.getWidth() == w && buf.getHeight() == h)
1060 1060
			isSupersampling = false;
1061
		
1061

  
1062 1062
		if(gdalBands.length == 0)
1063 1063
			return;
1064
		
1064

  
1065 1065
		// Selecciona las bandas
1066 1066
		gdalBands[0] = getRasterBand(1);
1067
		
1067

  
1068 1068
		for(int iBand = 1; iBand < gdalBands.length; iBand++)
1069 1069
			gdalBands[iBand] = getRasterBand(iBand + 1);
1070
		
1070

  
1071 1071
		assignDataTypeFromGdalRasterBands(gdalBands);
1072
		
1072

  
1073 1073
		int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
1074 1074
		readDataCachedBuffer(buf, bandList, new int[]{x, y, w, h}, buf.getWidth(), buf.getHeight(), 0, 0, stpBuffer, status);
1075 1075
	}
1076
	
1076

  
1077 1077
	/**
1078 1078
	 * Asigna el tipo de datos de las bandas a partir de una lista de GdalRasterBands
1079 1079
	 * @param gdalBands
......
1087 1087
		}
1088 1088
		setDataType(dt);
1089 1089
	}
1090
	
1090

  
1091 1091
	/**
1092 1092
	 * Lee una ventana de datos. Esta funci?n es usuada por
1093 1093
	 * readWindow para coordenadas reales y readWindow en coordenadas pixel. Esta es una versi?n de readData pero
......
1104 1104
	 * </UL>
1105 1105
	 * @param bufWidth Ancho del buffer de la imagen de entrada. Si no coincide con inputWindow[2] el propio gdal resamplea
1106 1106
	 * @param bufHeight Alto del buffer de la imagen de entrada. Si no coincide con inputWindow[3] el propio gdal resamplea
1107
	 * @param stepX Desplazamiento en p?xeles en X a partir de la posici?n x. Este desplazamiento es util cuando hay un 
1107
	 * @param stepX Desplazamiento en p?xeles en X a partir de la posici?n x. Este desplazamiento es util cuando hay un
1108 1108
	 * supersampleo ya que puede ser que de los pixeles que est?n en el borde izquierdo de la petici?n solo queramos una
1109
	 * parte de ellos. 
1110
	 * @param stepY Desplazamiento en p?xeles en Y a partir de la posici?n y. Este desplazamiento es util cuando hay un 
1109
	 * parte de ellos.
1110
	 * @param stepY Desplazamiento en p?xeles en Y a partir de la posici?n y. Este desplazamiento es util cuando hay un
1111 1111
	 * supersampleo ya que puede ser que de los p?xeles que est?n en el borde superior de la petici?n solo queramos una
1112 1112
	 * parte de ellos.
1113
	 * @param stepBuffer El buffer puede empezar a escribirse a partir de un pixel determinado y acabar de escribir antes 
1113
	 * @param stepBuffer El buffer puede empezar a escribirse a partir de un pixel determinado y acabar de escribir antes
1114 1114
	 * de fin de buffer. Este par?metro indica el desplazamiento desde el inicio del buffer y la posici?n final.
1115 1115
	 * <UL>
1116 1116
	 * <LI>stepBuffer[0]:Desplazamiento en X desde el inicio</LI>
......
1120 1120
	 * </UL>
1121 1121
	 * @throws GdalException
1122 1122
	 */
1123
	private void readDataCachedBuffer(Buffer buf, 
1124
			BandList bandList, 
1125
			int[] inputWindow, 
1126
			int bufWidth, 
1127
			int bufHeight, 
1128
			int stpX, 
1129
			int stpY, 
1123
	private void readDataCachedBuffer(Buffer buf,
1124
			BandList bandList,
1125
			int[] inputWindow,
1126
			int bufWidth,
1127
			int bufHeight,
1128
			int stpX,
1129
			int stpY,
1130 1130
			int[] stepBuffer,
1131 1131
			TaskStatus status) throws GdalException, ProcessInterruptedException {
1132 1132
		if(buf.isCached()) {
......
1142 1142
				if(lastblock > 0 && i == (nBlocks - 1)) {
1143 1143
					int[] newStepBuffer = new int[]{0, initYBuffer, stepBuffer[2], initYBuffer + lastblock};
1144 1144
					int[] newWindow = new int[]{inputWindow[0], initYSrc, inputWindow[2], lastBlockYSrc};
1145
					readData(buf, 
1146
							bandList, 
1147
							newWindow, 
1145
					readData(buf,
1146
							bandList,
1147
							newWindow,
1148 1148
							bufWidth, lastblock, 0, 0, newStepBuffer);
1149 1149
				} else {
1150 1150
					int[] newStepBuffer = new int[]{0, initYBuffer, stepBuffer[2], initYBuffer + buf.getBlockHeight()};
1151 1151
					int[] newWindow = new int[]{inputWindow[0], initYSrc, inputWindow[2], stepYSrc};
1152
					readData(buf, 
1153
							bandList, 
1154
							newWindow, 
1152
					readData(buf,
1153
							bandList,
1154
							newWindow,
1155 1155
							bufWidth, buf.getBlockHeight(), 0, 0, newStepBuffer);
1156 1156
					initYSrc += stepYSrc;
1157 1157
					initYBuffer += buf.getBlockHeight();
......
1161 1161
			readData(buf, bandList, inputWindow, bufWidth, bufHeight, 0, 0, stepBuffer);
1162 1162
		}
1163 1163
	}
1164
		
1164

  
1165 1165
	/**
1166 1166
	 * Lee una ventana de datos. Esta funci?n es usuada por
1167
	 * readWindow para coordenadas reales y readWindow en coordenadas pixel. 
1167
	 * readWindow para coordenadas reales y readWindow en coordenadas pixel.
1168 1168
	 * @param buf Buffer donde se almacenan los datos
1169 1169
	 * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
1170 1170
	 * @param inputWindow
......
1176 1176
	 * </UL>
1177 1177
	 * @param bufWidth Ancho del buffer de la imagen de entrada. Si no coincide con inputWindow[2] el propio gdal resamplea
1178 1178
	 * @param bufHeight Alto del buffer de la imagen de entrada. Si no coincide con inputWindow[3] el propio gdal resamplea
1179
	 * @param stepX Desplazamiento en p?xeles en X a partir de la posici?n x. Este desplazamiento es util cuando hay un 
1179
	 * @param stepX Desplazamiento en p?xeles en X a partir de la posici?n x. Este desplazamiento es util cuando hay un
1180 1180
	 * supersampleo ya que puede ser que de los pixeles que est?n en el borde izquierdo de la petici?n solo queramos una
1181
	 * parte de ellos. 
1182
	 * @param stepY Desplazamiento en p?xeles en Y a partir de la posici?n y. Este desplazamiento es util cuando hay un 
1181
	 * parte de ellos.
1182
	 * @param stepY Desplazamiento en p?xeles en Y a partir de la posici?n y. Este desplazamiento es util cuando hay un
1183 1183
	 * supersampleo ya que puede ser que de los p?xeles que est?n en el borde superior de la petici?n solo queramos una
1184 1184
	 * parte de ellos.
1185
	 * @param stepBuffer El buffer puede empezar a escribirse a partir de un pixel determinado y acabar de escribir antes 
1185
	 * @param stepBuffer El buffer puede empezar a escribirse a partir de un pixel determinado y acabar de escribir antes
1186 1186
	 * de fin de buffer. Este par?metro indica el desplazamiento desde el inicio del buffer y la posici?n final.
1187 1187
	 * <UL>
1188 1188
	 * <LI>stepBuffer[0]:Desplazamiento en X desde el inicio</LI>
......
1192 1192
	 * </UL>
1193 1193
	 * @throws GdalException
1194 1194
	 */
1195
	private void readData(Buffer buf, 
1196
			BandList bandList, 
1197
			int[] inputWindow, 
1198
			int bufWidth, 
1199
			int bufHeight, 
1200
			int stpX, 
1201
			int stpY, 
1195
	private void readData(Buffer buf,
1196
			BandList bandList,
1197
			int[] inputWindow,
1198
			int bufWidth,
1199
			int bufHeight,
1200
			int stpX,
1201
			int stpY,
1202 1202
			int[] stepBuffer) throws GdalException, ProcessInterruptedException {
1203
		
1204
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + ""); 
1205
		FileUtils fUtil = RasterLocator.getManager().getFileUtils(); 
1206
			
1203

  
1204
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
1205
		FileUtils fUtil = RasterLocator.getManager().getFileUtils();
1206

  
1207 1207
		GdalBuffer gdalBuf = null;
1208 1208
		for(int iBand = 0; iBand < gdalBands.length; iBand++) {
1209 1209
			int[] drawableBands = bandList.getBufferBandToDraw(fUtil.getFormatedRasterFileName(fileName), iBand);
1210 1210
			if(drawableBands == null || (drawableBands.length == 1 && drawableBands[0] == -1))
1211
				continue;	
1211
				continue;
1212 1212
			int init = (int)((bufWidth * stpY) + stpX); //Pos inicial. Desplazamos stpX pixels hacia la derecha y bajamos stpY lineas
1213 1213
			int pos = init;
1214
			gdalBuf = gdalBands[iBand].readRaster(	inputWindow[0], 
1215
													inputWindow[1], 
1216
													inputWindow[2], 
1217
													inputWindow[3], 
1218
													bufWidth, 
1219
													bufHeight, 
1214
			gdalBuf = gdalBands[iBand].readRaster(	inputWindow[0],
1215
													inputWindow[1],
1216
													inputWindow[2],
1217
													inputWindow[3],
1218
													bufWidth,
1219
													bufHeight,
1220 1220
													dataType[iBand]);
1221 1221
			int lineInputWindow = 0;
1222 1222
			if(dataType[iBand] == Gdal.GDT_Byte) {
1223 1223
				for (int line = stepBuffer[1]; line < stepBuffer[3]; line++) {
1224 1224
					pos = (int)((bufWidth * (lineInputWindow - stepBuffer[0])) + init);
1225 1225
					for (int col = stepBuffer[0]; col < stepBuffer[2]; col ++) {
1226
						for (int i = 0; i < drawableBands.length; i++) 
1226
						for (int i = 0; i < drawableBands.length; i++)
1227 1227
							buf.setElem(line, col, drawableBands[i], gdalBuf.buffByte[pos]);
1228 1228
						pos ++;
1229 1229
					}
......
1287 1287
			}
1288 1288
		}
1289 1289
	}
1290
	
1290

  
1291 1291
	/**
1292 1292
	 * Lee una ventana de datos sin resampleo a partir de coordenadas en pixeles. Esta funci�n es usuada por
1293
	 * readWindow para coordenadas reales y readWindow en coordenadas pixel. 
1293
	 * readWindow para coordenadas reales y readWindow en coordenadas pixel.
1294 1294
	 * @param buf Buffer donde se almacenan los datos
1295 1295
	 * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
1296 1296
	 * @param x Posici�n X en pixeles
......
1304 1304
		GdalBuffer gdalBuf = null;
1305 1305
		int rasterBufLine;
1306 1306
		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
1307
		FileUtils fUtil = RasterLocator.getManager().getFileUtils(); 
1308
		
1307
		FileUtils fUtil = RasterLocator.getManager().getFileUtils();
1308

  
1309 1309
		for(int iBand = 0; iBand < gdalBands.length; iBand++) {
1310 1310
			int[] drawableBands = bandList.getBufferBandToDraw(fUtil.getFormatedRasterFileName(fileName), iBand);
1311 1311
			if(drawableBands == null || (drawableBands.length == 1 && drawableBands[0] == -1))
1312
				continue;	
1312
				continue;
1313 1313
			if(dataType[iBand] == Gdal.GDT_Byte) {
1314 1314
				for (int line = y; line < yMax; line++) {
1315 1315
					gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
......
1363 1363
			}
1364 1364
		}
1365 1365
	}
1366
	
1366

  
1367 1367
	/**
1368 1368
	 * Obtiene el valor de un pixel determinado por las coordenadas x e y que se pasan
1369 1369
	 * por par�metro
......
1399 1399
			return null;
1400 1400
		}
1401 1401
	}
1402
	
1402

  
1403 1403
	public int getBlockSize(){
1404 1404
		return this.getBlockSize();
1405 1405
	}
......
1411 1411
	public AffineTransform getOwnTransformation() {
1412 1412
		return ownTransformation;
1413 1413
	}
1414
		
1414

  
1415 1415
	/**
1416 1416
	 * Calcula el extent en coordenadas del mundo real sin rotaci�n. Solo coordenadas y tama�o de pixel
1417 1417
	 * @return Extent
1418 1418
	 */
1419 1419
	public Extent getExtentWithoutRot() {
1420
		AffineTransform at = new AffineTransform(	externalTransformation.getScaleX(), 0, 
1421
													0, externalTransformation.getScaleY(), 
1420
		AffineTransform at = new AffineTransform(	externalTransformation.getScaleX(), 0,
1421
													0, externalTransformation.getScaleY(),
1422 1422
													externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
1423 1423
		Point2D p1 = new Point2D.Double(0, 0);
1424 1424
		Point2D p2 = new Point2D.Double(width, height);
......
1426 1426
		at.transform(p2, p2);
1427 1427
		return new ExtentImpl(p1, p2);
1428 1428
	}
1429
	
1429

  
1430 1430
	/**
1431 1431
	 * Asigna una transformaci�n que es aplicada sobre la que ya tiene el propio fichero
1432 1432
	 * @param t
......
1442 1442
	public String getGdalShortName() {
1443 1443
		return shortName;
1444 1444
	}
1445
	
1445

  
1446 1446
	public void dispose() {
1447 1447
		open = false;
1448 1448
		try {
......
1454 1454
		} catch (Throwable e) {
1455 1455
		}
1456 1456
	}
1457
	
1457

  
1458 1458
	protected void finalize() {
1459 1459
		fileTransparency       = null;
1460 1460
		palette                = null;
......
1469 1469
		version                = null;
1470 1470
		dataType               = null;
1471 1471
		metadata                = null;
1472
		
1472

  
1473 1473
		if(gdalBands != null) {
1474 1474
			for (int i = 0; i < gdalBands.length; i++) {
1475 1475
				gdalBands[i] = null;
......
1478 1478
		}
1479 1479
		this.finalize();
1480 1480
	}
1481
		
1481

  
1482 1482
}
1483 1483

  
1484 1484

  

Also available in: Unified diff