trensim.comSimulación Ferroviaria
   

Objetos versión "zero"

Objetos para incorporar a rutas de RailWorks.

Moderador: Moderadores

Re: Objetos versión "zero"

Notapor jjlor » Vie Nov 05, 2010 11:37 pm

A ver por donde empiezo:
Código: Seleccionar todo
verbose = true                  -- comment out or change to false to suppress verbose reporting in LogMate

-- configure the following according to your art asset

-- names of all the child blueprints representing animated gates
--gGates = { "Gate1", "Gate2" }
--gGateCount = 2                  -- be sure to match this with the number of entries in the line above

-- whether the gates are closed in their default position or open
--initiallyOpen = true            -- remove comment dashes if they are open initially

-- commenting out any of the following lines means that this feature is not present in the model
-- WARNING_ANIMATION = "warn"         -- the name of an optional animation played before the gates are closed
CLOSING_ANIMATION = "Stop"         -- the name of the animation moving the gates from open position to closed
CLOSED_ANIMATION = "closed"         -- the name of the optional animation plyed while the gates are closed
OPENING_ANIMATION = "Clear"         -- the name of the animation moving the gates from closed position to open


-- end of art asset configuration


-- Messages sent by the game core - we must handle these in OnSignalMessage
RESET_SIGNAL_STATE                        = 0
INITIALISE_SIGNAL_TO_BLOCKED                = 1
JUNCTION_STATE_CHANGE                     = 2
INITIALISE_TO_PREPARED                     = 3

-- Messages sent by signals to manage block occupation - unlikely to be relevant here
OCCUPATION_INCREMENT                     = 10
OCCUPATION_DECREMENT                     = 11

-- Messages announcing a coming train
SIGNAL_UNPREPARED                        = 18   -- actually the cancellation of a coming train
SIGNAL_PREPARED                           = 19   -- train coming
SIGNAL_PREPARED_VISIBLE                     = 20   -- same thing, as far as we are concerned

-- Animation phases
PHASE_WARNING   = 1      -- warning phase before starting to close
PHASE_CLOSING   = 2      -- animation to close them is running
PHASE_CLOSED   = 3      -- gates close
PHASE_OPENING   = 4      -- animation to open them is running
PHASE_OPEN      = 5      -- gates open

phaseName = {"warning", "closing", "closed", "opening", "open"}

-- Global variables
gOccupation      = 0                  -- total amount of train length within the links
-- moved to Initialise: gPhase         = PHASE_OPEN         -- default state is open
gInitialised    = false               -- only used on startup, to postpone initialisation of art asset
gUpdating      = false
gInitiallyBlocked = {}
-- moved to Initialise: gLinkCount      = 0

-- Called on startup
function Initialise()
   gInitialised = false
   if initiallyOpen then
      gPhase = PHASE_OPEN
   else
      gPhase = PHASE_CLOSED
   end
   gLinkCount = Call( "GetLinkCount" )
   for i = 0, gLinkCount - 1 do
      --Print (( "Initialise " .. i))
      gInitiallyBlocked[i] = false
   end
   -- When the route is loaded, the real initialisation will happen
   gUpdating = true
   Call( "BeginUpdate" )
end

   
-- Called pretty often while a train is within 100m form a link
function OnConsistPass( prevFrontDist, prevBackDist, frontDist, backDist, linkIndex )
      
   if (frontDist < backDist and prevFrontDist > prevBackDist) or
         (frontDist > backDist and prevFrontDist < prevBackDist) then
      local x = prevFrontDist            -- Train changed direction - swap previous ends
      prevFrontDist = prevBackDist      -- to simplify logic below
      prevBackDist = x
   end
   
   local length = backDist - frontDist
   if length < 0 then
      length = 0 - length
   end
   --Print ( ( "OnConsistPass: " .. frontDist .. " " .. prevFrontDist .. " " .. backDist .. " " .. prevBackDist ))
                                             -- positive distance = facing the signal front side
   if math.mod(linkIndex, 2) == 0 then                     -- link 0, 2, ... are located in approach to the crossing
      if frontDist < prevFrontDist then               -- moving forward
         if frontDist <= 0 and prevFrontDist > 0 then   -- just started crossing
            StartClosing(length)
         end
      else                                    -- moving backward
         if backDist >= 0 and prevBackDist < 0 then      -- just finished crossing
            StartOpening(length)
         end
      end
   else                                       -- link 1, 3, ... are located beyond the crossing
      if frontDist > prevFrontDist then               -- moving backward
         if frontDist >= 0 and prevFrontDist < 0 then   -- just started crossing
            StartClosing(length)
         end
      else                                    -- moving forward
         if backDist <= 0 and prevBackDist > 0 then      -- just finished crossing
            StartOpening(length)
         end
      end
   end
