		.386p
		ASSUME	CS:CODE

		PUBLIC	ClipPolyg3D,ClipLine3D


CLIP		MACRO	CPP
;Y=(X-X1)(Y2-Y1)/(X2-X1)+Y1
		SUB	EDX,EBX		;EDX=Y2-Y1
		SUB	ECX,EAX		;ECX=X2-X1
		SUB	EAX,CPP		;EAX=(X1-X)*-1
		NEG	EAX		;   = X-X1
		IMUL	EDX		;EAX:EDX=(X-X1)(Y2-Y1)
		IDIV	ECX		;EAX=(X-X1)(Y2-Y1)/(X2-X1)
		ADD	EAX,EBX		;EAX=(X-X1)(Y2-Y1)/(X2-X1)+Y1
		ENDM



CODE		SEGMENT
		ALIGN	4
ClipPolyg3D	PROC
#CPZ		EQU	ESP+48
#SRCPTR		EQU	ESP+44
#DSTPTR		EQU	ESP+40
#RETADR		EQU	ESP+36
#EBP		EQU	ESP+32
#ESI		EQU	ESP+28
#EDI		EQU	ESP+24
#EBX		EQU	ESP+20
#ESPOFS		EQU	20
#NPOINTSRC	EQU	ESP+16
#NPOINTDST	EQU	ESP+12
#X1		EQU	ESP+8
#Y1		EQU	ESP+4
#Z1		EQU	ESP

		PUSH	EBP
		PUSH	ESI
		PUSH	EDI
		PUSH	EBX
		SUB	ESP,#ESPOFS

		MOV	ESI,[#SRCPTR]
		MOV	EDI,[#DSTPTR]

		MOV	ECX,[ESI]
		MOV	[#NPOINTSRC],ECX
		MOV	[#NPOINTDST],DWORD PTR 0

		LEA	ESI,[ESI+4]
		LEA	EDI,[EDI+4]

		DEC	ECX
		LEA	ECX,[ECX+ECX*2]
		MOV	EAX,[ESI+ECX*4]
		MOV	[#X1],EAX
		MOV	EAX,[ESI+ECX*4+4]
		MOV	[#Y1],EAX
		MOV	EAX,[ESI+ECX*4+8]
		MOV	[#Z1],EAX

#LOOP0:		MOV	EAX,[#Z1]
		MOV	ECX,[ESI+8]
		CMP	EAX,[#CPZ]
		SETGE	BL
		CMP	ECX,[#CPZ]
		SETGE	BH
		XOR	BL,BH
		JE	#X2append

		MOV	EBX,[#X1]
		MOV	EDX,[ESI]
		CLIP	[#CPZ]
		MOV	[EDI],EAX

		MOV	EAX,[#Z1]
		MOV	EBX,[#Y1]
		MOV	ECX,[ESI+8]
		MOV	EDX,[ESI+4]
		CLIP	[#CPZ]
		MOV	[EDI+4],EAX

		MOV	EAX,[#CPZ]
		MOV	[EDI+8],EAX
		ADD	EDI,12
		INC	DWORD PTR [#NPOINTDST]

#X2append:	MOV	ECX,[ESI+8]
		CMP	ECX,[#CPZ]
		JL	#LOOP0OUT
		MOV	EAX,[ESI]
		MOV	EBX,[ESI+4]
		MOV	[EDI],EAX
		MOV	[EDI+4],EBX
		MOV	[EDI+8],ECX
		ADD	EDI,12
		INC	DWORD PTR [#NPOINTDST]

#LOOP0OUT:	MOV	EAX,[ESI]
		MOV	EBX,[ESI+4]
		MOV	ECX,[ESI+8]
		MOV	[#X1],EAX
		MOV	[#Y1],EBX
		MOV	[#Z1],ECX
		ADD	ESI,12
		DEC	DWORD PTR [#NPOINTSRC]
		JNE	#LOOP0

		MOV	EAX,[#NPOINTDST]
		MOV	EDI,[#DSTPTR]
		MOV	[EDI],EAX	;EAX:shouldn't be changed

		ADD	ESP,#ESPOFS
		POP	EBX
		POP	EDI
		POP	ESI
		POP	EBP
		RET			;return npointdst;
ClipPolyg3D	ENDP


		ALIGN	4
ClipLine3D	PROC
#CPZ		EQU	ESP+28
#SRCPTR		EQU	ESP+24
#DSTPTR		EQU	ESP+20
#RETADR		EQU	ESP+16
#EBP		EQU	ESP+12
#ESI		EQU	ESP+8
#EDI		EQU	ESP+4
#EBX		EQU	ESP

		PUSH	EBP
		PUSH	ESI
		PUSH	EDI
		PUSH	EBX

		CLD
		MOV	ESI,[#SRCPTR]
		MOV	EDI,[#DSTPTR]
		MOV	ECX,6
		REP	MOVSD
		MOV	ESI,[#SRCPTR]
		MOV	EDI,[#DSTPTR]

		MOV	EAX,[ESI+ 8   ]
		MOV	ECX,[ESI+ 8+12]
		CMP	EAX,[#CPZ]
		SETG	BL
		CMP	ECX,[#CPZ]
		SETG	BH
		TEST	BH,BL
		JNE	#BothIsGreater
		OR	BH,BL
		JE	#BothIsSmaller

		MOVZX	EBX,BL
		LEA	EBX,[EBX+EBX*2]
		LEA	EDI,[EDI+EBX*4]

		MOV	EBX,[ESI+0   ]
		MOV	EDX,[ESI+0+12]
		CLIP	[#CPZ]
		MOV	[EDI],EAX

		MOV	EAX,[ESI+8]
		MOV	EBX,[ESI+4]
		MOV	ECX,[ESI+8+12]
		MOV	EDX,[ESI+4+12]
		CLIP	[#CPZ]
		MOV	[EDI+4],EAX

		MOV	EAX,[#CPZ]
		MOV	[EDI+8],EAX

		POP	EBX
		POP	EDI
		POP	ESI
		POP	EBP
		SUB	EAX,EAX
		RET

#BothIsGreater:	POP	EBX
		POP	EDI
		POP	ESI
		POP	EBP
		SUB	EAX,EAX
		RET


#BothIsSmaller:	POP	EBX
		POP	EDI
		POP	ESI
		POP	EBP
		MOV	EAX,1
		RET
ClipLine3D	ENDP
CODE		ENDS
		END
