;;;COPYRIGHT BY Matteo Trasi, ABC Corsi, Via A. Binda 20, Milano, Italy
;;;feel free to use this code as you want, you are free to modify it or use in your
;;;projects, even commercial, but you are not authorized to put your copyright over this code!
;;;If you use this in your commercial or copyrighted projects you must notice in your
;;;license or copyright statement that some part of the code (this) is free and not your own.
;;;You can release this as a piece of free software (everybody knows wht is free software!)

(vl-load-com)
(defun AABC_RasterManager_WordFile
       (filename / c1 c2 ext extW filenameW)
  (setq
	ext (vl-filename-extension filename)
	extW ".w"
	filenameW filename
  )
  (if ext
    (progn
      (setq ext (strcase ext t))
      (setq filenameW
	     (substr filename 1 (- (strlen filename) (strlen ext)))
      )
      (setq c1 (substr ext 1 2))
      (setq c2 (substr ext (strlen ext) 1))
      (setq extW (strcat c1 c2 "w"))
    )
  )
  (strcat filenameW extW)
)

(defun AABC_RASTER_FOUND_PATH (vlaimg / raw-path dwg-dir full-path)
  (setq raw-path (vla-get-ImageFile vlaimg))
  (setq dwg-dir (getvar "DWGPREFIX"))
  
  (cond
    ;; 1. Se il percorso salvato è già assoluto ed esiste
    ((findfile raw-path)
     (setq full-path (findfile raw-path)))
    
    ;; 2. Se è un percorso relativo (es. ".\cartella\img.jpg" o "..\img.jpg")
    ;; Lo unisce alla cartella del DWG e usa findfile per risolverlo e normalizzarlo
    ((findfile (strcat dwg-dir raw-path))
     (setq full-path (findfile (strcat dwg-dir raw-path))))
    
    ;; 3. Se è "Nessun percorso" o AutoCAD lo trova nei percorsi di supporto/cartella DWG
    ((findfile (strcat (vl-filename-base raw-path) (vl-filename-extension raw-path)))
     (setq full-path (findfile (strcat (vl-filename-base raw-path) (vl-filename-extension raw-path)))))
    
    ;; 4. Altrimenti il file non è stato trovato (risulta "Non trovato" nei Riferimenti esterni)
    (t (setq full-path nil))
  )
  full-path
)