end

function OnSignalMessage( message, parameter, direction, linkIndex )
   VerbosePrint (( "OnSignalMessage " .. message .. " " .. parameter .. " " .. direction .. " " .. linkIndex ))
   
   -- There is a train approaching us when the route first loads
   if (message == INITIALISE_TO_PREPARED) then
   
      -- Do nothing while it is not here

   -- There is a train beyond one of the links when the route first loads
   -- The bad news is that we don't know how many they are, each train will send messages to 2 links, maybe more.
   elseif (message == INITIALISE_SIGNAL_TO_BLOCKED) then
      
      gInitiallyBlocked[linkIndex] = true      -- evaluation is performed in first Update

   -- There is a junction and it changed state (i.e., a switch was set).
   elseif (message == JUNCTION_STATE_CHANGE) then
   
      -- Currently, we just ignore this.
      -- With more information on the relative link positions, one could reason whether the approaching train can
      -- reach the crossing, i.e., whether it is relevant or not. But for such complex situations, distinct
      -- messager objects are much better.
      
   -- This message is sent after a scenario is reset
   elseif (message == RESET_SIGNAL_STATE) then
      
      -- We do nothing, hoping that the old state is still valid.
      -- If someone put a train on the crossing in scenario editor, we will not realise it. So be it.
      
   else
   
      -- Just forward the message
      Call( "SendSignalMessage", message, parameter, -direction, 1, linkIndex )
   
   end
end

function StartClosing(length)
   VerbosePrint (( "StartClosing " .. length ))
   if gOccupation > 0 then
      gOccupation = gOccupation + length
      -- do nothing else, current phases are neither OPEN nor OPENING
   else
      gOccupation = gOccupation + length
      
      gChange = true

      if not gUpdating then         -- don't call it if update is already active
         gUpdating = true
         Call( "BeginUpdate" )
      end
   end
end

function StartOpening(length)
   VerbosePrint (( "StartOpening " .. length ))
   gOccupation = gOccupation - length
   if gOccupation > 0.5 then                     -- round off residual train length, just to be on the safe side
      -- do nothing else, gates are kept closed
   else
      gOccupation = 0

      gChange = true
      
      if not gUpdating then         -- don't call it if update is already active
         gUpdating = true
         Call( "BeginUpdate" )
      end
   end
end

