forum.boolean.name

forum.boolean.name (http://forum.boolean.name/index.php)
-   Blitz3D (http://forum.boolean.name/forumdisplay.php?f=45)
-   -   Вопрос-Ответ (для новичков) (http://forum.boolean.name/showthread.php?t=7886)

Ganociy 07.03.2011 19:57

Ответ: Вопрос-Ответ (для новичков)
 
тут где-то на форуме была функция DeparentAllChilds, я её не нашёл. Кто-нибудь может подсказать где на булке искать её?

moka 07.03.2011 20:06

Ответ: Вопрос-Ответ (для новичков)
 
А что поиск по форуму не работает вообще?
Я забил запрос "DeparentAllChilds", сразу же в третьей ссылке нашёл.

БЛИН! ДА ЧТО ЭТО С ЛЮДЬМИ?!..
Вообще нихера не могут, где блин пылкость, где интузиазм, побуждающий на ДЕЙСТВИЯ! А не просто желание результата, в состоянии бездействия, паразиты блин!

Ganociy 07.03.2011 20:30

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от MoKa (Сообщение 181755)
А что поиск по форуму не работает вообще?
Я забил запрос "DeparentAllChilds", сразу же в третьей ссылке нашёл.

БЛИН! ДА ЧТО ЭТО С ЛЮДЬМИ?!..
Вообще нихера не могут, где блин пылкость, где интузиазм, побуждающий на ДЕЙСТВИЯ! А не просто желание результата, в состоянии бездействия, паразиты блин!

Значить я неправильно вводил в поиске символы

moka 07.03.2011 22:20

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от Ganociy (Сообщение 181758)
Значить я неправильно вводил в поиске символы

Я тупо копипастнул из твоего поста..
В любом случае, гугл по запросу, даже ошибками выдаёт ссылку на булку если вписать приставку site:forum.boolean.name

QuBe 08.03.2011 19:56

Ответ: Вопрос-Ответ (для новичков)
 
Можно сделать коллизию для плоскости? (Floor=CreatePlane)

RBK 08.03.2011 21:29

Ответ: Вопрос-Ответ (для новичков)
 
Можно. Делай коллизию с полигоном.

DeeJex 09.03.2011 03:16

Ответ: Вопрос-Ответ (для новичков)
 

Hint: Стандартную систему коллизий использовать не желательно. Гораздо лучше прикрутить физикс. Главное уметь им правильно пользоваться.

RegIon 13.03.2011 12:51

Ответ: Вопрос-Ответ (для новичков)
 
Код:

Graphics3D 640,480,16,2
SetBuffer BackBuffer()
cam=CreateCamera()
Light=CreateLight()
PositionEntity cam,0,5,-10
TurnEntity cam,20,0,0

phWorldCreate(1,"")
;phMatSetDefFriction(1,0.9)
phMatSetDefElasticity(0.0)
Plan=CreatePlane()
EntityColor plan,90,182,211

mat_cub=phMatCreate()
cub=CreateCube()
cub_=phBodyCreateBox(2,2,2,4)
phBodySetEntity cub_,cub
phBodySetMat(cub_,mat_cub)

mat_cub2=phMatCreate()
cub2=CreateCube()
cub2_=phBodyCreateBox(2,2,2,1)
phBodySetEntity cub2_,cub2
phBodySetDamping cub_,.5,1
phBodySetMat(cub_,mat_cub)

phMatSetFriction mat_cub,mat_cub2,1,.9
Repeat
UpdateChar(cub_)
If KeyHit(57) phBodySetPos cub2_,Rnd(-2,2),10,Rnd(-2,2)




phWorldStep(100)
  UpdateWorld
  RenderWorld
Flip

Until KeyHit(1)

End

Function UpdateChar(body%,maxvel#=5)
    phBodySetOmega body,-phBodyGetOmegaX(body),-phBodyGetOmegaY(body),-phBodyGetOmegaZ(body);чтоб не крутился
    ;проверяем, есть ли под ногами земля (или хоть что-то)
    x# = phBodyGetX(body)
    y# = phBodyGetY(body)
    z# = phBodyGetZ(body)

    If (phRayCast(x,y,z,x,y-5.1,z));на земле
        ;желаемая скорость
        TFormVector (KeyDown(32)-KeyDown(30)),0,(KeyDown(17)-KeyDown(31)),cub,0
        vx# = TFormedX()*maxvel
        vy# = TFormedY()*maxvel
        vz# = TFormedZ()*maxvel
        ;текущая скорость
        vxcur# = phBodyGetVelX(body)
        vycur# = phBodyGetVelY(body)
        vzcur# = phBodyGetVelZ(body)
        ;"вежливо" устанавливаем ту скорость, которую хотим мы
        ;считаем желаемое изменение скорости
        dvx# = (vx-vxcur);*.1
        If (vx*vx+vz*vz)<.001 Then dvy# = vy - vycur Else dvy# = 0
        dvz# = (vz-vzcur);*.1
        phBodyAddImpulse(body,x,y,z,dvx,dvy,dvz)
       
    EndIf

End Function

почему то не работают материалы,хотя трение должно быть максимальным..

LLI.T.A.L.K.E.R. 20.03.2011 02:29

Ответ: Вопрос-Ответ (для новичков)
 
Рисунок: http://s53.radikal.ru/i141/1103/92/ea40fd599a7b.jpg

Код внутри

Код:

; AddMesh Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

type_ground=1
type_character=2

Dim temp_vertex(4,4)

camera=CreateCamera()
PositionEntity camera,0,10,-10

light=CreateLight()
RotateEntity light,90,0,0

; Create tree mesh (upper half)
tree=CreateMesh()
PositionMesh tree,0,1.5,0

width#=3
height#=3

For i=1 To 50 Step 10
        For j=1 To 50 Step 10
                Local surface=CreateSurface(tree)
                temp_vertex(0,0)=AddVertex(surface,i-width#,0,j-height#)
                temp_vertex(0,1)=AddVertex(surface,i-width#,0,j+height#)
                temp_vertex(1,0)=AddVertex(surface,i+width#,0,j-height#)
                temp_vertex(1,1)=AddVertex(surface,i+width#,0,j+height#)
                VertexTexCoords surface,temp_vertex(0,0),0,1,0
                VertexTexCoords surface,temp_vertex(0,1),0,0,0
                VertexTexCoords surface,temp_vertex(1,0),1,1,0
                VertexTexCoords surface,temp_vertex(1,1),1,0,0
                AddTriangle(surface,temp_vertex(0,0),temp_vertex(0,1),temp_vertex(1,1))
                AddTriangle(surface,temp_vertex(1,1),temp_vertex(1,0),temp_vertex(0,0))
        Next
Next
UpdateNormals tree
EntityType tree,type_ground

Player=CreateCube()
PositionEntity player,-7,0,-4
EntityType player,type_character

Collisions type_character,type_ground,2,3

While Not KeyDown( 1 )

MoveEntity player,0.1,0,0.1
PointEntity camera,player

UpdateWorld
RenderWorld

Draw_Wire_2D(tree,camera,255,0,0)

Flip

Wend

End

Function Draw_Wire_2D(mesh,cam,red=0,grn=0,blu=0)
        Color red,grn,blu
        If EntityInView(mesh,cam)=False Then Return
        cnt=CountSurfaces(mesh)
        For a=1 To cnt
                surf=GetSurface(mesh,a)
                For tri=0 To CountTriangles(surf)-1
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,0)),VertexY(surf,TriangleVertex(surf,tri,0)),VertexZ(surf,TriangleVertex(surf,tri,0)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx1=ProjectedX()
                        sy1=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,1)),VertexY(surf,TriangleVertex(surf,tri,1)),VertexZ(surf,TriangleVertex(surf,tri,1)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx2=ProjectedX()
                        sy2=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,2)),VertexY(surf,TriangleVertex(surf,tri,2)),VertexZ(surf,TriangleVertex(surf,tri,2)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx3=ProjectedX()
                        sy3=ProjectedY()
                        If Check_Cull_2D(sx1,sy1,sx2,sy2,sx3,sy3)<0
                                Line sx1,sy1,sx2,sy2
                                Line sx2,sy2,sx3,sy3
                                Line sx3,sy3,sx1,sy1       
                        End If
                Next                       
        Next
End Function

Function Check_Cull_2D(x1,y1,x2,y2,x3,y3)
        Return (x1-x2)*(y3-y2)-(y1-y2)*(x3-x2)
End Function



Почему коллизия не действует на добавленные к мешу трианглы?

Примечание: кубик Player ударяется в стенку в позиции 0,0,0 радиусом 1

Кто знает RMFLoader 0.08 (загрузчик карт редактора Valve Hammer Editor), то там уровень строится по трианглам. И коллизия действует.
Сам сравнить код пока затрудняюсь, так как там он сильно развлетвлён.

Решение - ниже.

LLI.T.A.L.K.E.R. 20.03.2011 03:08

Ответ: Вопрос-Ответ (для новичков)
 
Как и предполагал: "коллизия не действовала, потому что модель была плоска относительно объекту." Повернул трианглы вертикально - теперь сталкивается. Теперь ручками придётся рисовать кубы и модельки.

Рисунок: http://s51.radikal.ru/i132/1103/90/a7334abd7668.jpg

Код:

; AddMesh Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

type_ground=1
type_character=2

Dim temp_vertex(4,4)

camera=CreateCamera()
PositionEntity camera,-10,10,-10

light=CreateLight()
RotateEntity light,90,0,0

; Create tree mesh (upper half)
Global tree=CreateMesh()
PositionMesh tree,0,1.5,0
Global surface=CreateSurface(tree)

width#=3
height#=3

For i=1 To 50 Step 8
        For j=1 To 50 Step 10
                temp_vertex(0,0)=AddVertex(surface,i-width#,-1,j-height#)
                temp_vertex(0,1)=AddVertex(surface,i-width#,-1,j+height#)
                temp_vertex(1,0)=AddVertex(surface,i-width#,2,j-height#)
                temp_vertex(1,1)=AddVertex(surface,i-width#,2,j+height#)
                VertexTexCoords surface,temp_vertex(0,0),0,1,0
                VertexTexCoords surface,temp_vertex(0,1),0,0,0
                VertexTexCoords surface,temp_vertex(1,0),1,1,0
                VertexTexCoords surface,temp_vertex(1,1),1,0,0
                AddTriangle(surface,temp_vertex(0,0),temp_vertex(0,1),temp_vertex(1,1))
                AddTriangle(surface,temp_vertex(1,1),temp_vertex(1,0),temp_vertex(0,0))
        Next
Next
UpdateNormals tree
EntityType tree,type_ground

Player=CreateCube()
PositionEntity Player,-7,0,-10
EntityType Player,type_character

Collisions type_character,type_ground,2,2

While Not KeyDown( 1 )

MoveEntity player,0.1,0,0.1
PointEntity camera,player

UpdateWorld
RenderWorld

Draw_Wire_2D(tree,camera,255,0,0)

Flip

Wend

End

Function Draw_Wire_2D(mesh,cam,red=0,grn=0,blu=0)
        Color red,grn,blu
        If EntityInView(mesh,cam)=False Then Return
        cnt=CountSurfaces(mesh)
        For a=1 To cnt
                surf=GetSurface(mesh,a)
                For tri=0 To CountTriangles(surf)-1
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,0)),VertexY(surf,TriangleVertex(surf,tri,0)),VertexZ(surf,TriangleVertex(surf,tri,0)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx1=ProjectedX()
                        sy1=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,1)),VertexY(surf,TriangleVertex(surf,tri,1)),VertexZ(surf,TriangleVertex(surf,tri,1)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx2=ProjectedX()
                        sy2=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,2)),VertexY(surf,TriangleVertex(surf,tri,2)),VertexZ(surf,TriangleVertex(surf,tri,2)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx3=ProjectedX()
                        sy3=ProjectedY()
                        If Check_Cull_2D(sx1,sy1,sx2,sy2,sx3,sy3)<0
                                Line sx1,sy1,sx2,sy2
                                Line sx2,sy2,sx3,sy3
                                Line sx3,sy3,sx1,sy1       
                        End If
                Next                       
        Next
End Function

Function Check_Cull_2D(x1,y1,x2,y2,x3,y3)
        Return (x1-x2)*(y3-y2)-(y1-y2)*(x3-x2)
End Function


RegIon 20.03.2011 12:12

Ответ: Вопрос-Ответ (для новичков)
 
LLI.T.A.L.K.E.R....ет ты кому написал...если мне,ТО У МЯ КОСЯКИ ФИЗИКИ......

LLI.T.A.L.K.E.R. 20.03.2011 12:23

Ответ: Вопрос-Ответ (для новичков)
 
Это я себе задачку решал: создание меша путём добавления трианглов и последующей коллизии.
Так же теперь допёр как правильно нужно делать AddMesh (а то не совсем правильно понял Blitz-help и был косяк с коллизией)

Вот тут окончательный тест по этой теме:

Код:

; AddMesh Example
; ---------------

Graphics3D 640,480
SetBuffer BackBuffer()

type_ground=1
type_character=2

Dim temp_vertex(4,4)

camera=CreateCamera()
PositionEntity camera,-10,10,-10

light=CreateLight()
RotateEntity light,90,0,0

; Create tree mesh (upper half)
Global tree=CreateMesh()
Global surface=CreateSurface(tree)

width#=3
height#=3

For i=1 To 50 Step 8
        For j=1 To 50 Step 10
                temp_vertex(0,0)=AddVertex(surface,i-width#,-1,j-height#)
                temp_vertex(0,1)=AddVertex(surface,i-width#,-1,j+height#)
                temp_vertex(1,0)=AddVertex(surface,i-width#,2,j-height#)
                temp_vertex(1,1)=AddVertex(surface,i-width#,2,j+height#)
                VertexTexCoords surface,temp_vertex(0,0),0,1,0
                VertexTexCoords surface,temp_vertex(0,1),0,0,0
                VertexTexCoords surface,temp_vertex(1,0),1,1,0
                VertexTexCoords surface,temp_vertex(1,1),1,0,0
                AddTriangle(surface,temp_vertex(0,0),temp_vertex(0,1),temp_vertex(1,1))
                AddTriangle(surface,temp_vertex(1,1),temp_vertex(1,0),temp_vertex(0,0))
        Next
Next
UpdateNormals tree
EntityType tree,type_ground

Cube=CreateCube()
PositionMesh Cube,-3,0,-5

AddMesh Cube,tree
FreeEntity Cube

Player=CreateCube()
PositionEntity Player,-7,0,-10
EntityType Player,type_character

Collisions type_character,type_ground,2,2

While Not KeyDown( 1 )

MoveEntity player,0.1,0,0.1
PointEntity camera,player

UpdateWorld
RenderWorld

Draw_Wire_2D(tree,camera,255,0,0)

Flip

Wend

End

Function Draw_Wire_2D(mesh,cam,red=0,grn=0,blu=0)
        Color red,grn,blu
        If EntityInView(mesh,cam)=False Then Return
        cnt=CountSurfaces(mesh)
        For a=1 To cnt
                surf=GetSurface(mesh,a)
                For tri=0 To CountTriangles(surf)-1
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,0)),VertexY(surf,TriangleVertex(surf,tri,0)),VertexZ(surf,TriangleVertex(surf,tri,0)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx1=ProjectedX()
                        sy1=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,1)),VertexY(surf,TriangleVertex(surf,tri,1)),VertexZ(surf,TriangleVertex(surf,tri,1)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx2=ProjectedX()
                        sy2=ProjectedY()
                        TFormPoint VertexX(surf,TriangleVertex(surf,tri,2)),VertexY(surf,TriangleVertex(surf,tri,2)),VertexZ(surf,TriangleVertex(surf,tri,2)),mesh,0
                        CameraProject(cam,TFormedX(),TFormedY(),TFormedZ())
                        sx3=ProjectedX()
                        sy3=ProjectedY()
                        If Check_Cull_2D(sx1,sy1,sx2,sy2,sx3,sy3)<0
                                Line sx1,sy1,sx2,sy2
                                Line sx2,sy2,sx3,sy3
                                Line sx3,sy3,sx1,sy1       
                        End If
                Next                       
        Next
End Function

Function Check_Cull_2D(x1,y1,x2,y2,x3,y3)
        Return (x1-x2)*(y3-y2)-(y1-y2)*(x3-x2)
End Function



Теперь будет не много мелких объектов, а один глобальный.

Из этого понял, что
PositionEntity - помещает скин, но не сам объект
PositionMesh - помещает объект со всеми его свойствами

LLI.T.A.L.K.E.R. 30.03.2011 13:23

Ответ: Вопрос-Ответ (для новичков)
 
Ogre3D Wrapper for Blitz3D
Example01 вылетает с МАВ (Windows 7)

Дебаг выдаёт проблемное место:
PHP код:

файл root.bb

    
Function SetMediaDir
        строка o_addResourceLocation 

Просьба проверить Ogre3D на Windows 7
и направить на путь исправления
ошибки

Вот исходники O3d+B3d

На WinXP ошибок не выдаёт.

IgorOK 30.03.2011 16:54

Ответ: Вопрос-Ответ (для новичков)
 
Как узнать директорию запуска приложения Blitz3D если приложение вызывалось перетаскиванием на него файла?

UPD:

Через функцию SystemProperty("appdir")

RlexGm 29.05.2011 11:39

Ответ: Вопрос-Ответ (для новичков)
 
Как сделать синхронизацию в игре на Blitz3D и ещё сделать реальное время т.е. например 3000 в игре - равно реальным 3 секундам..
Прошу прощенья, если этот вопрос уже где то был:)

pepel 29.05.2011 12:04

Ответ: Вопрос-Ответ (для новичков)
 
синхронизация игры и фпс 60 :

PHP код:

Graphics 640,480,16,2

Const UPS=60

period
=1000/UPS
time
=MilliSecs()-period

Repeat
    Repeat
        elapsed
=MilliSecs()-time
    Until elapsed    
    ticks
=elapsed/period
    tween
#=Float(elapsed Mod period)/Float(period)
    
    
For k=1 To ticks
        time
=time+period    
        
If KeyHit(1End    
    Next
    
    Flip
    Cls
Forever 

а команда MilliSecs() - это милисекунды

pepel 29.05.2011 12:37

Ответ: Вопрос-Ответ (для новичков)
 
PHP код:

Graphics3D 640,480,16,2



Const UPS=60

cub
=CreateCube()
cam=CreateCamera()
PositionEntity cam,0,0,-10

period
=1000/UPS
time
=MilliSecs()-period

Repeat
    Repeat
        elapsed
=MilliSecs()-time
    Until elapsed    
    ticks
=elapsed/period
    tween
#=Float(elapsed Mod period)/Float(period)

    

    
    
For k=1 To ticks
        time
=time+period
        
;Здесь код циклла
        TurnEntity cub
,0,0,1
        
        
If KeyHit(1End    
    Next

    

    RenderWorld 
()
    
Flip
    Cls

Forever 

попробуй поменять значение UPS и увидишь разницу)

LLI.T.A.L.K.E.R. 05.06.2011 00:00

Ответ: Вопрос-Ответ (для новичков)
 
В скором времени попробую изобретать велосипеды на Б3Д:

тупо вводишь в поисковике "исходник игры ..." - шашки, точки, пятнашки, крестики-нолики и т.п. (без ИИ)
изучаешь код - переводишь в 3Д на Б3Д


и опыт, и исходники другим, и прикольно

RegIon 05.06.2011 06:38

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

В скором времени попробую изобретать велосипеды на Б3Д:

тупо вводишь в поисковике "исходник игры ..." - шашки, точки, пятнашки, крестики-нолики и т.п. (без ИИ)
изучаешь код - переводишь в 3Д на Б3Д


и опыт, и исходники другим, и прикольно
я ща движку соберу на С,таким макаром на портативку игры и проги портировать стараться буду

RlexGm 06.06.2011 11:15

Ответ: Вопрос-Ответ (для новичков)
 
Такой вопрос, b3d сравнивает переменные string$?
У меня такой код:
PHP код:

If EnterKey$="2317499356"

Regfile=OpenFile("data\maps\7\file.vs")
WriteLine(regfile,"ab729c")
CloseFile(regfile)
click=0
Else

EnterKey$=""
SimKol=0
click
=0
EndIf 

PHP код:

Text centrw,centrh-50,"Press key",True,True
Text centrw
,centrh,EnterKey$,True,True
If SimKol<=10

If KeyHit(2Then EnterKey$=EnterKey$+"1":SimKol=SimKol+1
If KeyHit(3Then EnterKey$=EnterKey$+"2":SimKol=SimKol+1
If KeyHit(4Then EnterKey$=EnterKey$+"3":SimKol=SimKol+1
If KeyHit(5Then EnterKey$=EnterKey$+"4":SimKol=SimKol+1
If KeyHit(6Then EnterKey$=EnterKey$+"5":SimKol=SimKol+1
If KeyHit(7Then EnterKey$=EnterKey$+"6":SimKol=SimKol+1
If KeyHit(8Then EnterKey$=EnterKey$+"7":SimKol=SimKol+1
If KeyHit(9Then EnterKey$=EnterKey$+"8":SimKol=SimKol+1
If KeyHit(10Then EnterKey$=EnterKey$+"9":SimKol=SimKol+1
If KeyHit(11Then EnterKey$=EnterKey$+"0":SimKol=SimKol+1

EndIf 

Суть заключается в том, что когда будет введена переменная, и нажата кнопка будет сравнение набранной переменной с строковыми цифрами.Если набрано правильно, то в файл должна записаться строка.
Но когда набираешь правильно, то записи в файл не происходит.Просто всё стирается.Скажите пожалуйста в чём проблема.

RegIon 06.06.2011 11:25

Ответ: Вопрос-Ответ (для новичков)
 
нашёл как сделать, можно инпутом....

RegIon 06.06.2011 11:29

Ответ: Вопрос-Ответ (для новичков)
 
Код:

;GetKey возращает символ нажатой кнопки в Аск2
string_$=Chr(GetKey())
If string_$>"!";чтоб отсеять символ нечитабельный
String__$=String__$+string_$
EndIf
Text x,y, String__$;чтоб видно было


RlexGm 06.06.2011 11:52

Ответ: Вопрос-Ответ (для новичков)
 
всё равно не пишет в файл

LLI.T.A.L.K.E.R. 06.06.2011 12:16

Ответ: Вопрос-Ответ (для новичков)
 
Код:

If EnterKey$="2317499356"
Походу зациклен. Нужно один раз проверять, например при нажатии "Сохранить"

PHP код:

WriteFile (filename$)
Open a file to write to (открыть файл для записи

Код:

; Open a file to write to
fileout = WriteFile("mydata.dat")

; Write the information to the file
WriteString( fileout, BestName )
WriteInt( fileout, BestScore )
WriteByte( fileout, BestLevel )

; Close the file
CloseFile( fileout )

; Open the file to Read
filein = ReadFile("mydata.dat")



С OpenFile (filename$) со строками чёт помудрёней будет

RlexGm 06.06.2011 12:51

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от LLI.T.A.L.K.E.R. (Сообщение 190419)
Код:

If EnterKey$="2317499356"
Походу зациклен.

Нечего подобного :)
Цитата:

С OpenFile (filename$) со строками чёт помудрёней будет
разницы нет

RegIon 06.06.2011 15:21

Ответ: Вопрос-Ответ (для новичков)
 
а народ то не знает как с файлами работать...:-D

RlexGm 06.06.2011 16:19

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от RlexGm (Сообщение 190424)

разницы нет

в смысле что на результат ни как не влияет, как не записывал, так и не записывает

St_AnGer 06.06.2011 16:23

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от RlexGm (Сообщение 190412)
Такой вопрос, b3d сравнивает переменные string$?
У меня такой код:
PHP код:

If EnterKey$="2317499356"

Regfile=OpenFile("data\maps\7\file.vs")
WriteLine(regfile,"ab729c")
CloseFile(regfile)
click=0
Else

EnterKey$=""
SimKol=0
click
=0
EndIf 

PHP код:

Text centrw,centrh-50,"Press key",True,True
Text centrw
,centrh,EnterKey$,True,True
If SimKol<=10

If KeyHit(2Then EnterKey$=EnterKey$+"1":SimKol=SimKol+1
If KeyHit(3Then EnterKey$=EnterKey$+"2":SimKol=SimKol+1
If KeyHit(4Then EnterKey$=EnterKey$+"3":SimKol=SimKol+1
If KeyHit(5Then EnterKey$=EnterKey$+"4":SimKol=SimKol+1
If KeyHit(6Then EnterKey$=EnterKey$+"5":SimKol=SimKol+1
If KeyHit(7Then EnterKey$=EnterKey$+"6":SimKol=SimKol+1
If KeyHit(8Then EnterKey$=EnterKey$+"7":SimKol=SimKol+1
If KeyHit(9Then EnterKey$=EnterKey$+"8":SimKol=SimKol+1
If KeyHit(10Then EnterKey$=EnterKey$+"9":SimKol=SimKol+1
If KeyHit(11Then EnterKey$=EnterKey$+"0":SimKol=SimKol+1

EndIf 

Суть заключается в том, что когда будет введена переменная, и нажата кнопка будет сравнение набранной переменной с строковыми цифрами.Если набрано правильно, то в файл должна записаться строка.
Но когда набираешь правильно, то записи в файл не происходит.Просто всё стирается.Скажите пожалуйста в чём проблема.

Тупо скопировал твой код и вставил в б3д с небольшим допиливанием. Всё сравнивает и пишет в файл. Но, происходит перезапись файла. Исправляется предварительным чтением всего файла в массив пользуясь циклом
Код:

While Not Eof(file)
...
Wend

,
и последующая запись всего по порядку.
Возможно как то можно открыть файл в б3д на дозапись, но я не знаю как.

RegIon 06.06.2011 16:42

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Возможно как то можно открыть файл в б3д на дозапись, но я не знаю как.
там SeekFile( file, ofset) ставит позицию для записи,не знаю в чем мерится...

RlexGm 06.06.2011 17:01

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от St_AnGer (Сообщение 190438)
Но, происходит перезапись файла

Перезапись? Стирается старое значение и записываеться новое?

RegIon 06.06.2011 17:16

Ответ: Вопрос-Ответ (для новичков)
 
да,но с лайнами вроде так не проходит,он всегда дописывает лайн(WriteLine)

St_AnGer 06.06.2011 18:20

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от Костян (Сообщение 190443)
да,но с лайнами вроде так не проходит,он всегда дописывает лайн(WriteLine)

дописывает только при текущей работе с файлом до закрытия файла. Иначе файл переписывается с нуля новыми данными.

RegIon 07.06.2011 07:04

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

дописывает только при текущей работе с файлом до закрытия файла. Иначе файл переписывается с нуля новыми данными.
ведать я его забывал закрывать...

RlexGm 08.06.2011 19:15

Ответ: Вопрос-Ответ (для новичков)
 
выяснил что при сравнении б3д не видит что EnterKey$ и циферки равны, т.к. выполняется условие "не равно"...С чем это может быть связано?

LLI.T.A.L.K.E.R. 09.06.2011 01:42

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от RlexGm (Сообщение 190412)
Такой вопрос, b3d сравнивает переменные string$?
У меня такой код:
Код:

If EnterKey$="2317499356"
 . .
Else
 . . EnterKey$=""
EndIf


Короче так как EnterKey$ изначально не равен "2317499356"
то он всегда чист EnterKey$=""
Тут вот тупик!

Или давай относительно полный код! Так как наверняка проверка If EnterKey$="2317499356" происходит в один определённый момент (действии).

RlexGm 09.06.2011 09:17

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от LLI.T.A.L.K.E.R. (Сообщение 190811)
то он всегда чист EnterKey$=""

Так он же выводиться на экран:4to:
Цитата:

Сообщение от LLI.T.A.L.K.E.R. (Сообщение 190811)
давай относительно полный код! (действии).

PHP код:

If bt\status=And click=1 Then ;click=1 когда нажимаешь на мышь
...
...
...

If 
bt\id=26 Then если id кнопки такойто:
If 
EnterKey$="2317499356"
FileReg=OpenFile("data\maps\7\file.vs")
WriteLine(FileReg,"ab729c")
CloseFile(FileReg)
EndIf
If 
EnterKey$!="2317499356" здесь делал разное: Else, If not EnterKey$= , != и т.д
EnterKey$=""
SimKol=0
End 
если вылетаетзначит выполняется это условие
EndIf  
EndIf

...

click=0
EndIf
EndIf 

не большая не важная поправка, код php убрал знак \. bt\ это в типе. Например тут btstatus=2, а должно быть bt\status=2

RegIon 09.06.2011 12:12

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Graphics 640,480,16,2

Const UPS=60

period=1000/UPS
time=MilliSecs()-period

Repeat

Repeat
elapsed=MilliSecs()-time
Until elapsed
ticks=elapsed/period
tween#=Float(elapsed Mod period)/Float(period)

For k=1 To ticks
time=time+period


s=GetKey()
If s>32 s_$=s_$+Chr(s)

;;If s_="1234567890" And KeyHit(57) End

;;If btstatus=2 And click=1 Then ;click=1 когда нажимаешь на мышь

If MouseHit(1) Then ; если id кнопки такой, то:
If s_$="1234567890"
FileReg=WriteFile("file.txt")
WriteLine(FileReg,"ab729c")
CloseFile(FileReg)
EndIf
If s_$="1234567890" ; здесь делал разное: Else, If not EnterKey$= , != и т.д.
s_$=""
SimKol=0
End ; если вылетает, значит выполняется это условие
EndIf
EndIf


click=0




Text 0,0,s_


If KeyHit(1) End
Next

Flip
Cls
Forever
вот врубил твой код...МОЖЕТ неправильно набираешь просто,у меня всё работает.......S_=EnterKEy(),может просто нет процедуры нажатия кнопки
Цитата:

EnterKey$!="2317499356"
что за !=,блитз разве знает такую функцию???

Leowey 10.06.2011 00:42

Ответ: Вопрос-Ответ (для новичков)
 



Цитата:

Цитата:

EnterKey$!="2317499356"
что за !=,блитз разве знает такую функцию???



Плюсы отаке!!!!!111


Nex 10.06.2011 09:59

Ответ: Вопрос-Ответ (для новичков)
 
Дайте пожалуйста код с шумом Перлина.
В инете все туторы для c++, моя его не понимать. :(

KingMaks 11.06.2011 14:12

Ответ: Вопрос-Ответ (для новичков)
 
Нету в папке блиц примера castle. Выложите у кого имееться:)

tormoz 11.06.2011 15:40

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от Nex (Сообщение 190975)
Дайте пожалуйста код с шумом Перлина.
В инете все туторы для c++, моя его не понимать. :(


Код:

; -------------------------------------------------------------------------------------------------------------------
; Perlin Noise Heightmap Generator - Copyright 2003 - Shawn C. Swift
; -------------------------------------------------------------------------------------------------------------------

Graphics 640,480,32,2
SetBuffer BackBuffer()
Const MAX_HEIGHTMAP_SIZE =1024

Dim HeightMap#(MAX_HEIGHTMAP_SIZE, MAX_HEIGHTMAP_SIZE)
Dim NoiseMap#(MAX_HEIGHTMAP_SIZE+1, MAX_HEIGHTMAP_SIZE+1)


.Main

        SeedRnd MilliSecs()       


        ; Set the size of the heightmap we want to generate.
        HeightMapSize =32

        ; Generate the heightmap.
        Generate_Heightmap(HeightMapSize, 0.25, 2)

        ; Save the heightmap to an image.
        ; You'll get more accuracy and more interesting terrains if you save the actual data instead.
        ; But that will quadruple the size of the datafile created.
        ; Which is why instead you might consider just figuring out which sets of values produce a nice terrain and then
        ; just creating the terrain at runtime when the program starts.  But if you do this, pray Mark never changes the
        ; behavior of the rand() function!
               
                ; Create an image.
                        DestImage = CreateImage(HeightMapSize, HeightMapSize)
                        DestBuffer = ImageBuffer(DestImage)
                    DrawImage DestImage,0,0
                    Text 20,20,"aaaaa"
                    Flip
       
                ; Write the data to the image.

                        LockBuffer(DestBuffer)
               
                        For LoopY = 0 To HeightMapSize-1
                                For LoopX = 0 To HeightMapSize-1       
                                       
                                        ; Calculate the color for this pixel.
                                        Pr = HeightMap#(LoopX, LoopY)
                                        If Pr < 0  Then Pr = 0
                                        If Pr > 255 Then Pr = 255
                                       
                                        Pg = Pr
                                        Pb = Pr
                                                                               
                                        ; Convert the color into a longint.       
                                        NewPixel = Pb Or (Pg Shl 8) Or (Pr Shl 16) Or ($ff000000)
       
                                        ; Store the pixel in the image.
                                        WritePixelFast LoopX, LoopY, NewPixel, DestBuffer
                                DrawImage DestImage,0,0
                              Cls
                              Text 20,20,LoopY
                    Flip
                                Next
                        Next       
               
                        UnlockBuffer(DestBuffer)
                        SetBuffer BackBuffer()
                        Cls
                        Text 20,20,"bbbbbbb"
                    DrawImage DestImage,0,0
                    Flip
                  WaitKey
                        ;SaveImage(DestImage, "heightmap.bmp")
                        FreeImage DestImage
       
        ; All done!
                       
End


; -------------------------------------------------------------------------------------------------------------------
; HeightmapSize must ba a power of 2.
; Scale# is the maximum height of the most frequent and smallest bumps in the terrain.
; Multiplier# is how much each successive pass multiplies scale# by.
; -------------------------------------------------------------------------------------------------------------------
Function Generate_Heightmap(HeightMapSize, Scale#, Multiplier#)

        ; Set the maximum height of the first noise pass.
        Max_Height# = Scale#

        ; Do the first pass seprately from the other passes since we can do it very cheaply.
       
                For Noise_Y = 0 To HeightMapSize
                        For Noise_X = 0 To HeightMapSize
                                HeightMap#(Noise_X, Noise_Y) = Rnd#(0, Max_Height#)
                        Next
                Next

        ; Now start with the second highest frequency noise;
        ; The second largest noise map with slightly larger bumps than the first pass.
        NoiseMapSize = HeightMapSize/2
       
        ; Multiply the maximum height for the start of the second pass.
        Max_Height# = Max_Height# * Multiplier#
               
        Repeat
       
                ; Generate a noise map.
                For Noise_Y = 0 To NoiseMapSize
                        For Noise_X = 0 To NoiseMapSize
                                NoiseMap#(Noise_X, Noise_Y) = Rnd#(0, Max_Height#)
                        Next
                Next

                ; Calculate the diffrence in scale between the noisemap and the heightmap.               
                ScaleDifference = HeightMapSize / NoiseMapSize
               
                ; Calculate how large of steps across the noise map we need to take for each pixel of the heightmap.
                StepSize# = 1.0 / Float(ScaleDifference)

                ; Stretch the noise map over the heightmap using bilinear filtering.
                For Noise_Y = 0 To NoiseMapSize-1
                        For Noise_X = 0 To NoiseMapSize-1

                                N1# = NoiseMap#(Noise_X,  Noise_Y) 
                                N2# = NoiseMap#(Noise_X+1, Noise_Y) 
                                N3# = NoiseMap#(Noise_X,  Noise_Y+1)
                                N4# = NoiseMap#(Noise_X+1, Noise_Y+1)
                       
                                Hx = Noise_X*ScaleDifference
                                Hy = Noise_Y*ScaleDifference
                       
                                Iy# = 0
                                For Height_Y = 0 To ScaleDifference-1

                                        ; Calculate cosine-weighted bilinear average.
       
                                                ICy# = 1.0 - ((Cos(Iy#*180.0) + 1.0) / 2.0)
                                       
                                        Ix# = 0                       
                                        For Height_X = 0 To ScaleDifference-1
                               
                                                ; Calculate cosine-weighted bilinear average.
                                                ;
                                                ; Cosine weighting makes the map smoother, removing unsightly diamond artifacts from the
                                                ; bilinear filtering.
                                                ;
                                                ; Essentially it "pushes" the four corner pixel colors towards the center, reducing the area
                                                ; which is the average of the colors.  So the corner pixels go from a blurry diamond shape
                                                ; to a blurry circle.
                                                ;
                                                ; It is of course, slower to calculate than regular bilinear filtering, though by using a
                                                ; lookup table one could possibly speed the operation a litle.
                                                                                                       
                                                        ICx# = 1.0 - ((Cos(Ix#*180.0) + 1.0) / 2.0)

                                                        Na# = N1#*(1.0-ICx#)
                                                        Nb# = N2#*ICx#
                                                        Nc# = N3#*(1.0-ICx#)
                                                        Nd# = N4#*ICx#
                                                       
                                                        HeightMap#(Hx+Height_X, Hy+Height_Y) = HeightMap#(Hx+Height_X, Hy+Height_Y) + (Na#+Nb#)*(1.0-ICy#) + (Nc+Nd#)*ICy#
                                               
                                                ; Calculate bilinear average.

                                                        ;Na# = N1#*(1.0-Ix#)
                                                        ;Nb# = N2#*Ix#
                                                        ;Nc# = N3#*(1.0-Ix#)
                                                        ;Nd# = N4#*Ix#
                                                                               
                                                        ;HeightMap#(Hx+Height_X, Hy+Height_Y) = HeightMap#(Hx+Height_X, Hy+Height_Y) + (Na#+Nb#)*(1.0-Iy#) + (Nc+Nd#)*Iy#
                               
                                                Ix# = Ix# + StepSize#

                                        Next
                                       
                                        Iy# = Iy# + StepSize#       

                                Next
               
                        Next
                       
                Next
               
                ; Reduce the frequency of the noise by half.                               
                NoiseMapSize = NoiseMapSize/2
               
                ; Increase the maximum height of the noise.
                Max_Height# = Max_Height# * Multiplier#
                       
        Until NoiseMapSize <= 1

End Function


Код:

; ID: 1420
; Author: Booticus
; Date: 2005-07-12 21:19:27
; Title: Heightmap Toolbox
; Description: Generates Heightmaps with varying techniques.

;Strict

;Rem

;HeightMap Toolbox
;V0.1.0 BETA

;By Shane Raffa
;May 2005

;Incorporating code (adapted) by
; * Shawn C. Swift (Perlin noise stuff)
; * Simon Wetterlind (Midpoint displacement stuff)

;PURPOSE

        A self-contained package of heightmap creating, processing, exporting, And
        importing utilities.

TEST SYSTEM

        Athlon XP 1600+, 512MB, GeForce 3 Ti200 (64MB)
        Windows XP, BlitzMax

IMPLEMENTED METHODS And FUNCTIONS:
       
        createRandomMap
        createHillMap
        createParticleSMap
        createParticleRMap
        createFaultMap
        createPerlinMap
        createMPDMap
                recurseMPD
                MPD
       
        fill
        resize
        normalise
        smoothen
        flatten
        makeCoast
       
        exportPNG
        importPNG
        exportX3D
        exportBin
        importBin

    blendMapsAdd       
    blendWithMapAdd
    blendMapsSub       
    blendWithMapSub
    blendMapsMul
    blendWithMapMul
    blendMapsDiv
    blendWithMapDiv
    blendMapsHi
    blendWithMapHi
    blendMapsLo
    blendWithMapLo
    blendMapsRep
    blendWithMapRep

        renderToBackBuffer
        renderToImage
        renderToPixmap
       
TODO:

        makeRivers
        makeIsland
        importX3D
        {Mac OS 10.x port}
        {improve documentation}

End Rem

Type THeightMap

  Field Width = 128                                'Width (units) > 0
  Field Height = 128                        'Height (units) > 0
  Field Map#[Width, Height]          'Matrix of height values (floats) >=0.0 <=1.0 normalised

  Rem fill(val# = 0.0)
  Set all heights To a specific value.
  val#: value To use. Use 0.0 To clear the map.
  End Rem
  Method fill(val# = 0.0)

    Local x, z

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        Map#[x, z] = val#
      Next
    Next

  End Method
 
  Rem resize(w, h)
  Resize the map.
  w: width. > 0. Higher = slower performance And increased memory consumption.
  h: height. > 0. Higher = slower performance And increased memory consumption.
  End Rem
  Method resize(w, h)
   
    If Not ((w > 0) And (h > 0)) Return

    Map# = Null
    FlushMem

    Width = w
    Height = h
    Map# = New Float[Width, Height]

  End Method

  Rem createRandomMap(seed)
  Create a map of random height between 0.0 And 1.0.
  seed: random seed. Use MilliSecs() To generate a different result every time.
  End Rem
  Method createRandomMap(seed)

    Local x, z

    SeedRnd(seed)

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        Map#[x, z] = Rnd()
      Next
    Next

  End Method

  Rem createHillMap(seed, numhills, maxhsize)
  Create a map using the "hill algorithm".
  seed: random seed. Use MilliSecs() To generate a different result every time.
  numhills: number of hills. (>1000) is best. Minimum 1.
  maxhsize: maximum hill radius. For best results, value should be significantly
  less than the map's shortest dimension.
  End Rem
  Method createHillMap(seed, numhills, maxhsize)

    Local i, n, x, z, centrex, centrez, radius, startx, endx, startz, endz, ipos
    Local y#
 
    SeedRnd(seed)

    fill(0.0)
 
    For n = 1 To numhills

          centrex = Rand(0, Width - 1)
          centrez = Rand(0, Height - 1)
          radius = Rand(0, Abs(maxhsize))

      startx = centrex - radius
      If startx < 0
            startx = 0
      EndIf

      endx = centrex + radius
          If endx > Width
            endx = Width
      EndIf

      startz = centrez - radius
      If startz < 0
            startz = 0
      EndIf

      endz = centrez + radius
      If endz > Height
            endz = Height
      EndIf

      For x = startx To endx - 1
        For z = startz To endz - 1
                    y# = (radius * radius) - (((x - centrex) * (x - centrex)) + ((z - centrez) * (z - centrez)))
              If y# > 0.0
                Map#[x, z] :+ y#
              EndIf
            Next
          Next
   
    Next
 
    normalise()
 
  End Method

  Rem createParticleSMap(seed, particles, clusters)
  Create a map using the "sticky particle deposition" algorithm.
  seed: random seed. Use MilliSecs() To generate a different result every time.
  particles: number of particles To calculate per cluster. Minimum 1.
  cluster: number of clusters: higher number gives greater map density. Minimum 1.
  End Rem
  Method createParticleSMap(seed, particles, clusters)

    Local m, n, x, z
    Local y#, disp# = 1.0
 
    SeedRnd(seed)

    fill(0.0)
 
    For m = 0 To clusters - 1
 
      x = Rand(0, Width - 1)
      z = Rand(0, Height - 1)
       
      For n = 0 To particles - 1
       
        If ((x < Width) And (z < Height) And (x >= 0) And (z >= 0))
              y# = Map#[x, z] + disp#
              Map#[x, z] = y#
            EndIf
       
            Select Rand(0, 3)
          Case 0
            x :+ 1
          Case 1
            x :- 1
          Case 2
            z :+ 1
          Case 3
            z :- 1
        End Select

      Next

    Next

    normalise()
 
  End Method

  Rem createParticleRMap(seed, particles, clusters)
  Create a map using the "rolling particle deposition" algorithm.
  seed: random seed. Use MilliSecs() To generate a different result every time.
  particles: number of particles To calculate per cluster. Minimum 1.
  cluster: number of clusters: higher number gives greater map density. Minimum 1.
  End Rem
  Method createParticleRMap(seed, particles, clusters)

    Local m, n, x, z, x2, z2, startx, endx, startz, endz
    Local y#, y2#, disp# = 1.0
 
    SeedRnd(seed)

    fill(0.0)
 
    For m = 0 To clusters - 1
 
      x = Rand(0, Width - 1)
      z = Rand(0, Height - 1)
       
      For n = 0 To particles - 1
       
        If ((x < Width) And (z < Height) And (x >= 0) And (z >= 0))

              y# = Map#[x, z] + disp#
              Map#[x, z] = y#
       
              startx = x - 1
          If startx < 0 
                    startx = 0
                  EndIf
          endx = x + 1
          If endx > Width
                      endx = Width
          EndIf

          startz = z - 1
          If startz < 0
                    startz = 0
                  EndIf
          endz = z + 1
          If endz > Height
                    endz = Height
          EndIf

          For x2 = startx To endx - 1
            For z2 = startz To endz - 1
                      y2# = Map#[x2, z2]
              If y2# < y#
                Map#[x2, z2] = y2# + disp#
              EndIf
            Next
          Next
       
            EndIf
       
            Select Rand(0, 3)
          Case 0
            x :+ 1
          Case 1
            x :- 1
          Case 2
            z :+ 1
          Case 3
            z :- 1
        End Select

      Next

    Next

    normalise()
 
  End Method
 
  Rem createFaultMap(seed, realism)
  Create a map using the "fault line" algorithm.
  seed: random seed. Use MilliSecs() To generate a different result every time.
  realism: number of fault lines: higher number (> 1000) gives greater realism. Minimum 1.
  End Rem
  Method createFaultMap(seed, realism)

    Local n, x, z
    Local d#, disp#, v#, a#, b#, c#
 
    SeedRnd(seed)

    fill(0.0)
 
    d# = Sqr((Width * Width) + (Height * Height))
    disp# = 10.0

    For n = 1 To realism
 
      v# = Rnd(1,359)
          a# = Sin(v#)
      b# = Cos(v#)
      c# = (RndFloat() * d#) - (d# / 2)

      For x = 0 To Width - 1
        For z = 0 To Height - 1
          If (((a# * x) + (b# * z) - c#) > 0.0)
            Map#[x, z] :+ disp#
          Else
            Map#[x, z] :- disp#
          EndIf
        Next
      Next

    Next

    normalise()

  End Method

  Rem createPerlinMap(seed, scale#, multiplier#)
  Create a map using the "perlin noise" alogorithm.
  ADAPTED from code obtained from the blitzbasic.com code archives.
  **** ORIGINAL AUTHOR: Shawn C. Swift ****
  IMPORTANT NOTE: This method will only work properly on maps with equal Width And
  Height dimensions that are a power of two: eg 256 x 256.
  seed: random seed. Use MilliSecs() To generate a different result every time.
  "scale# is the maximum height of the most frequent and smallest bumps in the terrain." - S. Swift.
  "multiplier# is how much each successive pass multiplies scale# by." - S. Swift.
  End Rem
  Method createPerlinMap(seed, scale#, multiplier#)

    If Not(Width = Height) Return

    SeedRnd(seed)

    Local size = Width
    Local x, z, ipos, ScaleDifference, Hx, Hz, Height_Z, Height_X,  Noise_Z, Noise_X
    Local max_height# = scale
    Local NoiseMapSize = Floor(size / 2)
        Local i;
        Local NoiseMap#[NoiseMapSize + 1, NoiseMapSize + 1]

        Local StepSize#, N1#, N2#, N3#, N4#, Iy#, ICy#, Ix#, ICx#, Na#, Nb#, Nc#, Nd#, y#
       
        For x = 0 To size - 1
      For z = 0 To size - 1
        Map#[x, z] = RndFloat() * scale
          Next
          Next
 
    max_height# :* multiplier#
       
  Repeat
 
      For Noise_Z = 0 To NoiseMapSize
            For Noise_X = 0 To NoiseMapSize
                    NoiseMap#[Noise_X, Noise_Z] = RndFloat() * max_height#
                Next
          Next
       
      ScaleDifference = size / NoiseMapSize
      StepSize = 1.0 / ScaleDifference
               
      For Noise_Z = 0 To NoiseMapSize - 1
            For Noise_X = 0 To NoiseMapSize - 1
                N1# = NoiseMap#[Noise_X, Noise_Z]
                  N2# = NoiseMap#[(Noise_X + 1), Noise_Z] 
              N3# = NoiseMap#[Noise_X, (Noise_Z + 1)]
              N4# = NoiseMap#[(Noise_X + 1), (Noise_Z + 1)]
              Hx = Noise_X * ScaleDifference
              Hz = Noise_Z * ScaleDifference
              Iy# = 0.0
       
              For Height_Z = 0 To ScaleDifference - 1
                        ICy# = 1.0 - ((Cos(Iy# * 180.0) + 1.0) / 2.0)
                    Ix# = 0.0                       
           
                    For Height_X = 0 To ScaleDifference - 1
                          ICx = 1.0 - ((Cos(Ix * 180.0) + 1.0) / 2.0)
                        Na# = N1# * (1.0 - ICx#)
                      Nb# = N2# * ICx#;
                      Nc# = N3# * (1.0 - ICx#)
                        Nd# = N4# * ICx#
                                                       
                      y# = Map#[(Hx + Height_X), (Hz + Height_Z)]
                      Map#[(Hx + Height_X), (Hz + Height_Z)] = (y# + (Na# + Nb#) * (1.0 - ICy#) + (Nc# + Nd#) * ICy#)
                      Ix# = Ix# + StepSize;
                    Next
                                       
                    Iy# = Iy# + StepSize#       

              Next
       
            Next         
      Next
                               
    NoiseMapSize :/ 2
    max_height# :* multiplier
                       
    Until (NoiseMapSize < 1)

        normalise()

  End Method

  Rem
  createMPDMap(seed, grain#)
  recurseMPD(x0, y0, x2, y2, grain#, level#)
  mpd#(x0, y0, x1, y1, x2, y2, grain#, level#)

  ADAPTED from code obtained from the BlitzCoder.com code database.
  **** ORIGINAL AUTHOR: Simon Wetterlind 13-08-2002 ****
  **** v.0.9.3 - Revised: 18-11-2002 by Simon Wetterlind. ****

  These methods are used To create a terrain map using the
  Midpoint Displacement fractal algorithm (ie Plasma algorithm).
  grain# is the "graininess" i.e. the influence of randomness.

  seed: random seed. Use MilliSecs() To generate a different result every time.
  End Rem
  Method createMPDMap(seed, grain#)

    fill(-1.0)

    SeedRnd(seed)

    Map#[0, 0] = RndFloat()
    Map#[(Width - 1), 0] = RndFloat()
    Map#[0, (Height - 1)]= RndFloat()
    Map#[(Width - 1), (Height - 1)] = RndFloat()

    recurseMPD(0, 0, Width - 1, Height - 1, grain#, 1.0)

    normalise()

  End Method

  Method recurseMPD(x0, z0, x2, z2, grain#, level#)

    If (x2 - x0 < 2) And (z2 - z0 < 2) Then Return
   
    Local v#, i#

    ' change the calculation of level# To (possibly) achieve
    ' strange results
    level# = 2.0 * level#
   
    Local x1 = Ceil((x0 + x2) / 2.0)
    Local z1 = Ceil((z0 + z2) / 2.0)
   
    v# = Map#[x1, z0]
    If v# = -1.0
      v# = MPD#(x0, z0, x1, z0, x2, z0, grain#, level#)
    EndIf
    i# = v#
   
    v# = Map#[x2, z1]
    If v# = -1.0
      v# = MPD#(x2, z0, x2, z1, x2, z2, grain#, level#)
    EndIf
    i# :+ v#
   
    v# = Map#[x1, z2]
    If v# = -1.0
      v# = MPD#(x0, z2, x1, z2, x2, z2, grain#, level#)
    EndIf
    i# :+ v#

    v# = Map#[x0, z1]
    If v# = -1.0
      v# = MPD#(x0, z0, x0, z1, x0, z2, grain#, level#)
    EndIf
    i# :+ v#

    If Map#[x1, z1] = -1.0
      Map#[x1, z1] = i# / 4.0 + Rnd(-grain#, grain#) / level#
    EndIf
 
    RecurseMPD(x0, z0, x1, z1, grain#, level#)
    RecurseMPD(x1, z0, x2, z1, grain#, level#)
    RecurseMPD(x1, z1, x2, z2, grain#, level#)
    RecurseMPD(x0, z1, x1, z2, grain#, level#)

  End Method

  Method MPD#(x0, z0, x1, z1, x2, z2, grain#, level#)

    Local r# = 0

    r# :+ (Map#[x0, z0] + Map#[x2, z2]) / 2.0
   
    If r# < 0.0 Then r# = 0.0
    If r# > 1.0 Then r# = 1.0
 
    Map#[x1, z1] = r#
   
    Return r#
   
  End Method

  Rem normalise()
    Normalise all map values To between 0 And 1.
  End Rem
  Method normalise()

  Local x, z;
  Local minv# = 10^38, maxv# = 10^-38, y#
 
  For x = 0 To Width - 1
    For z = 0 To Height - 1

      y# = Map#[x, z]
            If y# < minv#
            minv# = y#
          Else
            If y# > maxv#
                  maxv# = y#
                EndIf
          EndIf
         
    Next
  Next

  For x = 0 To Width - 1
    For z = 0 To Height - 1
      y# = (Map#[x, z] - minv#) / (maxv# - minv#)
          Map#[x, z] = y#
        Next
  Next       
       
  End Method

  Rem smoothen(k#)
  Smooth the map values.
  Some maps require more smoothing than others To create more realistic terrains.
  k#: smoothing factor. Minumum 0.0 (extreme). Maxumum 1.0 (no smoothing).
  End Rem
  Method smoothen(k#)
 
    Local x, z
    Local y#, y2#

    For x = 1 To Width - 1
      For z = 0 To Height - 1
            y# = Map#[x, z]
            y2# = Map#[(x - 1), z]
            Map#[x, z] = y2# * (1 - k#) + y# * k#
      Next
    Next

    For x = (Width - 3) To 0 Step -1
      For z = 0 To Height - 1
            y# = Map#[x, z]
            y2# = Map#[(x + 1), z]
            Map#[x, z] = y2# * (1 - k#) + y# * k#
      Next
    Next

    For x = 0 To Width - 1
      For z = 1 To Height - 1
            y# = Map#[x, z]
            y2# = Map#[x, (z - 1)]
            Map#[x, z] = y2# * (1 - k#) + y# * k#
      Next
    Next

    For x = 0 To Width - 1
      For z = (Height - 3) To 0 Step -1
            y# = Map#[x, z]
            y2# = Map#[x, (z + 1)]
            Map#[x, z] = y2# * (1 - k#) + y# * k#
      Next
    Next

  End Method

  Rem flatten(value#)
  'Flatten' the map values.
  value#: flattening amount. 1 = no flattening. Minimum 1. Maximum (suggested) 4.
  End Rem
  Method flatten(value#)

    Local x, z
    Local y#
 
    For x = 0 To Width - 1
      For z = 0 To Height - 1
        y# = Map#[x, z] ^ value#
        Map#[x, z] = y#
      Next
    Next

  End Method
 
  Rem makeCoast(extent#, depth#)
  Create a crude coastline effect. For best results, smoothing should be applied
  After this process.
  extent#: extent of coastilisation. 0.0 To 1.0 = None To 100%.
  depth#: depth. 0.0 To 1.0 = Shallow To deep.*/
  End Rem
  Method makeCoast(extent#, depth#)

    Local x, z
        Local y#, e#, d#, minv# = 10^38, maxv# = 10^-38
       
    For x = 0 To Width - 1
      For z = 0 To Height - 1
        y# = Map#[x, z]
            If y# < minv#
              minv# = y#
            Else
              If y# > maxv#
                    maxv# = y#
                  EndIf
            EndIf
          Next
        Next

        e# = (maxv# - minv#) * extent#
        d# = (maxv# - minv#) * depth#
       
    For x = 0 To Width - 1
      For z = 0 To Height - 1
            y# = Map#[x, z]
            If y# <= (minv# + e#)
              Map#[x, z] = y# - d#
            EndIf
          Next
        Next 
 
    normalise()

  End Method

  Rem exportToPNG(url$ = "test.png", clvl = 9)
    Save the map To a greyscale PNG file.
    url$: target file.
    clvl: Compression level: 0 To 9: low To high. Higher = slower.
  End Rem
  Method exportPNG(url$ = "test.png", clvl = 9)

    Local result = False
    Local pmap:TPixmap = CreatePixmap(Width, Height, PF_RGBA8888)

    renderToPixmap(pmap)
    result = SavePixmapPNG(pmap, url$, clvl)

    pmap = Null
    FlushMem

    If result
      Print url$ + " saved."
    Else
      Print url$ + " could NOT be saved."
    EndIf

  End Method

  Rem importFromPNG(url$)
    Import from a PNG file.
    url$: source file. Only the blue component Data is used.
  End Rem
  Method importPNG(url$)

    Local x, z, c

    Local pmap:TPixmap = LoadPixmapPNG(url$)

    If pmap = Null
      Print url$ + " could NOT be loaded."
      FlushMem
      Return
    Else
      Print url$ + " loaded."     
    EndIf

    resize(pmap.Width, pmap.Height)
 
    For x = 0 To Width - 1
      For z = 0 To Height - 1
        c = ReadPixel(pmap, x, z)
        c :| c Shr 24
        Map#[x, z] = $000000 | c
      Next
    Next

    normalise()

    pmap = Null
    FlushMem

  End Method

  Rem exportToX3D(url$ = "test.x3d", tpl$ = "", hmulti# = 10.0, xspacing# = 100.0, zspacing# = 100.0, prec = 4)
  Reads an X3d V3.0 file (used as a template) And generates a New X3d file
  incorporating the original file And "ElevationGrid" Data generated from the map Data.
  url$: Target file name. Any existing file with the same name will be REPLACED.
  templ$ = source X3d file name: the "ElevationGrid" tag must be empty And start
  on a New Line ie: "<ElevationGrid />" without the quotes. If the template file is
  Not found Then internal X3d code is used.
  hmulti# = height multiplyer: higher values will produce higher/steeper terrain elements.
  xSpacing# = corresponds To the x3d ElevationGrid xSpacing property.
  zSpacing# = corresponds To the x3d ElevationGrid zSpacing property.
  prec = precision (number of digits) For the exported height values. 1 To 8. eg 4 = 1.34 Or 12.2 etc
  End Rem
  Method exportX3D(url$ = "test.x3d", tpl$ = "", hmulti# = 10.0, xspacing# = 100.0, zspacing# = 100.0, prec = 4)

    Local pre$ = ""
    Local post$ = ""
    Local tag$ = "<ElevationGrid ccw='true' "
    tag$ :+ "creaseAngle='0.76' "
    tag$ :+ "solid='false' "
    tag$ :+ "colorPerVertex='true' "
    tag$ :+ "normalPerVertex='true' "
    tag$ :+ "xDimension='" + Width + "' "
    tag$ :+ "xSpacing='" + xspacing# + "' "
    tag$ :+ "zDimension='" + Height + "' "
    tag$ :+ "zSpacing='" + zspacing# + "' height='~r"

    Local templ:TStream = OpenFile(tpl$)
    If Not templ
      Print "Template file " + tpl$ + " could NOT be opened. Using internal template..."
      pre$ = "<?xml version='1.0'?>~r"
      pre$ :+ "<!DOCTYPE X3D Public 'ISO//Web3D//DTD X3D 3.0//EN' 'http://www.web3d.org/specifications/x3d-3.0.dtd'>~r"
      pre$ :+ "<X3D profile='Immersive' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' xsd:noNamespaceSchemaLocation='http://www.web3d.org/specifications/x3d-3.0.xsd'>~r"
      pre$ :+ "<head><meta name='generator' content='Heightmap Toolbox V0.1'/></head>~r"
      pre$ :+ "<Scene><NavigationInfo Type='~qFLY~q ~qANY~q' speed='3.0' /><Viewpoint description='VP1' orientation='0 0 0 0' position='20 20 100' centerOfRotation='90 0 0'/>~r"
      pre$ :+ "<Shape><Appearance><Material diffuseColor='0.4 0.4 0.1' emissiveColor='0.3 0.3 0.3' /></Appearance>~r"
      post$ = "~r</Shape></Scene></X3D>"
    Else
      Print "Using template file " + tpl$ + "."
    EndIf

    Local result = CreateFile(url$)

    If Not result 
      Print url$ + " could NOT be created."
      Return
    EndIf

    Local x, z, spos
    Local n$, t$, l$

    Local file:TStream = OpenFile(url$)

    Try

    If templ
      t$ = "<ElevationGrid />"
      l$ = ReadLine (templ)
      spos = Instr(l$, t$)
      While Not Eof(templ)
        If spos > 0 Then Exit
        WriteLine file, l$
        l$ = ReadLine (templ)
        spos = Instr(l$, t$)
      Wend
     
    Else
      WriteString(file, pre$)
    EndIf

    WriteString(file, tag$)

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        n$ = String.FromFloat(Map#[x, z] * hmulti#)
        n$ = n$[..prec] + " "
        WriteString(file, n$)
      Next
    Next

    WriteString(file, "'/>")

    If templ
      While Not Eof(templ)
        l$ = ReadLine (templ)
        WriteLine file, l$
      Wend
    Else
      WriteString(file, post$)
    EndIf

    CloseFile(file)
    If templ CloseFile(templ)

    Catch ex:Object
      Print "File IO error."
      Return
    End Try

    Print "X3D file " + url$ + " saved."

  End Method

  Rem exportBin(url$ = "test.bin")
    Save heightmap Data as a binary file.
    File Structure:
            1 * Int (Width)
            1 * Int (Height)
            Width * Height * Floats (height values)
    url$: target file name.
  End Rem
  Method exportBin(url$ = "test.bin")

    Local result = False

    result = CreateFile(url$)

    If Not result 
      Print url$ + " could NOT be created."
      Return
    EndIf

    Local x, z

    Try

    Local file:TStream = OpenFile(url$)

    WriteInt(file, Width)
    WriteInt(file, Height)

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        WriteFloat(file, Map#[x, z])
      Next
    Next
   
    CloseFile(file)

    Catch ex:Object
      Print "File IO error."
      Return
    End Try

    Print "Binary file " + url$ + " created."

  End Method

  Rem importBin(url$ = "test.bin")
    Load heightmap Data from a binary file that was previously saved using exportBin.
    url$: source file name.
  End Rem
  Method importBin(url$ = "test.bin")

    Local x, z

    Local file = False

    file = OpenFile(url$)

    If Not file 
      Print url$ + " could NOT be opened."
      Return
    EndIf

    Try

    resize(ReadInt(file), ReadInt(file))

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        Map#[x, z] = ReadFloat(file)
      Next
    Next

    Catch ex:Object
      Print "File IO error."
      Return
    End Try

    Print "Binary file " + url$ + " loaded."

  End Method

  Rem blendMapsAdd(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps using an additive process.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsAdd(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        outp.Map#[x, z] = y1# + y2#

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapAdd(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance using a
  an additive process.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapAdd(src:THeightMap)

    blendMapsAdd(Self, src, Self)

  End Method

  Rem blendMapsSub(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps using a subtractive process.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsSub(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        outp.Map#[x, z] = y1# - y2#

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapSub(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance using a
  a subtractive process.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapSub(src:THeightMap)

    blendMapsSub(Self, src, Self)

  End Method

  Rem blendMapsMul(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps using an multiplicative process.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsMul(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        outp.Map#[x, z] = y1# * y2#

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapMul(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance using a
  an multiplicative process.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapMul(src:THeightMap)

    blendMapsMul(Self, src, Self)

  End Method

  Rem blendMapsDiv(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps using a division process.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsDiv(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        outp.Map#[x, z] = y1# / y2#

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapDiv(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance using a
  an division process.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapDiv(src:THeightMap)

    blendMapsDiv(Self, src, Self)

  End Method

  Rem blendMapsHi(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps, favouring the highest values.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsHi(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        If y1# > y2# Then
          outp.Map#[x, z] = y1#
        Else
          outp.Map#[x, z] = y2#
        EndIf

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapHi(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance,
  favouring the highest values.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapHi(src:THeightMap)

    blendMapsHi(Self, src, Self)

  End Method

  Rem blendMapsHi(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps, favouring the lowest values.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsLo(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        If y1# < y2# Then
          outp.Map#[x, z] = y1#
        Else
          outp.Map#[x, z] = y2#
        EndIf

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapLo(src:THeightMap)
  Blends the current THeightMap instance with another THeightMap instance,
  favouring the lowest values.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapLo(src:THeightMap)

    blendMapsLo(Self, src, Self)

  End Method

  Rem blendMapsRep(src1:THeightMap, src2:THeightMap, outp:THeightMap)
  Blends two maps, replacing outp's values with src1's values. ie copy src1 To outp.
  src1: source THeightMap instance #1.
  src2: source THeightMap instance #2.
  outp: output THeightMap instance into which the results will be stored.
  End Rem
  Function blendMapsRep(src1:THeightMap, src2:THeightMap, outp:THeightMap)

    Local x, z
    Local y1#, y2#
   
    For x = 0 To outp.Width - 1
      For z = 0 To outp.Height - 1

        If (x < src1.Width) And (z < src1.Height)
          y1# = src1.Map#[x, z]
        Else
          y1# = 0.0
        EndIf 
        If (x < src2.Width) And (z < src2.Height)
          y2# = src2.Map#[x, z]
        Else
          y2# = 0.0
        EndIf 

        outp.Map#[x, z] = y1#

      Next
    Next
   
    outp.normalise()

  End Function

  Rem blendWithMapRep(src:THeightMap)
  Replaces the current THeightMap values with those of another THeightMap instance.
  src: THeightMap To blend with.
  End Rem
  Method blendWithMapRep(src:THeightMap)

    blendMapsRep(Self, src, Self)

  End Method

  Rem renderToImage(img:TImage, offx = 0, offz = 0)
  Render the map To a BlitzMax image Object.
  img: Destination TImage Object. Must be the same dimensions as the map.
  offx: x offset (pixels) into img. >=0 And <=img width.
  offz: z offset (pixels) into img. >=0 And <=img height.
  End Rem
  Method renderToImage(img:TImage, offx = 0, offz = 0)

    Local pm = LockImage(img)
    renderToPixmap(pm, offx, offz)
    UnlockImage(img)

  End Method

  Rem renderToPixmap(pm:TPixmap, offx = 0, offz = 0)
  Render the map To a BlitzMax pixmap Object.
  pm: Destination TPixmap Object. Must be the same dimensions as the
  map. The pixmap format should be PF_RGBA8888
  offx: x offset (pixels) into pm. >=0 And <=pm width.
  offz: z offset (pixels) into pm. >=0 And <=pm height.
  End Rem
  Method renderToPixmap(pm:TPixmap, offx = 0, offz = 0)

    If Not ((offx >= 0) And (offx < pm.Width)) Return
    If Not ((offz >= 0) And (offz < pm.Height)) Return

    Local x, z, r, g, b, a = $FF000000

    For x = 0 To Width - 1
      For z = 0 To Height - 1
                If ((offx + x) < pm.Width) And ((offz + z) < pm.Height)
          r = Floor(Map#[x, z] * 255)
          g = r
          b = r
          WritePixel(pm, (offx + x), (offz + z), a Shl 24 | r Shl 16 | g Shl 8 | b Shl 0)
        EndIf
      Next
    Next

  End Method

  Rem renderToBackBuffer(offx = 0, offz = 0)
  Render the map directly To the BackBuffer.
  offx: x offset (pixels) BackBuffer. >=0 And <=screen width.
  offz: z offset (pixels) BackBuffer. >=0 And <=screen height.
  TODO; Validate offx and offz.
  End Rem
  Method renderToBackBuffer(offx = 0, offz = 0)
   
    Local gw = GraphicsWidth()
    Local gh = GraphicsHeight()

    If Not ((offx >= 0) And (offx < gw)) Return
    If Not ((offz >= 0) And (offz < gh)) Return

    Local x, z, c

    For x = 0 To Width - 1
      For z = 0 To Height - 1
        If ((offx + x) < gw) And ((offz + z) < gh)
          c = Floor(Map#[x, z] * 255)
          SetColor c, c, c
          Plot (offx + x), (offz + z)
        EndIf
      Next
    Next

  End Method

End Type





'==================================
' Cut And paste this And save it
' as hmaptest.bmx Or whatever.
'==================================



Rem

Height Map Test
V0.1.0 BETA

By Shane Raffa
May 2005

PURPOSE

        A crude, non-gui heightmap editing program To demonstrate usage
        of the THeightMap class. (See hmap010.bmx)

TEST SYSTEM

        Athlon XP 1600+, 512MB, GeForce 3 Ti200 (64MB)
        Windows XP, BlitzMax

End Rem

Strict

Import "hmap010.bmx"

Type THMapTest Extends THeightMap

  Field Img1:TImage

  Field ScrnX
  Field ScrnZ

  Method create(w, h, sx = 0, sz = 0)

    ScrnX = sx
    ScrnZ = sz
    resize(w, h)
    Img1:TImage = CreateImage(Width, Height, 1, DYNAMICIMAGE)
    generateMap()

  End Method
 
  Method destroy()

    Img1 = Null

  End Method

  Method generateMap()

    Local n = Rand(0, 5)

    DrawText "Generating Map... ", ScrnX, ScrnZ
    Flip

    Select n
      Case 0
        createPerlinMap(MilliSecs(), 0.25, 1.5)
      Case 1
        createMPDMap(MilliSecs(), 0.5)
      Case 2
        createHillMap(MilliSecs(), 1000, 30)
      Case 3
        createParticleSMap(MilliSecs(), 1000, 1000)
        smoothen(0.25)
      Case 4
        createParticleRMap(MilliSecs(), 1000, 1000)
        smoothen(0.25)
      Case 5
        createFaultMap(MilliSecs(), 500)
        smoothen(0.25)
    End Select
   
    renderToImage(Img1, 0, 0)

    render()
    Flip

  End Method

  Method render()

    DrawImage(Img1, ScrnX, ScrnZ)
   
  End Method

End Type


Graphics 800, 600

SetBlend(SOLIDBLEND)
SetLineWidth(2.0)

Global Menu = True
Global Active = 0

Global HMap:THMapTest[] = [New THMapTest, New THMapTest, New THMapTest]

HMap[0].create(256, 256, 0, 0)
HMap[1].create(256, 256, HMap[0].Width, 0)
HMap[2].create(256, 256, HMap[0].Width + HMap[1].Width, 0)

While Not KeyHit(KEY_ESCAPE)

  Cls

  For Local i:THMapTest = EachIn HMap
    i.render()
  Next

  If MouseDown(1)
    Local c = 0
    For Local i:THMapTest = EachIn HMap
      If (MouseX() >= i.ScrnX) And (MouseX() < (i.ScrnX + i.Width))
        If (MouseY() >= i.ScrnZ) And (MouseY() < (i.ScrnZ + i.Height))
          Active = c
        EndIf
      EndIf
      c :+ 1
    Next
  EndIf

  If Menu showMenu()

  drawActiveBox()

  processKeys()
  FlushKeys()

  Flip

Wend

For Local i:THMapTest = EachIn HMap
  i.destroy()
Next

FlushMem

EndGraphics

End

Function drawActiveBox()

  SetColor(0, 255, 0)
  DrawLine HMap[Active].ScrnX, HMap[Active].ScrnZ, HMap[Active].ScrnX + HMap[Active].Width - 1, HMap[Active].ScrnZ
  DrawLine HMap[Active].ScrnX + HMap[Active].Width - 1, HMap[Active].ScrnZ, HMap[Active].ScrnX + HMap[Active].Width - 1, HMap[Active].ScrnZ + HMap[Active].Height - 1
  DrawLine HMap[Active].ScrnX, HMap[Active].ScrnZ + HMap[Active].Height - 1, HMap[Active].ScrnX + HMap[Active].Width - 1, HMap[Active].ScrnZ + HMap[Active].Height - 1
  DrawLine HMap[Active].ScrnX, HMap[Active].ScrnZ, HMap[Active].ScrnX, HMap[Active].ScrnZ + HMap[Active].Height - 1
  SetColor(255, 255, 255)

End Function

Function showMenu()

  DrawText "SELECT", 5, 300
  DrawText "------", 5, 315
  DrawText "{Left Click} - Select", 5, 330
  DrawText "UP ARROW - Next", 5, 345
  DrawText "RIGHT ARROW - Next", 5, 360
  DrawText "DOWN ARROW - Previous", 5, 375
  DrawText "LEFT ARROW - Previous", 5, 390
  DrawText "ESC - Exit", 5, 405
  DrawText "TAB - Toggle Menu", 5, 420

  DrawText "CREATE", 200, 300
  DrawText "------", 200, 315
  DrawText "1 - Random", 200, 330
  DrawText "2 - Perlin", 200, 345
  DrawText "3 - Midpoint Disp.", 200, 360
  DrawText "4 - Hill", 200, 375
  DrawText "5 - Sticky Particle", 200, 390
  DrawText "6 - Rolling Particle", 200, 405
  DrawText "7 - Fault", 200, 420
  DrawText "0 - Clear", 200, 435

  DrawText "PROCESS", 400, 300
  DrawText "-------", 400, 315
  DrawText "SPACE - Smoothen", 400, 330
  DrawText "f - Flatten", 400, 345
  DrawText "c - Coast", 400, 360
  DrawText "a - Blend Add", 400, 375
  DrawText "s - Blend Subtract", 400, 390
  DrawText "m - Blend Multiply", 400, 405
  DrawText "d - Blend Divide", 400, 420
  DrawText "h - Blend Highest", 400, 435
  DrawText "l - Blend Lowest", 400, 450
  DrawText "r - Blend Replace", 400, 465

  DrawText "IMPORT/EXPORT", 600, 300
  DrawText "-------------", 600, 315
  DrawText "F1 - Export Binary", 600, 330
  DrawText "F2 - Export PNG", 600, 345
  DrawText "F3 - Export X3D", 600, 360
  DrawText "F5 - Import Binary", 600, 390
  DrawText "F6 - Import PNG", 600, 405
  DrawText "F10 - Export...", 600, 435
  DrawText "F12 - Import...", 600, 450

End Function

Function processKeys()
 
  If KeyDown(KEY_0)
    DrawText "Clearing... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].fill(0.0)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_1)
    DrawText "Generating Random... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createRandomMap(MilliSecs())
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_2)
    DrawText "Generating Perlin... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createPerlinMap(MilliSecs(), 0.25, 1.5)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_3)
    DrawText "Generating MPD... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createMPDMap(MilliSecs(), 0.5)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_4)
    DrawText "Generating Hill... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createHillMap(MilliSecs(), 1000, 30)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_5)
    DrawText "Generating S Particle... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createParticleSMap(MilliSecs(), 1000, 1000)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_6)
    DrawText "Generating R Particle... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createParticleRMap(MilliSecs(), 1000, 1000)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If
  If KeyDown(KEY_7)
    DrawText "Generating Fault... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].createFaultMap(MilliSecs(), 500)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  End If

  If KeyDown(KEY_UP) Or KeyDown(KEY_RIGHT)
    Active :+ 1
    If Active >= HMap.length Active = 0
  End If

  If KeyDown(KEY_DOWN) Or KeyDown(KEY_LEFT)
    Active :- 1
    If Active < 0 Active = HMap.length - 1
  End If

  If KeyDown(KEY_TAB)
    Menu = Not Menu
  End If

  If KeyDown(KEY_SPACE)
    DrawText "Smoothing... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].smoothen(0.75)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf

  If KeyDown(KEY_F)
    DrawText "Flattening... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].flatten(2)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf

  If KeyDown(KEY_C)
    DrawText "Making Coast... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].makeCoast(0.5, 0.1)
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf

  If KeyDown(KEY_A)
    DrawText "Blending (Add)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsAdd(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsAdd(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsAdd(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf

  If KeyDown(KEY_S)
    DrawText "Blending (Subtract)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsSub(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsSub(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsSub(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_M)
    DrawText "Blending (Multiply)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsMul(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsMul(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsMul(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_D)
    DrawText "Blending (Divide)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsDiv(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsDiv(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsDiv(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_H)
    DrawText "Blending (Highest)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsHi(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsHi(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsHi(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_L)
    DrawText "Blending (Lowest)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsLo(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsLo(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsLo(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_R)
    DrawText "Blending (Replace)... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    Select Active
      Case 0
        THeightMap.blendMapsRep(HMap[1], HMap[2], HMap[Active])
      Case 1
        THeightMap.blendMapsRep(HMap[0], HMap[2], HMap[Active])
      Case 2
        THeightMap.blendMapsRep(HMap[0], HMap[1], HMap[Active])
      End Select
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf

  If KeyDown(KEY_F1)
    DrawText "Exporting test.bin... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].exportBin("test.bin")
  EndIf
  If KeyDown(KEY_F5)
    DrawText "Importing test.bin... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].importBin("test.bin")
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_F2)
    DrawText "Exporting test.png... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].exportPNG("test.png", 9)
  EndIf
  If KeyDown(KEY_F6)
    DrawText "Importing test.png... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].importPNG("test.png")
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_F3)
    DrawText "Exporting test.x3d... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
    Flip
    HMap[Active].exportX3d("test.x3d", "templ01.x3d", 40.0, 2.0, 2.0)
  EndIf
  If KeyDown(KEY_F12)
    Local fn$ = RequestFile("Import file...", "Supported Files:png,bin;All Files:*", False)
    If Right$(fn$, 4) = ".png"
      DrawText "Importing PNG: " + fn$ + "... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
      Flip
      HMap[Active].importPNG(fn$)
    Else
      If Right$(fn$, 4) = ".bin"
        DrawText "Importing Binary: " + fn$ + "... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
        Flip
        HMap[Active].importBin(fn$)
      EndIf
    EndIf
    HMap[Active].renderToImage(HMap[Active].Img1, 0, 0)
  EndIf
  If KeyDown(KEY_F10)
    Local fn$ = RequestFile("Export file...", "Supported Files:png,bin,x3d", True)
    If Right$(fn$, 4) = ".png"
      DrawText "Exporting PNG: " + fn$ + "... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
      Flip
      HMap[Active].exportPNG(fn$)
    Else
      If Right$(fn$, 4) = ".bin"
        DrawText "Exporting Binary: " + fn$ + "... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
        Flip
        HMap[Active].exportBin(fn$)
      Else
        If Right$(fn$, 4) = ".x3d"
          DrawText "Exporting X3D: " + fn$ + "... ", HMap[Active].ScrnX, HMap[Active].ScrnZ
          Flip
          HMap[Active].exportX3d(fn$, "templ01.x3d", 40.0, 2.0, 2.0)
        EndIf
      EndIf
    EndIf
  EndIf

End Function


KingMaks 12.06.2011 15:04

Ответ: Вопрос-Ответ (для новичков)
 
Может кто знает, как провернуть родительский объект на определенный угол не повернув при этом дочерние объекты?
Разумно ли будет освобождать дочерние объекты от родительского, затем проворачивать родительский объект и опять привязывать дочерние?

baton4ik 12.06.2011 15:50

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от KingMaks (Сообщение 191283)
Может кто знает, как провернуть родительский объект на определенный угол не повернув при этом дочерние объекты?
Разумно ли будет освобождать дочерние объекты от родительского, затем проворачивать родительский объект и опять привязывать дочерние?

Поворачиваешь родительский на angle, а дочерние на -angle. Можно и отвязывать.

KingMaks 13.06.2011 18:24

Ответ: Вопрос-Ответ (для новичков)
 
Нужна помощь!
Есть небольшой код:
Цитата:

Graphics3D 800,600
SetBuffer BackBuffer()

pivot=CreatePivot()
sphere=CreateSphere()
PositionEntity sphere,0,0,5
EntityParent sphere,pivot

cam=CreateCamera()
PositionEntity cam,0,20,0
RotateEntity cam,90,0,0

cub=CreateCube()
PositionEntity cub,5,0,-5

Repeat

If KeyDown(203) TurnEntity pivot,0,1,0
If KeyDown(200) PointEntity cub,sphere

UpdateWorld
RenderWorld
Flip
Until KeyHit(1)
End
Здесь при нажатии кнопки вперед куб резко поворачивается в сторону сферы, а нужно, чтобы поворачивался плавно и только при нажатии вперед! Подскажите неучу:)

Nex 13.06.2011 18:36

Ответ: Вопрос-Ответ (для новичков)
 
Кнопка "Поиск"!
Цитата:

Сообщение от HolyDel (Сообщение 18081)
Graphics3D 800,600
SetBuffer BackBuffer()

obj1=CreateSphere()

obj2=CreateCone()
RotateMesh obj2,90,0,0

p=CreatePlane()
EntityAlpha p,0.5
EntityColor p,255,0,0

cam=CreateCamera()
PositionEntity cam,0,10,-20
RotateEntity cam,45,0,0

l=CreateLight()

PositionEntity obj2,0,0,0
PositionEntity obj1,4,4,4

EntityBox p,-10000,-2,-10000,20000,2,20000
EntityPickMode p,3

While Not KeyDown(1)

If MouseDown(1)
CameraPick(cam,MouseX(),MouseY())
cx#=PickedX()
cz#=PickedZ()
PositionEntity obj1,cx,4,cz
EndIf

curvepointentity(obj2,obj1,5,5)
MoveEntity obj2,0,0,0.3
RenderWorld
Flip

Wend

Function CurvePointEntity(ent1,ent2,speedx#=1,speedy#=1)
dx#=DeltaPitch(ent1,ent2)
dy#=DeltaYaw(ent1,ent2)
If Abs(dx#)>speedx# Then TurnEntity ent1,speedx#*Sgn(dx),0,0 Else TurnEntity ent1,dx,0,0
If Abs(dy#)>speedy# Then TurnEntity ent1,0,speedy#*Sgn(dy),0 Else TurnEntity ent1,0,dy,0
End Function

Собственно ent1 - который надо повернуть, ent2 - на который надо повернуть,speedx - скорость поворота по оси х (за один вызов функции),speedy - скорость поворота по оси Y (за один вызов функции).


dsd 13.06.2011 18:58

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от KingMaks (Сообщение 191416)
Нужна помощь!
Есть небольшой код:


Здесь при нажатии кнопки вперед куб резко поворачивается в сторону сферы, а нужно, чтобы поворачивался плавно и только при нажатии вперед! Подскажите неучу:)

Graphics3D 800,600
SetBuffer BackBuffer()


Global cub,sphere

pivot=CreatePivot()
sphere=CreateSphere()
PositionEntity sphere,0,0,5
EntityParent sphere,pivot

cam=CreateCamera()
PositionEntity cam,0,20,0
RotateEntity cam,90,0,0


cub=CreateCone()
PositionEntity cub,5,0,-5
RotateMesh cub,90,0,0


timer=CreateTimer(30)
Repeat

If KeyDown(203) TurnEntity pivot,0,1,0
;If KeyDown(200) PointEntity cub,sphere
If KeyDown(200) Magic

UpdateWorld
RenderWorld
WaitTimer(timer)
Flip

Until KeyHit(1)
End

Function Magic()
oldroll#=EntityRoll#(cub)
olppitch#=EntityPitch#(cub)
oldyaw#=EntityYaw#(cub)
PointEntity cub,sphere
nroll#=EntityRoll#(cub)
npitch#=EntityPitch#(cub)
nyaw#=EntityYaw#(cub)
RotateEntity cub,oldpitch-0.1*(oldpitch-npitch),oldyaw-0.1*(oldyaw-nyaw),oldroll-0.1*(oldroll-nroll)

End Function

dsd 15.06.2011 01:02

Ответ: Вопрос-Ответ (для новичков)
 
Захотел я сделать так чтобы предмет был приближен к камере максимально и в тоже время полностью влазил в кадр.
Посчитал я максимальную ширину меша:
Sqr(MeshWidth(testcube)^2+MeshDepth(testcube)^2+Me shHeight(testcube)^2)

Расстояние от камеры до предмета:
EntityDistance(testcube,supershadowcamera)

поделил второе на первое и получил число, которое по моему пониманию при умножении на некую константу даст необходимый зум камеры. В итоге выяснилось что необходимая мне константа ни разу не константа. Почему? На глаз постигать зависимость тяжко. Может кто знает эту зависимость? Или это как то связано с сжатием по оси от камеры в дксграббере? Типа зум как бы линеен, но само 3д пространство не линейно что ли?

з.ы. Чет я туплю. :-) Забыл про основные свойства ортогональной проекции. Зум должен зависеть только от ширины меша

RegIon 15.06.2011 08:20

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Типа зум как бы линеен, но само 3д пространство не линейно что ли?
чет я не верю что зум линеен...Есди камера была 1,1,1,зумим её на ю 0.5 по всем осям,получается : .5,.5,.5, если ещё раз ещё провести-то никак не будет 0,0,0(будет всегда на половину меньше)--ту зум вроде квадратичен

tormoz 15.06.2011 10:00

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от dsd (Сообщение 191549)
Захотел я сделать так чтобы предмет был приближен к камере максимально и в тоже время полностью влазил в кадр.
Посчитал я максимальную ширину меша:
Sqr(MeshWidth(testcube)^2+MeshDepth(testcube)^2+Me shHeight(testcube)^2)

Расстояние от камеры до предмета:
EntityDistance(testcube,supershadowcamera)

поделил второе на первое и получил число, которое по моему пониманию при умножении на некую константу даст необходимый зум камеры. В итоге выяснилось что необходимая мне константа ни разу не константа. Почему? На глаз постигать зависимость тяжко. Может кто знает эту зависимость? Или это как то связано с сжатием по оси от камеры в дксграббере? Типа зум как бы линеен, но само 3д пространство не линейно что ли?

CameraProjMode camera,mode
Parameters
camera - camera handle
mode - projection mode:
0: no projection - disables camera (faster than HideEntity)
1: perspective projection (default)
2: orthographic projection

Description
Sets the camera projection mode.

The projection mode is the the technique used by Blitz to display 3D graphics on the screen. Using projection mode 0, nothing is displayed on the screen, and this is the fastest method of hiding a camera. Using camera projection mode 1, the graphics are displayed in their 'correct' form - and this is the default mode for a camera. Camera projection mode 2 is a special type of projection, used for displaying 3D graphics on screen, but in a 2D form - that is, no sense of perspective will be given to the graphics. Two identical objects at varying distances from the camera will both appear to be the same size. Orthographic projection is useful for 3D editors, where a sense of perspective is unimportant, and also certain games.

Use 'CameraZoom' to control the scale of graphics rendered with orthographic projection. As a general rule, using orthographic projection with the default camera zoom setting of 1 will result in graphics that are too 'zoomed-in' - changing the camera zoom to 0.1 should fix this.

One thing to note with using camera project mode 2, is that terrains will not be displayed correctly - this is because the level of detail algorithm used by terrains relies on perspective in order to work properly.

Example
; CameraProjMode Example
; ----------------------

Код:

Graphics3D 640,480
SetBuffer BackBuffer()

camera=CreateCamera()
PositionEntity camera,0,0,-10

light=CreateLight()
RotateEntity light,0,0,0

; Create cube 1, near to camera
cube1=CreateCube()
EntityColor cube1,255,0,0
PositionEntity cube1,0,0,0

; Create cube 2, same size as cube 1 but further away
cube2=CreateCube()
EntityColor cube2,0,255,0
PositionEntity cube2,5,5,5

While Not KeyDown( 1 )

; If spacebar pressed then change mode value
If KeyHit(57)=True Then mode=mode+1 : If mode=3 Then mode=0

; If mode value = 2 (orthagraphic), then reduce zoom value to 0.1
If mode=2 Then zoom#=0.1 Else zoom#=1

; Set camera projection mode using mode value
CameraProjMode camera,mode

; Set camera zoom using zoom value
CameraZoom camera,zoom#

RenderWorld

Text 0,0,"Press spacebar to change the camera project mode"
Text 0,20,"CameraProjMode camera,"+mode
Text 0,40,"CameraZoom camera,"+zoom#

Flip

Cls

Wend

End


dsd 16.06.2011 21:50

Ответ: Вопрос-Ответ (для новичков)
 
«Arrays can be re-dimmed by using the Dim statement again with the same array name, but the contents of the array will be lost.» Не могу я понять как поменять размер массива, хотя судя по этой строке это возможно. Или моя английский не достаточен для понимания смысла этого предложения и тут говорится о другом?

Вообще возможно менять кол-во элементов и размерность массива в функциях? Или нужно просто создавать массив с размерами которых точно хватит?

Кстати почему блитц начинает глючить если в меше больше 80к треугольников?

Делал функцию для создания мешей отдаленно похожих на поверхности вращения. Получился зачаток генератора пещер :)

Global pivot,camera,mxs#,mys#,Light,testmesh

Graphics3D 480,360,0,2
SetBuffer BackBuffer()
Dither 0

pivot=CreatePivot()
PositionEntity pivot,0,0,-40
camera=CreateCamera(pivot)
CameraClsColor camera,0,75,151
light=CreateLight()
ScaleSprite CreateSprite(light),0.2,0.2
AmbientLight 15,15,15

timer1=MilliSecs()
r#=45
segments=380
lengthsegment=40

Dim opanki#(segments-1,2,lengthsegment)

MakeTube(r#,segments,lengthsegment,4)
timer2=MilliSecs()
While Not KeyHit(1)
timer3=MilliSecs()
PointEntity light,camera
PositionEntity light,25*Sin(MilliSecs()/30),25,25*Cos(MilliSecs()/30)
If KeyDown(57) Then
If zulu<>Int(MilliSecs()/1000) Then
zulu=Int(MilliSecs()/1000)
If z=0 Then z=1 Else z=0
WireFrame z
EndIf
yhuu
Else WireFrame 0
EndIf
UpdateWorld
RenderWorld



control(1,1.4)
Text 100,10,"polygons in view "+TrisRendered()
Text 100,20,"number of vertices in test mesh "+CountVertices(GetSurface (testmesh,1))
Text 100,30,"millisecs for creation mesh "+(timer2-timer1)
Text 100,40,"Frames per second is: "+1000/(MilliSecs()-timer3)
Text 100,50,"Do not press [spacebar]"


Flip 0
Wend
End

Function yhuu()
surf1=GetSurface(testmesh,1)
For i=0 To CountVertices(surf1)-1
VertexCoords (surf1,i,VertexX(surf1,i),VertexY(surf1,i)+Sin(Mil liSecs()+i/10),VertexZ(surf1,i))
Next
End Function

Function control(speed#,mousesensitivity#)
mxs#=mxs#+(MouseXSpeed()/5.0)
mys#=mys#+(MouseYSpeed()/5.0)
RotateEntity camera,mousesensitivity#*mys#,-mousesensitivity#*mxs#,0
MoveMouse GraphicsWidth()/2,GraphicsHeight()/2
If KeyDown(17) Or KeyDown(200) MoveEntity camera,0,0,speed#
If KeyDown(31) Or KeyDown(208) MoveEntity camera,0,0,-speed#
If KeyDown(30) Or KeyDown(203) MoveEntity camera,-speed#,0,0
If KeyDown(32) Or KeyDown(205) MoveEntity camera,speed#,0,0
PositionEntity pivot,EntityX#(camera,1),EntityY#(camera,1),Entity Z#(camera,1)
PositionEntity camera,0,0,0
End Function

Function MakeTube(r#,segments,lengthsegment,seglenth#)
If segments=<2 RuntimeError "Illegal number of vertices for each segment"

For d=0 To lengthsegment
For i=0 To segments-1
opanki(i,0,d)=R#*Cos(360*i/segments)
opanki(i,1,d)=R#*Sin(360*i/segments)
opanki(i,2,d)=-lengthsegment*seglenth/2+seglenth*d
Next
Next


;For d=0 To lengthsegment
;For i=0 To segments-1
;PositionEntity CreateCube(),cucaracha(i,0,d)-40,cucaracha(i,1,d),cucaracha(i,2,d)
;Next
;Next

testmesh=CreateMesh()
testsurf=CreateSurface(testmesh)
For d=0 To lengthsegment
For i=0 To segments-1
AddVertex(testsurf,opanki(i,0,d),opanki(i,1,d),opa nki(i,2,d))
Next
Next

For d=0 To lengthsegment-1
For i=0 To segments-2
AddTriangle(testsurf,d*segments+i,(d+1)*segments+i ,d*segments+i+1)
AddTriangle(testsurf,d*segments+i+1,(d+1)*segments +i,(d+1)*segments+i+1)
Next
Next

For d=0 To lengthsegment-1
AddTriangle(testsurf,d*segments+segments-1,(d+1)*segments,d*segments)
AddTriangle(testsurf,(d+2)*segments-1,(d+1)*segments,(d+1)*segments-1)
Next

UpdateNormals testmesh

flipped=CopyMesh(testmesh)
ScaleMesh flipped,-1.4,-1.4,-1.0
AddMesh flipped,testmesh

FreeEntity flipped
End Function

baton4ik 16.06.2011 22:47

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от dsd (Сообщение 191838)
«Arrays can be re-dimmed by using the Dim statement again with the same array name, but the contents of the array will be lost.» Не могу я понять как поменять размер массива, хотя судя по этой строке это возможно. Или моя английский не достаточен для понимания смысла этого предложения и тут говорится о другом?

Просто инициализируешь массив с таким же названием, как предыдущий. Учти, что это его очистит.

dsd 16.06.2011 23:03

Ответ: Вопрос-Ответ (для новичков)
 
Если я пишу программу:

бла-бла
dim моймассив#(1)

бла-бла-бла
dim моймассив#(dimmension1,dim2,dim3)

оно компилить не хочет. Говорит: error duplicate identifer.

Если пишу:

бла-бла-бла.
dim моймассив#(1)

бла-бла-бла
end

function бу-бу-бу
dim моймассив#(dimmension1,dim2,dim3)
бла-бла-бла
end function
говорит тоже самое...
Может это особенность ide visual blitz?

NitE 17.06.2011 00:10

Ответ: Вопрос-Ответ (для новичков)
 
Нельзя менять количество измерений массива.

dsd 17.06.2011 00:55

Ответ: Вопрос-Ответ (для новичков)
 
Nite, мегасэнкс. Заработало. Теперь буду изврашаться с криволенейной направляющей и динамической образующей. Это будет жесткая функция:-)

dsd 18.06.2011 01:02

Ответ: Вопрос-Ответ (для новичков)
 
В общем решил я организовать вращение меша при помощи неведомой хрени явившейся мне во время заливки стяжки. Этакий ротэйтмеш только посредством вычислений новых координат точки в зависимости от пары углов. И ладно бы если бы ничего не получилось. Довольно легко получилось нечто вращающее меш вокруг одной оси правильно. При использовании двух углов начинает плавно корежить меш изгибая его по краю формой подозрительно похожей на синусоиду.
Это оно мне как бэ намекает, что косяк в вычислениях новых координат точек, в исходных данных или и там и там?

А с утра мой код стал мне напоминать попытку повернуть вектор вокруг начала координат наощупь. А неведомая хрень явно считается иначе :-).

dsd 19.06.2011 01:28

Ответ: Вопрос-Ответ (для новичков)
 
Хм... Интересно это векторное вращение меша? В общем так или иначе, но я прошел этот квест:)

Код:

Function VectorRoller(selectedmesh,alfa#,beta#,gama#)

surf=GetSurface(selectedmesh,1)
qverts=CountVertices (surf)

If selectedmesh<>controlofmeshidentity RuntimeError "Oopps, I'm trying to do something very wrong ^__^. Mmm... I meant that sourcemesh and preapered data is different. It's a fatal error :D."

For i=0 To qverts-1

;for simulation rotateentity
;x0#=saveddata#(i,0)
;y0#=saveddata#(i,1)
;z0#=saveddata#(i,2)

;for simulation turnentity
x0#=VertexX(surf,i)
y0#=VertexY(surf,i)
z0#=VertexZ(surf,i)

;alfa vocrug z
x1#=x0#*Cos(alfa)+y0#*Sin(alfa)
y1#=-x0#*Sin(alfa)+y0#*Cos(alfa)
z1#=z0#

;beta vokrug x

x2#=x1#
y2#=y1*Cos(beta)+z1*Sin(beta)
z2#=-y1*Sin(beta)+z1*Cos(beta)

;gama wokrug y
x3#=x2*Cos(-gama)+z2*Sin(-gama)
y3#=y2
z3#=-x2*Sin(-gama)+z2*Cos(-gama)

VertexCoords surf,i,x3,y3,z3

Next
UpdateNormals selectedmesh;it makes this function in two times slower
End Function


Nex 09.07.2011 05:50

Ответ: Вопрос-Ответ (для новичков)
 
Вложений: 1
Помогите с реализацией пошагового боя. :)
Я начал делать, когда у юнита заканчиваются очки действий происходит переключение на следующего, но "следующий" юнит никак не реагирует хотя вроде бы в коде все правильно сделал. :(

WhiteBlack 09.07.2011 19:10

Ответ: Вопрос-Ответ (для новичков)
 
а есть ли функция для рисования прямой в 3D пространстве?
или же надо использовать surface

NitE 09.07.2011 21:22

Ответ: Вопрос-Ответ (для новичков)
 
Nex, попробуй заюзать другую реализацию А*

Nex 10.07.2011 18:08

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от NitE (Сообщение 194877)
Nex, попробуй заюзать другую реализацию А*

Мля. Это самая нормальная что я нашел на Блитз. Есть еще наработка волнового алгоритма, но там я не вкурил как данные загнать к примеру в массив и потом их из массива использовать. =/

RegIon 11.07.2011 14:35

Ответ: Вопрос-Ответ (для новичков)
 
Код:

    For unit.unit = Each unit
        If gGameStarted = True And unit\pathAI = userControlled Then
          If unit\selected Then
                unit\oldX% = unit\xLoc
                unit\OldZ% = unit\yLoc

                walkability (unit\xLoc,unit\yLoc) =1
                If unit\xLoc <> unit\oldX Or unit\yLoc <> unit\oldZ Then walkability (unit\oldX,unit\oldZ) = 0
   
   
        ;    Player control

            PositionEntity unit\ent,unit\xLoc*MapScale,EntityY (unit\ent),unit\yLoc*MapScale
           
            If unit\action_points =0 Then
                For unit2.unit = Each unit
                ;    If unit\id+1 = unit2\id Then
                        unit2\selected = True
                        unit\selected = False
                    ;EndIf
                Next
                ;FreeBank unit\pathBank
                ;FreeEntity unit\ent
                ;Delete unit   
            EndIf
           
            If unit\xPath <> unit\oxPath Or unit\yPath <> unit\oyPath Then unit\action_points = unit\action_points -1 ;отнимаем очки действий
            unit\oxPath = unit\xPath
            unit\oyPath = unit\yPath
        EndIf
    EndIf
Next

нет действия для второго юнита....
сложно код построен....

KingMaks 21.07.2011 15:41

Ответ: Вопрос-Ответ (для новичков)
 
как в PhysX wrapper телу отключить коллизию с другими телами, но при этом оставить коллизию со статикой?

NitE 21.07.2011 16:34

Ответ: Вопрос-Ответ (для новичков)
 
Группы смотри.

Gector 21.07.2011 16:56

Ответ: Вопрос-Ответ (для новичков)
 
Цитата:

Сообщение от Мистер Розовый (Сообщение 196401)
как сделать hp в блице?

Смешно до слез прям... Ты смотри. А то забанят.


Часовой пояс GMT +4, время: 15:48.

vBulletin® Version 3.6.5.
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Перевод: zCarot