(defun c:AABC_RasterManagerInsert
				  (/	    file     fileW    lines
				   values   v1	     v2	      v3
				   v4	    v5	     v6	      ang
				   rot	    x0	     y0	      scaleX
				   scaleY   pixelX   pixelY
				   ReadWorldFile     Browse   mspace
				   theraster
				  )
  (vl-load-com)
  (defun ReadWorldFile (filename / file line result)
    (setq file (open filename "r"))
    (while (setq line (read-line file))
      (setq result (append result (list (vl-string-trim " " line))))
    )
    (close file)
    result
  )
  (defun Browse	(/ LastFolder filename)
    (setq LastFolder (vl-bb-ref 'AABC_RasterManagerLastFolder))
    (if	(not LastFolder)
      (setq LastFolder "")
    )
    (setq filename (getfiled "select Image" LastFolder "" 4))
    (if	filename
      (vl-bb-set 'AABC_RasterManagerLastFolder
		 (strcat (vl-filename-directory filename) "\\")
      )
    )
    filename
  )
  (defun mspace	()
    (vla-get-modelspace
      (vla-get-activedocument (vlax-get-acad-object))
    )
  )

  (setq file (Browse))
  (if file
    (progn
      (setq fileW (AABC_RasterManager_WordFile file))
      (princ (strcat "\nProcessing " fileW))
      (if (not (vl-file-systime fileW))
	(princ
	  (strcat "\n***Error: World file " fileW " not found!")
	)
	(progn
	  (princ (strcat "\nReading " fileW))
	  (setq lines (ReadWorldFile fileW))
	  (setq values (mapcar 'atof lines))
	  (if (>= (length values) 6)
	    (progn
	      (setq v1 (nth 0 values)
		    v2 (nth 1 values)
		    v3 (nth 2 values)
		    v4 (nth 3 values)
		    v5 (nth 4 values)
		    v6 (nth 5 values)
	      )
	      (if (= v4 0)
		(setq ang (/ pi 2.0))
		(setq ang (atan (/ v3 v4)))
	      )
	      (if (<= v1 0)
		(if (not (and (= v1 0) (> v2 0)))
		  (setq ang (+ ang pi))
		)
	      )
	      (setq rot (- (* 2.0 pi) ang))
	      (setq scaleX (sqrt (+ (* v1 v1) (* v2 v2))))
	      (setq scaleY (sqrt (+ (* v3 v3) (* v4 v4))))
	      (setq theraster (vla-AddRaster
				(mspace)
				file
				(vlax-3d-point '(0.0 0.0 0.0))
				1.0
				rot
			      )
	      )
	      (vla-put-scalefactor theraster (/ scaleY scaleX))
	      ;;disattiva scalature automatiche
	      (setq pixelX (vla-get-width theraster))
	      (setq pixelY (vla-get-height theraster))
	      (setq x0 (- v5 (* (Sin ang) scaleY pixelY)))
	      (setq y0 (- v6 (* (Cos ang) scaleY pixelY)))
	      ;;centra il pixel
	      (setq x0 (- x0
			  (+ (* (/ scaleX 2.0) (cos rot))
			     (* (/ scaleY 2.0) (sin rot))
			  )
		       )
	      )
	      (setq y0 (+ y0
			  (+ (* (/ (- 0.0 scaleX) 2.0) (sin rot))
			     (* (/ scaleY 2.0) (cos rot))
			  )
		       )
	      )
	      (vlax-invoke
		theraster
		'move
		'(0.0 0.0 0.0)
		(list x0 y0 0.0)
	      )
	      (vla-put-imagewidth
		theraster
		(* scaleX (vla-get-width theraster))
	      )
	      (vla-put-imageheight
		theraster
		(* scaleY (vla-get-height theraster))
	      )
	    )
	    (princ "\n**error** World file not correctly formatted!")
	  )
	)
      )
    )
  )
  (princ)
)


(defun c:AABC_RasterManagerWriteWorldFile (/	  ent	 img	file
					   fileW  img	 pixelx	pixely
					   scaleX scaleY orig	x0
					   y0	  insX	 insY	ang
					   rot	  v1	 v2	v3
					   v4	  v5	 v6	tan
					   data
					  )
  (defun tan (a) (/ (sin a) (cos a)))
  (defun WriteWorldFile	(filename lst / file)
    (if	(setq file (open filename "w"))
      (progn
	  (princ (strcat "\nWriting info into " filename "\n"))
	(foreach x lst
	  (write-line x file)
	)
	(close file)
	filename
      )
      nil
    )
  )
;;;MAIN
  (if
    (and
      (setq ent (car (entsel "\nSelect image: ")))
      (setq img (vlax-ename->vla-object ent))
      (= (vla-get-ObjectName img) "AcDbRasterImage")
    )
     (progn
       (setq pixelx (vla-get-width img))
       (setq pixely (vla-get-height img))
       (setq scaleX (/ (vla-get-imagewidth img) pixelX))
       (setq scaleY (/ (vla-get-imageheight img) pixelY))
       (setq orig (vlax-get img 'Origin))
       (setq x0 (nth 0 orig))
       (setq y0 (nth 1 orig))
       (setq rot (vla-get-rotation img))
       (setq h (vla-get-imageheight img))
       (setq w (vla-get-imagewidth img))
       (setq insX (+ x0
		     (* (- 0.0 h) (sin rot))
		     (* (/ scaleX 2.0) (cos rot))
		     (* (/ scaley 2.0) (sin rot))
		  )
       )
       (setq insY (+ y0
		     (* h (cos rot))
		     (* (/ scaleX 2.0) (sin rot))
		     (* (/ (- 0.0 scaleY) 2) (cos rot))
		  )
       )
       (setq ang (- rot (* 2.0 pi)))
       (if (> (cos rot) 0)
	 (progn
	   (setq ang (- rot (* 2.0 pi)))
	   (setq v1
		  (sqrt	(/ (* scaleX scaleX) (+ 1 (* (tan ang) (tan ang))))
		  )
	   )
	   (setq v2 (* v1 (tan ang)))
	   (setq v4
		  (- 0.0
		     (sqrt
		       (/ (* scaleY scaleY) (+ 1 (* (tan ang) (tan ang))))
		     )
		  )
	   )
	   (setq v3 (- 0.0 (* v4 (tan ang))))
	   (setq v5 insX)
	   (setq v6 insY)
	 )
	 (progn
	   (setq ang (- rot (* 2.0 pi)))
	   (setq v1
		  (- 0.0
		     (sqrt
		       (/ (* scaleX scaleX) (+ 1 (* (tan ang) (tan ang))))
		     )
		  )
	   )
	   (setq v2 (* v1 (tan ang)))
	   (setq v4
		  (sqrt	(/ (* scaleY scaleY) (+ 1 (* (tan ang) (tan ang))))
		  )
	   )
	   (setq v3 (- 0.0 (* v4 (tan ang))))
	   (setq v5 insX)
	   (setq v6 insY)
	 )
       )
       (setq file (AABC_RASTER_FOUND_PATH img))
       (setq fileW (AABC_RasterManager_WordFile file))
       (setq data (list	(rtos v1 2 32)
			(rtos v2 2 32)
			(rtos v3 2 32)
			(rtos v4 2 32)
			(rtos v5 2 32)
			(rtos v6 2 32)
		  )
       )
       (if (not (WriteWorldFile fileW data))
	 (alert (strcat "Error writing " fileW))
       )
     )
  )
  (princ)
)
(defun C:ABC-IMG-READ()(C:AABC_RasterManagerInsert))
(defun C:ABC-IMG-WRITE()(C:AABC_RasterManagerWriteWorldFile))
(princ "\nUtility ready. Type:\nABC-IMG-WRITE (to write a world file from a loaded image)\nABC-IMG-READ  (to insert a worldfile-georeferenced image)")
(princ)