function Update( time )
   
   if not gInitialised then
      local blocked = false
      gInitialised = true
      for i = 0, gLinkCount - 1, 2 do
         --Print (( "Checking " .. i))
         if gInitiallyBlocked[i] and not gInitiallyBlocked[i+1] then
            blocked = true
         end
      end
      if not initiallyOpen and not blocked then
         gChange = true
      end
   end
   
   -- if a new phase was set by StartClosing or StartOpening
   if gChange then
      if gCurrentAnimation ~= nil then
         ResetAnimation(gCurrentAnimation)
         VerbosePrint( ("Reset " .. gCurrentAnimation) )
         gCurrentAnimation = nil
      end
   elseif gCurrentAnimation ~= nil then
      if (UpdateAnimation( gCurrentAnimation, time )) then
         VerbosePrint( ("Finished animating " .. gCurrentAnimation) )
         gCurrentAnimation = nil
         gChange = true
      end
   end
   
   if gChange then
      VerbosePrint (( "Leaving phase " .. phaseName[gPhase] ))
   end
   local oldPhase = gPhase
   
   if gChange and gPhase == PHASE_OPEN then         -- i.e. the closing process just started
      gPhase = PHASE_WARNING
      if WARNING_ANIMATION ~= nil then
         gCurrentAnimation = WARNING_ANIMATION
         ResetAnimation(gCurrentAnimation)
         gChange = false
      end
   end
   
   if gChange and gPhase == PHASE_WARNING then
      gPhase = PHASE_CLOSING
      if CLOSING_ANIMATION ~= nil then
         gCurrentAnimation = CLOSING_ANIMATION
         ResetAnimation(gCurrentAnimation)
         gChange = false
      end
   end
   
   if gChange and gPhase == PHASE_CLOSING then
      gPhase = PHASE_CLOSED
      if CLOSED_ANIMATION ~= nil then
         gCurrentAnimation = CLOSED_ANIMATION
         ResetAnimation(gCurrentAnimation)
      end
      gChange = false                           -- change is coming from train pass here
   end
   
   if gChange and gPhase == PHASE_CLOSED then
      gPhase = PHASE_OPENING
      if OPENING_ANIMATION ~= nil then
         gCurrentAnimation = OPENING_ANIMATION
         ResetAnimation(gCurrentAnimation)
         gChange = false
      end
   end
   
   if gChange and gPhase == PHASE_OPENING then
      gPhase = PHASE_OPEN
      gChange = false
      Call( "EndUpdate" )
      gUpdating = false
   end
   
   if oldPhase ~= gPhase then
      VerbosePrint (( "Entering phase " .. phaseName[gPhase] ))
   end
end

function SwitchLight( lightname, state )

   -- If this light node exists
   if lightname ~= nil then
      if gLights ~= nil then
         for i = 1, gLightCount do
            Call ( gLights[i] .. ":ActivateNode", lightname, state )
         end
      else
         Call ( "ActivateNode", lightname, state )
      end
   end
end

function ResetAnimation( animationname )

   -- If this animation exists (should always be the case)
   if animationname ~= nil then
      if gGates ~= nil then
         for i = 1, gGateCount do
            Call ( gGates[i] .. ":Reset", animationname )
         end
      else
         Call ( "Reset", animationname )
      end
   end
end

function UpdateAnimation( animationname, time )      -- returns true if animation completed
   local done
   local result
   
   if animationname ~= nil then
      if gGates ~= nil then
         for i = 1, gGateCount do
            result = Call ( gGates[i] .. ":AddTime", animationname, time )
            done = result ~= 0
         end
         --Print ( ( "UpdateAnimation ( " .. animationname .. ", " .. time .. " ) - " .. result ) )
         return done
      else
         return Call ( "AddTime", animationname, time ) ~= 0
      end
   end
end

function VerbosePrint ( test )
   if verbose then
      Print (( test ))
   end
end


Ese es el Script es el que trato de usar.
Tengo 3 animaciones creadas de las 4 posibles que se pueden poner( bajar barreras, animación mientras estan las barreras bajadas y subir barreras)
En este caso seria extender los cepillos, girar los cepillos y retraer los cepillos.
Las animaciones según el script se llaman "stop", "closed", "Clear y son con los nombres que tengo identificadas cada animación en el blueprint ( un blueprint de señal animada con un par de links para la vía según el sentido )

Creo que no se me olvida nada pero si falta algo preguntad que lo pongo.
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor Repo » Vie Nov 05, 2010 11:47 pm

Quedé igual. :mrgreen:

Estimado, ¿sería mucho pedir que me pudieras enviar el rwp del artilugio éste para hacerle algunas pruebas de campo in game?

No se si alguna vez te he pasado mi dirección de correo, si no, me la pides por MP.

Ojalá accedas.

Saludos.
Imagen
Avatar de Usuario
Repo
 
Mensajes: 1198
Registrado: Mar Oct 11, 2005 4:27 pm
Ubicación: Santiago de Chile

Re: Objetos versión "zero"

Notapor jjlor » Sab Nov 06, 2010 12:14 am

