Is there a way to detect HBL and or VBL on an Apple II, and if yes, how it's done?
Hardware management on the Apple II is done by accessing a set of 'Softswitches', addresses when accessed set certain modes. For the screen there are several locations:
$C050 Select Graphics $C051 Select Text $C052 Full Screen (Graphics) $C053 Mixed Screen $C054 Page 1 $C055 Page 2 $C056 Select Low Res $C057 Select Highres
Usually they are accessed with a read (
LD*)to 'switch' the desired function on, with the value read considered as random. Except, it isn't. When reading any of these locations, the returned value is what has been read from screen RAM during video access, right before the read cycle (*1). The value is not delivered by purpose, but due being still 'present' on data lines.
The mechanic now needs a known value (but better sequence values) to be detected to synchronise. This can be on screen, as well as during the off screen (HBL) portion. The later allows the detection to run 'invisible'. Once found, cycle counting like on an Atari VCS can start to keep track of the beam.
Don Lancaster's (*2,*3) 1985 Book Enhancing Your Apple II and IIe Volume 2 calls the mechanic 'Vapor Lock', describing usage in great detail (p.193ff).
Tommy points in a comment to a nice demo game using these effects: Rasterbars in Space. The same author also did a real nifty demo spliting between low and highres not only horizontal but vertical as well: Megademo.
*1 - That means if accessed via a 4 cycle operation like
LDA $C051, it will be the value the video logic accessed between the third and fourth cycle.
*2 - As fadden reminded here.
*3 - Yes, that Don Lancaster whose 1976 'TV Typewriter Cookbook' and 1978 'Cheap Video Cookbook' eventually influenced many early developers, all the way from Wozniak to Sinclair. His website 'Guru's Lair' contains not only PDFs of many of his books, but as well still new updates worth reading.