He detectado un error de escritura en el blueprint que arregla sólo uno de los problemas. En el nombre de referencia de una de las animaciones había una "s" en vez de una "S". Ya no me duplica los rodillos en dos posiciones al pasar el tren pero la animación internedia de cuando las barreras estan cerradas parece estar configurada para el uso de discos de luces que parpadean de un lado a otro porque la animación la ejecuta una vez si... pasa un rato, otra vez... asi hasta que pasa el tren por completo entre los dos marcadores de detección del tren. No se si eso ayudará en entender el código porque he buscado la sentencia que hace referencia a como se ejecutan las animaciones y no he encontrado nada que me aclare.
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor Repo » Sab Nov 06, 2010 12:28 am

Ok jjlor, recibí tu mensaje y te envié un correo.

Saludos.
Imagen
Avatar de Usuario
Repo
 
Mensajes: 1198
Registrado: Mar Oct 11, 2005 4:27 pm
Ubicación: Santiago de Chile

Re: Objetos versión "zero"

Notapor Repo » Sab Nov 06, 2010 9:57 pm

Ya jjlor, estaríamos listos con el script, tuve que crear un addon propio para hacer las pruebas, pero creo que mi código va a trabajar perfectamente con tus "lava trenes", eso si, vas a tener que retocar algunas cositas en las animaciones. Este script tuve que hacerlo completo desde cero y terminó teniendo muchas menos líneas que el original que estabas tratando de usar.

Voy ver si grabo un videito y lo subo en breve.

Saludos.
Imagen
Avatar de Usuario
Repo
 
Mensajes: 1198
Registrado: Mar Oct 11, 2005 4:27 pm
Ubicación: Santiago de Chile

Re: Objetos versión "zero"

Notapor jjlor » Sab Nov 06, 2010 10:51 pm

Gracias Repo, ya me dirás que modificaciones tengo que hacer en las animaciones y como adaptar mi modelo al script que has creado. :wink:
Realmente me gustaría saber crear mis propios scripts y aunque he programado en Visual Basic 6 algo y entiendo mas o menos todo lo que hace el código me falta saber como usar las funciones, que variables tienen, que argumentos se le pasan etc.
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor Repo » Sab Nov 06, 2010 11:08 pm

Ok jjlor, acá te muestro un video de como funciona mi objeto gobernado por el script que he creado. Podrás ver como el cepillo entra al acercarse el tren y sale al alejarse, las toperas que se ven marcan el lugar donde se han puesto los Links. También puedes apreciar que a la animación de rotación le he configurado por código aceleración y desaceleración, es decir, efecto de inercia.

Todos los paramétros como velocidad de inicio y termino del giro así como la velocidad constante durante el lavado del tren son configurables facilmente cambiando un par de números en el script.

Acá el video:



Acá le pequñisimo código que hace el trabajo:

Código: Seleccionar todo
function Initialise()


gVamos = 0
gVel = 0
gIncremento = 0
gTime = 0
gTimeOld = 0



Call( "BeginUpdate" )

end




function OnConsistPass( prevFrontDist, prevBackDist, frontDist, backDist, linkIndex )

   if (linkIndex == 0) then                     
      if frontDist < prevFrontDist then               
         if frontDist <= 0 and prevFrontDist > 0 then   
            gVamos = 1
         end
      end
   end


   if (linkIndex == 1) then                     
      if backDist < prevBackDist then               
         if backDist <= 0 and prevBackDist > 0 then   
            gVamos = 0
         end
      end
   end
   
   
   
   
   
   if (linkIndex == 1) then                     
      if frontDist > prevFrontDist then               
         if frontDist >= 0 and prevFrontDist < 0 then   
            gVamos = 1
         end
      end
   end


   
   if (linkIndex == 0) then                     
      if backDist > prevBackDist then               
         if backDist >= 0 and prevBackDist < 0 then   
            gVamos = 0
         end
      end
   end
   
   end
   

function Update (time)


if gVamos == 1 then
   Call("*:AddTime", "ataque", 0.01 )

   if gIncremento < 0.08 then
      gIncremento = gIncremento + 0.0002
   end
      Call("*:AddTime", "giro", gIncremento )
      gVel = gVel + gIncremento

      if gVel > 1 then
         Call("*:AddTime", "giro", -1 )
         gVel = 0
      end
end


if gVamos == 0 then
Call("*:AddTime", "ataque", - 0.01 )

   if gIncremento > 0 then
      gIncremento = gIncremento - 0.0001
   end
      Call("*:AddTime", "giro", gIncremento )
      gVel = gVel + gIncremento

      if gVel > 1 then
         Call("*:AddTime", "giro", -1 )
         gVel = 0
      end
ResetAnimation(giro)
end

end



Ideal sería si pudieramos conversar por MSN para explicarte que cosas hay que modificar en tu objeto, que por lo demás no son muchas, sólo detalles respecto a la cantidad de frames de las animaciones y a los nombres de los animID en el blueprint.

Si te parece bien me mandas un MP y te agrego.

Saludos.
Imagen
Avatar de Usuario
Repo
 
Mensajes: 1198
Registrado: Mar Oct 11, 2005 4:27 pm
Ubicación: Santiago de Chile

Re: Objetos versión "zero"

Notapor jjlor » Dom Nov 07, 2010 1:58 am

Bueno, con ayuda del script de Repo ya funciona el lavadero como debería ser. Ahora le quedan detalles para hacerlo más real como poner sonido y efecto de vapor de agua y chorritos de agua.
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor jjlor » Mié Nov 10, 2010 12:48 am

Hola a todos, mientras termino el lavadero de trenes, después de investigar el tema de sonidos para añadirlos a los objetos y que no queden tan estáticos, lo he puesto en practica haciendo esta pequeña cinta cargadora con sonido y texturas animadas.

Imagen

La publicaré en breve.
Espero que os gusten estas innovaciones :wink:
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor Adrián » Mié Nov 10, 2010 1:10 am

Que poco te gusta hacer trastos... :D
Avatar de Usuario
Adrián
 
Mensajes: 1657
Registrado: Mar Oct 12, 2004 7:06 pm

Re: Objetos versión "zero"

Notapor javierfl » Mié Nov 10, 2010 1:51 am

Va a ser útil esa cinta, que cargar el carbón en cestos desloma... :mrgreen:

Saludos:

Javier.-
Avatar de Usuario
javierfl
grupo TrenSim
 
Mensajes: 9620
Registrado: Sab Ago 30, 2003 11:23 pm
Ubicación: Ciudad Astur

Re: Objetos versión "zero"

Notapor locomoto » Mié Nov 10, 2010 12:16 pm

Mi reconocimiento por toda la labor de investigación que llevais a cabo para crear estos objetos funcionales cada vez más realistas y bonitos. :app: :app: :app:
locomoto
 
Mensajes: 527
Registrado: Mié Ene 28, 2009 8:50 pm

Re: Objetos versión "zero"

Notapor jjlor » Jue Nov 11, 2010 9:20 pm

Gracias al script de Repo y un poco de imaginación, este será el siguiente objeto interactivo que publique en breve:

Imagen

Se colocan dos marcadores como en los pasos a nivel a cierta distancia de la puerta para que al cruzarlos, la puerta se abra o se cierre según donde esté el tren.
- Cualquier cosa que conlleve un esfuerzo es digno de reconocimiento. -
ImagenImagen
Un saludo, Jose
Avatar de Usuario
jjlor
Bibliotecario
 
Mensajes: 2120
Registrado: Dom Sep 07, 2003 1:35 am
Ubicación: Madrid

Re: Objetos versión "zero"

Notapor Pere » Jue Nov 11, 2010 9:42 pm

:app: :app: :app: :app:

Como corre tu imaginación. ¡Fantástico!
Avatar de Usuario
Pere
grupo TrenSim
 
Mensajes: 5043
Registrado: Jue Ago 28, 2003 11:44 pm
Ubicación: Barcelona

Re: Objetos versión "zero"

Notapor portu » Jue Nov 11, 2010 9:43 pm

Ya te digo :app:
https://trainzportu.blogspot.com.es/
Imagen
Avatar de Usuario
portu
 
Mensajes: 879
Registrado: Sab Mar 29, 2008 12:30 am

AnteriorSiguiente

Volver a Objetos para rutas RW

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 11 invitados